Lesson 8 of 9 · Composition
Tracing With LangSmith
Trace LangChain apps with LangSmith: enable tracing, read run trees, add names, tags and metadata, use @traceable, hide private data and debug with traces.
- 8 min read
- Intermediate
- Reviewed
- Turn on LangSmith tracing for a LangChain application
- Read a trace as a tree of runs
- Add run names, tags and metadata to make traces searchable
- Trace your own Python functions with @traceable
- Keep private data out of traces, and control volume with sampling
Seeing inside a chain
A RAG chain has a retriever, a prompt, a model and a parser. When an answer is wrong, which step went wrong? Did the retriever miss the right chunk, or did the model ignore it? Tracing records every step so you can look (the AI Agent Evaluation course explains traces and spans in general).
Turning tracing on
Create a LangSmith account and an API key, then set environment variables before your program starts:
export LANGSMITH_TRACING=true
export LANGSMITH_API_KEY="your-key"
export LANGSMITH_PROJECT="bike-shop-assistant" # optional: groups traces by projectThat's all. Every LangChain call your program makes, including chains, models, retrievers, tools and agents, is now recorded as a trace in that project, with inputs, outputs, timings, token counts and errors. No code changes are needed.
What a trace records
A trace is a tree of runs: the chain is the parent, and its steps are children. Here's the idea in plain Python, with a decorator that records each call, its inputs, its output and its parent:
import functools, itertools
# What tracing records, in plain Python: a decorator that logs each call as a run,
# with its inputs, output, parent run and tags, so nested calls form a tree.
RUNS, STACK, IDS = [], [], itertools.count(1)
def traceable(name=None, tags=()):
def wrap(fn):
@functools.wraps(fn)
def inner(*args, **kwargs):
run = {"id": next(IDS), "name": name or fn.__name__, "tags": list(tags),
"parent": STACK[-1]["id"] if STACK else None, "inputs": args, "error": None}
RUNS.append(run)
STACK.append(run)
try:
run["output"] = fn(*args, **kwargs)
return run["output"]
except Exception as e:
run["error"] = repr(e)
raise
finally:
STACK.pop()
return inner
return wrap
@traceable(name="retrieve")
def retrieve(q):
return ["returns-policy.md"]
@traceable(name="model")
def model(prompt):
return "30 days [returns-policy.md]"
@traceable(name="rag", tags=["support"])
def rag(question):
docs = retrieve(question)
return model(f"Context: {docs}\nQuestion: {question}")
rag("How long can I return a bike?")
def show(parent=None, depth=0):
for r in (r for r in RUNS if r["parent"] == parent):
print(" " * depth + f"{r['name']} in={r['inputs'][0]!r:.35} out={r.get('output')!r}")
show(r["id"], depth + 1)
show()In LangSmith you see the same tree in a web interface, and you can click any run to see its exact inputs and outputs. For a RAG question, that means seeing which chunks were retrieved and the exact prompt the model received, which usually answers “why did it say that?” in seconds.
Names, tags and metadata
Traces become far more useful when you can find and group them. Pass a config when you invoke any Runnable:
answer = rag.invoke(
"How many days do I have to return a bike?",
config={
"run_name": "returns-question", # the name shown in the trace list
"tags": ["rag", "returns"], # filter traces by tag
"metadata": {"user_id": "u-17", "prompt_version": "v3"},
},
)
print(answer)You can return a bike within 30 days of delivery for a full refund [returns-policy.md].
run_namereplaces a generic name like “RunnableSequence” with something meaningful.tagslet you filter: allreturnsquestions, all runs of promptv3.metadatastores details such as the user ID (a pseudonymous one) or the prompt version, so you can search and compare later.
Tracing your own code
Not everything is a LangChain component. The @traceable decorator from the langsmith package records any Python function as a run, nested correctly under whatever called it:
from langsmith import traceable
@traceable(name="classify_ticket")
def classify(ticket: str) -> str:
return "billing" if "charged" in ticket.lower() else "repairs"
@traceable(name="handle_ticket", tags=["support"], metadata={"prompt_version": "2026-11"})
def handle_ticket(ticket: str) -> str:
category = classify(ticket) # traced as a child of handle_ticket
return f"Routed to {category}"
print(handle_ticket("I was charged twice for order 881."))Routed to billing
With tracing turned on, handle_ticket appears as a parent run with classify_ticket as its child, along with any LangChain calls made inside them. Without the environment variables, the decorator does nothing and the function runs normally.
Common mistakes
Use tags on traced runs to compare two prompt versions, the kind of question tracing tools answer with a filter.
# Runs exported from a tracing tool: name, tags and the tokens each one used
runs = [
{"name": "rag", "tags": ["support", "v2"], "tokens": 1850},
{"name": "rag", "tags": ["support", "v3"], "tokens": 1240},
{"name": "summarise", "tags": ["newsletter"], "tokens": 900},
{"name": "rag", "tags": ["support", "v3"], "tokens": 1310},
]
# Compare prompt versions: for the tags "v2" and "v3", print the average tokens of runs
# with that tag, rounded to a whole number, in the form: v9: 1000
What do you need to change in a LangChain application's code to trace its chains in LangSmith?
Summary
- LangSmith records LangChain runs as traces: trees of runs with inputs, outputs, timings and tokens.
- Turn it on with
LANGSMITH_TRACING,LANGSMITH_API_KEYand optionallyLANGSMITH_PROJECT. - Use
run_name,tagsandmetadatainconfigto make traces searchable and comparable. @traceabletraces your own functions, nested under their callers.- Protect privacy with hidden inputs and outputs or redaction, and control volume with sampling.
Next: the project, a RAG chatbot with LangChain.
Finished reading? Tick it off to track your progress.