LangSmith Tracing for a LangGraph App: Two Settings, @traceable, Tags and Metadata, and Filtering Runs by User and Version
A flight recorder for a planner, researcher and writer graph. Two lines in .env decide whether traces leave your machine, run_config adds the tags v1.3.0 and support-copilot plus a user id, and an offline trace tree shows the researcher as the slowest step, 350 tokens and a failing get_ticket call.
What you will learn
- Turn LangSmith tracing on and off with LANGSMITH_TRACING and LANGSMITH_API_KEY
- Attach a run name, tags and metadata to a LangGraph run so you can filter by user and app version
- Add your own Python functions to the trace tree with @traceable
- Read a trace tree offline to find the slowest step, the token total and a failing tool call
Before you start
- LangGraph Nodes, Edges and State
- Observability and Tracing for LLM Apps
When an agent gives a wrong or slow answer, you want to replay exactly what happened inside it. In this article we switch on LangSmith tracing for a small multi-agent support app, read a trace tree, find the slow step and the failing tool call, and filter runs by user and by app version. The graph runs on a scripted stand-in test model, so the code works without a model key. Only the LangSmith part needs your own LangSmith key.
A flight data recorder for agents
A plane has a flight data recorder. Every step of the trip is logged, so after a problem you can replay it. Our app is the plane: one request, "handle ticket T-100", goes through three agents, a planner, a researcher and a writer. Tracing is the recorder. For every step it writes down how long it took, how many tokens it used and whether a tool call failed. From that log you can answer real questions: which step was the slowest, and which user on which version sent this request?
The app we trace
agents_graph.py is a three-node LangGraph graph. TICKETS holds two made-up tickets, T-100 and T-200, and get_ticket is a tool that raises an error for an unknown id.
@tool
def get_ticket(ticket_id: str) -> str:
"""Look up a support ticket by id."""
if ticket_id not in TICKETS:
raise ValueError(f"Ticket {ticket_id} not found")
return TICKETS[ticket_id]
def get_model(replies: list[str] | None = None):
"""Test model reply source. Swap for init_chat_model(...) when you have a key."""
replies = replies or [
"Plan: look up the ticket, then write a short reply.",
"Hi, we found the issue with your reset email and have fixed it. Please try again.",
]
msgs = [
AIMessage(
content=text,
usage_metadata={
"input_tokens": 120 + 40 * i,
"output_tokens": 30 + 10 * i,
"total_tokens": 150 + 50 * i,
},
)
for i, text in enumerate(replies)
]
return GenericFakeChatModel(messages=iter(msgs))
Each scripted reply carries usage_metadata, so the test model reports tokens just like a real one: 150 for the first call and 200 for the second. These are example numbers, not a real bill.
def planner(state: State) -> State:
reply = model.invoke(f"Plan how to handle ticket {state['ticket_id']}")
return {"plan": reply.content}
def researcher(state: State) -> State:
time.sleep(ticket_delay) # stands in for a slow lookup
try:
notes = get_ticket.invoke({"ticket_id": state["ticket_id"]})
except ValueError as exc:
notes = f"lookup failed: {exc}"
return {"notes": notes}
def writer(state: State) -> State:
reply = model.invoke(f"Write a reply using: {state['notes']}")
return {"answer": reply.content}
The edges run START, planner, researcher, writer, END. If you need a refresher on nodes and edges, see LangGraph Nodes, Edges and State.
Two settings decide whether anything is sent
.env.example lists what tracing needs, with no secret in it: LANGSMITH_TRACING=false, an empty LANGSMITH_API_KEY and LANGSMITH_PROJECT=support-copilot-dev. Copy it to .env; your key goes only into that private copy.
import os
from dotenv import load_dotenv
load_dotenv()
DEFAULT_PROJECT = "support-copilot-dev"
def tracing_status() -> dict:
"""Return what LangSmith will do, without revealing the key."""
enabled = os.getenv("LANGSMITH_TRACING", "false").lower() == "true"
has_key = bool(os.getenv("LANGSMITH_API_KEY"))
return {
"tracing_requested": enabled,
"api_key_set": has_key,
"will_send_traces": enabled and has_key,
"project": os.getenv("LANGSMITH_PROJECT", DEFAULT_PROJECT),
}
01_check_tracing_env.py prints this dictionary. With the fresh copy:
tracing_requested False
api_key_set False
will_send_traces False
project support-copilot-dev
Traces are sent only when tracing is true and a key is set. Otherwise the same code runs and nothing leaves your machine.
Tags and metadata on every run
def run_config(user_id: str, app_version: str, tags: list[str] | None = None) -> dict:
"""Tags and metadata that let you filter runs by user and version in LangSmith."""
return {
"run_name": "support_copilot_request",
"tags": ["support-copilot", f"v{app_version}", *(tags or [])],
"metadata": {"user_id": user_id, "app_version": app_version},
}
The run name becomes the name of the trace in LangSmith. The tags are the app name and the version with a v in front. The metadata holds the user id and the version. Tags and metadata are what you filter on later. 02_run_graph.py passes this config to the graph:
graph = build_graph()
result = graph.invoke({"ticket_id": "T-100"}, config=run_config("user-42", "1.3.0"))
print("plan :", result["plan"])
print("notes :", result["notes"])
print("answer:", result["answer"])
plan : Plan: look up the ticket, then write a short reply.
notes : Customer cannot reset password; reset email never arrives.
answer: Hi, we found the issue with your reset email and have fixed it. Please try again.
The plan and the answer are test model replies. The notes came from the real get_ticket tool.
@traceable for your own functions
LangChain and LangGraph record their own steps. Your plain Python functions need the traceable decorator from the langsmith package to show up in the tree.
from langsmith import traceable
from agents_graph import build_graph
from tracing_config import run_config
@traceable(name="clean_ticket_id", run_type="chain")
def clean_ticket_id(raw: str) -> str:
return raw.strip().upper()
@traceable(name="handle_request", run_type="chain", tags=["support-copilot"],
metadata={"app_version": "1.3.0"})
def handle_request(raw_ticket: str, user_id: str) -> str:
ticket_id = clean_ticket_id(raw_ticket)
graph = build_graph()
result = graph.invoke({"ticket_id": ticket_id}, config=run_config(user_id, "1.3.0"))
return result["answer"]
if __name__ == "__main__":
print(handle_request(" t-100 ", user_id="user-42"))
The messy id " t-100 " gets cleaned to T-100, and the whole graph run sits inside the handle_request step. With tracing off, the decorators do nothing extra.
How a run becomes a trace
Read a trace tree on your own machine
Before sending anything, you can collect the same run objects LangSmith would receive. 04_local_trace_tree.py uses LangChain's RunCollectorCallbackHandler:
from langchain_core.tracers.run_collector import RunCollectorCallbackHandler
from agents_graph import build_graph
from tracing_config import run_config
def collect(ticket_id: str, user_id: str, version: str, delay: float = 0.0):
collector = RunCollectorCallbackHandler()
graph = build_graph(ticket_delay=delay)
cfg = run_config(user_id, version)
cfg["callbacks"] = [collector]
graph.invoke({"ticket_id": ticket_id}, config=cfg)
return collector.traced_runs[0]
def seconds(run) -> float:
return (run.end_time - run.start_time).total_seconds()
def walk(run, depth=0):
yield depth, run
for child in run.child_runs:
yield from walk(child, depth + 1)
def slowest_step(root):
return max(root.child_runs, key=seconds)
def token_total(root) -> int:
total = 0
for _, run in walk(root):
for gens in (run.outputs or {}).get("generations", []):
for gen in gens:
usage = (gen.get("message") or {}).get("kwargs", {}).get("usage_metadata")
if usage:
total += usage["total_tokens"]
return total
def failed_tool_calls(root):
return [r.name for _, r in walk(root) if r.run_type == "tool" and r.error]
The script runs T-100 for user-42 with a 0.3 second delay in the researcher (a stand-in for a slow lookup), prints the tree, and then runs the unknown ticket T-999 for user-7 on version 1.4.0 to get a failing tool call. In the recorded run, the parent support_copilot_request took about 306 ms, and the researcher alone about 302 ms, with get_ticket inside it. Timings differ a little on every run. The summary lines below the tree are:
tags : ['support-copilot', 'v1.3.0']
metadata : {'user_id': 'user-42', 'app_version': '1.3.0'}
slowest : researcher
tokens : 350
failed : ['get_ticket']
The slowest step is the researcher, which is the delay we added. The tokens add up to 150 + 200 = 350. And the failed list shows get_ticket from the T-999 run: the node caught the error and wrote "lookup failed" into its notes, so the graph finished, but the trace still marks the tool run as failed. The project's tests run the same checks offline: 7 passed.
Turn tracing on and read it in LangSmith
In your own .env, set LANGSMITH_TRACING=true and paste your LangSmith key on the next line. Run the check again and all three values are True. Then run 02_run_graph.py and 03_traceable_steps.py. The output looks the same as before, but both runs are now sent to LangSmith in the background.
On the Tracing page, the project support-copilot-dev appears with two traces: handle_request and support_copilot_request, each with its latency. Open support_copilot_request and you see:
- The parent run with six runs inside it: the three nodes, the two model calls with 150 and 200 tokens, and the
get_tickettool call. - The input of the whole request (ticket id T-100) and the output (answer, notes and plan).
- Click
get_ticketand you see exactly what it was called with,ticket_id: T-100, and the ticket text it returned. A failing tool call would show its error here.
Filter by tag and by user
Tick the tag v1.3.0 and only one trace is left. handle_request drops out because its own tags are only support-copilot. Then add a metadata filter, metadata.user_id is user-42, in the search box after the tag filter. It's still the same run, and now you know who sent it and on which version.
Change line 7 of 02_run_graph.py to run_config("user-7", "1.4.0") and run it again. The project now shows three traces. Tick v1.4.0 and filter on user-7, and only the new run is left. Its latency column read 0.17 seconds in the recorded run. With a real model, compare latency and token counts run by run to spot a slow or expensive version.
To stop sending, set LANGSMITH_TRACING=false. The key can stay in .env; will_send_traces becomes False. It's one line.
In a bigger app: the Support Copilot
The Support Copilot (a supervisor, a RAG agent, a ticket agent and a responder) uses the same switch, set from its settings at startup:
def setup_tracing() -> bool:
if not settings.langsmith_api_key:
return False
os.environ["LANGSMITH_API_KEY"] = settings.langsmith_api_key
os.environ["LANGSMITH_TRACING"] = "true"
os.environ["LANGSMITH_PROJECT"] = settings.langsmith_project
return True
There is no tracing code inside the agents. Every graph run gets a config with the tag support-copilot and the customer's email as metadata, so when a customer says the bot was wrong, one search shows every trace for that customer:
def config_for(thread_id: str, customer_email: str = "") -> dict:
"""thread_id for the checkpointer; tags and metadata so a trace can be found later (by customer, by app)."""
return {"configurable": {"thread_id": thread_id}, "tags": ["support-copilot"],
"metadata": {"customer_email": customer_email}}
Two steps in that app are plain Python, so they get @traceable: the knowledge-base search becomes a kb_search step (run_type="retriever"), and the MCP tool call becomes an mcp_call step (run_type="tool"), with process_inputs dropping the self argument so the trace shows only the tool name and its arguments. Offline, its show_trace.py script prints the same kind of tree: for "How long does standard shipping take?" the run takes about two and a half seconds, and the RAG agent alone takes 2,135 ms. For "Where is my order 1043?" the supervisor routes to the ticket agent instead, which takes 3,377 ms because it calls the MCP tools. The route decides the path, and the slow step stands out. The same project also runs a 20-case golden set against four evaluators; that part is in LangSmith Datasets and Experiments.
Common mistakes
- Setting the key but not the switch. Both
LANGSMITH_TRACING=trueand a key are needed. Print the status instead of guessing. - Printing or committing the key. Check whether it is set, never its value, and keep
.envout of git. - No tags or metadata. Without a version tag and a user id, a busy project is a wall of identical traces.
- Catching a tool error and forgetting it. The researcher caught the error, so the run "succeeded". Look for failed tool runs in the tree, not only failed requests.
- Plain Python steps missing from the tree. Wrap them with
@traceable, or a slow search looks like a slow model.
Quick recap
| Piece | Job |
|---|---|
LANGSMITH_TRACING + LANGSMITH_API_KEY | Both set: traces are sent to LANGSMITH_PROJECT |
run_config | Run name, tags (app, version) and metadata (user, version) |
@traceable | Puts your own functions into the trace tree |
| Trace tree | Each step with its time, tokens and errors |
| Filters | Tag v1.4.0 plus metadata.user_id finds one user's runs on one version |
For the ideas behind spans, redaction and sampling, see Observability and Tracing for LLM Apps.
Try it yourself
Raise the delay in 04_local_trace_tree.py to 1.0 second and add a delay to the writer too. Run it and check which step slowest_step picks. Then tag a run with an extra tag, such as run_config("user-42", "1.3.0", tags=["beta"]), and filter on it in LangSmith.
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
From ML Metrics to LLM Evals: Same Ruler, New Targets
Precision and recall don't disappear when you build with LLMs; they move. A spam filter at 0.75/0.75, precision@3 and recall@3 on six help-desk documents, exact match vs a key-fact check on two written answers, and the rubric that replaces a single label.
Why You Cannot Ship an LLM Feature Without an Eval: Five Parts, Three Graders, One Tiny Eval
A friendlier prompt looked better on three questions and broke on others. An eval catches that: a fixed set of cases, a grader, a pass rate and a threshold. A tiny Python eval scores two prompt versions on the same six questions: v1 passes 83% and ships, v2 passes 50% and is blocked.
Building a Golden Dataset for LLM Evals: Cases, a Schema, a Coverage Table and a Seeded Split
The answer key for a support bot: 24 cases in one JSONL file, from 12 past tickets, 8 edge cases and 4 attacks. A Pydantic schema catches 4 problems in a broken file, a stats table finds that payments and account have no hard case, and a seeded split gives the same 16 dev and 8 test cases every time.
Retrieval Evals: Score the Retriever With Recall@K, MRR and nDCG Before Blaming the Model
When a RAG answer is wrong, check the retriever first. Score two retrievers on 24 graded queries with Recall@5, MRR and nDCG@5: overall there's no clear winner (0.757 vs 0.819, 0.854 vs 0.826, 0.769 vs 0.782), but the paraphrase slice drops to about 0.5 for both, and one query scores zero everywhere.
