LangSmith: tracing, datasets and evaluation
- Advanced
- 40 min
- Lesson 5 of 7 in LangChain ecosystem
- Last verified
Select text in the lesson first to keep it with your note. With the keyboard, move focus here and press the button: the note goes with the section you are reading.
In this module
On this page
Before you start
- Completed:LangGraph: persistence, human approval and failure
- Completed:Observability and eval pipelinesProduction: cost, serving and observability
You will be able to
- Turn on tracing for LangChain and for plain code, add the tags, metadata and thread id that make traces searchable, and plan privacy, volume and flushing.
- Follow a method that takes you from a complaint to a failing run, classifies the cause and turns the failure into a test.
- Define dataset, example, split, reference output, experiment and evaluator, and choose an evaluator type for a given check.
- Say why an evaluation score may mislead, and name the checks that make it trustworthy: judge calibration, slices, repetitions and a hold-out set.
- Describe an automation rule and a release gate, and close the loop from production failure to dataset to experiment to release.
Last night’s wrong answer left no trail. Aarav cannot say which page he read from. Kavya cannot say which page she fetched. The dashboard says everything is fine.
Before lunch, Ananya adds a recorder to every step so it writes down what it received and what it sent on.
By evening there is a stack of traces, and she has circled the one that matters. What does she do with it so the same mistake cannot happen twice?
Concept
In the story, the recorder Ananya adds to every step is LangSmith. It is a platform for the working life of a model application: it records what happened (observability), tests whether a change is better (evaluation), and, in the next lesson, hosts the running agent. The docs describe it as covering agents built with any framework, so none of this requires LangChain.
This lesson has one thread: trace, then dataset, then experiment, then fix, then experiment again. A trace shows you what happened. A dataset turns a failure into a test case. An experiment tells you whether a change helped. A rule or gate stops the next regression. It builds on observability and evals in the production module; here the lesson is how this platform realises it, and the judgement calls underneath.
Why It Matters
Without a record, “the agent got it wrong” ends the investigation. With one, you can ask which step, which input, which tool result. And without a test set, every fix is a hope: you change a prompt, it works on the example you looked at, and you cannot say what it broke. Teams that run agents in production end up building both. The question is whether you build them deliberately.
Mental Model
Ananya’s method has three parts. The traces are everything that happened, in order. The datasets hold the cases worth keeping: each with the question that was asked and, where there is one, the right answer. The experiments take a version of the system, run it over the whole dataset, and score it.
Every serious mistake should travel from the tape to a card. That is how a one-off incident becomes a permanent test.
The vocabulary
The observability concepts page defines these terms; they are used exactly in interviews.
| Term | Meaning |
|---|---|
| Run | One unit of work: a model call, a retrieval, a tool call. Comparable to a span in OpenTelemetry |
| TraceTraceThe recorded path of one request through a system, with each stage's inputs, outputs, timing and cost. Traces hold user data and need privacy controls.Open the glossary entry | The collection of runs for one operation, tied together by a trace id. The docs state a cap of 25,000 runs per trace |
| Project | A container for the traces of one application or service |
| Thread | A sequence of traces from one multi-turn conversation, grouped by a thread_id metadata key |
| Feedback | A tag and score attached to a run, continuous or categorical |
| Tags and metadata | Strings and key-value pairs on runs, for filtering and grouping: version, environment, tenant |
SaaS traces are retained for 180 days from ingestion according to the docs read; examples saved to a dataset persist after the source trace is gone. That is one reason to move important failures into datasets.
Turning tracing on
For LangChain and LangGraph code, tracing is switched on with environment variables:
LANGSMITH_TRACING=true
LANGSMITH_API_KEY=<your key>
LANGSMITH_PROJECT=support-agent-prodWithout a project name, traces go to a project called default. Other variables name the workspace if your key spans several, and the endpoint for non-US regions. The docs also show wrapping specific calls so only those are traced, and a block that forces tracing off.
For code that does not use LangChain, you instrument it yourself: a decorator traces a function, a context manager traces a block, and a low-level run-tree API exists for custom cases. Integrations also exist for several model SDKs and agent frameworks.
# Illustrative, after the observability pages. Names and options change; check the SDK you install.
from langsmith import traceable
@traceable(run_type="chain", name="answer_question", tags=["rag"], metadata={"app_version": "1.4.2"})
def answer(question: str) -> str:
docs = retrieve(question) # decorate retrieve() too, as a retriever run
return generate(question, docs)Add tags and metadata on day one: app version, model, prompt version, tenant, environment. A trace you cannot filter by version is a trace you cannot use when a release goes wrong. For conversations, pass a thread id in metadata on every turn.
Operational questions interviewers ask:
- Flushing. In Python, tracing runs in a background thread, so a short-lived process can exit before traces are sent. The docs say to wait for tracers in a
finallyblock, or to make callbacks synchronous, and they recommend the synchronous setting in serverless environments. - Privacy. Traces contain prompts, retrieved text and tool arguments, and that is often personal or confidential. Environment flags hide all inputs or all outputs. An anonymizer built from regex rules or a function can redact patterns before data leaves. A per-function setting can process inputs and outputs for one traced function. Combine this with redaction middleware from lesson 2, and decide region and retention up front. Large payloads and complicated patterns can slow an anonymizer down.
- Volume. Tracing everything is expensive and often unnecessary. A common policy is to sample ordinary traffic and keep every error, every negative-feedback run and every run from a flagged tenant. The rules feature in the docs lets you act on a filtered sample.
- Distributed traces. If a request crosses services, the trace headers have to be passed along, or one request becomes several unrelated traces.
Debugging from a trace: a method
- Find the trace. Filter by error, high latency, negative feedback, tenant or tag.
- Read top down. Which run was slow, costly or wrong? Token counts and latency per run narrow it quickly.
- Look at each run’s exact input. The rendered prompt, the retrieved chunks, the tool arguments. In practice most failures are bad inputs rather than a bad model.
- Classify the cause. Retrieval miss, prompt or context bug, tool error, model reasoning error, routing error, a loop, a truncation.
- Reproduce, fix, and keep the case. Re-run the exact prompt, change one thing, then add the failing trace to a dataset so it becomes a regression test.
The same classification you used for harness failures applies: the harness lesson sorts failures into context, constraint, verification and planning layers. A trace is how you find out which layer broke.
Datasets and experiments
The evaluation concepts page defines the pieces.
- Dataset. A collection of examples used for evaluating an application.
- Example. An input, an optional reference output and optional metadata. The docs stress that reference outputs are not passed to your application. They exist for evaluators.
- Split. A named subset, such as hard cases, regressions or a category. One example can belong to several splits.
- Experiment. The result of evaluating one specific version of the application on a dataset. You run several to compare versions.
- Evaluator. A function (or a person) that scores an output.
Where examples come from: written by hand, copied from production traces, generated, or taken from public sets. Include hard and adversarial cases and a split for regressions, and track slices (language, tenant, intent) because an average hides a group that got worse.
# Illustrative, after the evaluate-an-application page.
def target(inputs: dict) -> dict: # the application version under test
return {"answer": answer(inputs["question"])}
def has_citation(inputs, outputs, reference_outputs): # a code evaluator
return "[source:" in outputs["answer"]
results = client.evaluate(
target,
data="support-regression-v3",
evaluators=[has_citation],
experiment_prefix="prompt-v7",
max_concurrency=4,
metadata={"models": ["provider:model-name"], "prompts": ["v7"]},
)An evaluator receives the example’s inputs, the application’s outputs and, if there is one, the reference outputs. The Python example on the docs page returns a boolean; other return shapes, such as a dictionary with a key and a score, exist in other examples. Check the SDK version you use.
Choosing an evaluator type (from the docs and the vault):
| Type | Best for | Watch out |
|---|---|---|
| Code | Format, schema validity, exact match, tool-call correctness, cost and latency thresholds | Brittle for open-ended text |
| LLM as judgeLLM-as-judgeUsing a model to score outputs against a rubric or pick the better of two. It scales, but has its own biases and must be validated against human labels.Open the glossary entry | Helpfulness, groundedness, tone against a rubric; can run without a reference | Bias toward long or first-placed answers, drift; calibrate it |
| Human | Ground truth, writing the rubric, calibrating the judge | Cost; reviewers disagree, so use annotation queues |
| Pairwise | Comparing two versions when absolute scores are noisy | Randomise the order |
For agents, score the trajectoryTrajectory evaluationJudging the steps an agent took, such as tool choices, cost and risk, in addition to its final result.Open the glossary entry (the tool calls and steps) as well as the final answer: right tools, right order, no redundant calls, inside the step budget. For retrieval-based systems, score retrieval and generation separately, as the RAG evaluation lesson does. The agent evaluation lesson, evaluating agents, has the method.
Offline and online evaluation
Offline evaluation runs on a dataset before you release: regression checks, comparisons, backtestingOffline evaluationRunning a fixed test set against a change before release. It catches regressions, including rare intents.Open the glossary entry. Online evaluation runs on live runs and threads from production tracing, with no reference outputs, so it can only check things that need none: format, groundedness against the retrieved context, refusal rate, signs of user frustration. The docs say reference outputs are used only offline. That is why you validate an online evaluator against human labels before you trust it, and why you read some of the low-scoring runs yourself.
| Aspect | Offline evaluation | Online evaluation |
|---|---|---|
| Runs on | A dataset, before release | Live production runs and threads |
| Reference outputs | Available | None |
| Can check | Correctness against a gold answer, regressions, version comparisons | Format, groundedness against retrieved context, refusal rate, user frustration |
| Used for | The release gate | Watching traffic after release |
Making evaluation trustworthy
A single number from a single run is an anecdote. Five habits make it evidence.
- Calibrate the judge. Label some examples by hand (the vault suggests 50 to 100), compare the judge to the labels and report agreement. Use a stronger or different model for judging, and prefer small scales or yes and no with a stated reason.
- Repeat runs for non-deterministic systems, and look at the spread. The tool for this in the SDK should be confirmed in your version (see the note above).
- Compare versions on the same examples and the same dataset version, and look at paired differences.
- Keep a hold-out set that you never tune on, so a score is not just memorisation of your own test.
- Watch for gaming. If you optimise against the judge, the judge’s quirks become the target. Re-check against human review from time to time.
Also treat cost and latency as metrics beside quality. A prompt that gains two points and doubles the bill is a decision, not a win.
A worked case. The judge says v2 beats v1 by six points, yet users complain. Candidates: the judge prefers longer answers and v2 is longer; the dataset does not contain what users now ask; v2 wins on average but loses on one slice, say a language; the judge is uncalibrated; the metric measures format, not usefulness. Each has a check: length-controlled comparison, a sample of recent production questions, slice breakdown, agreement with human labels, and a read of ten failures. One signal like “users complain” is a reason to look, not proof of which.
Rules, annotation and the release loop
An automation rule has an item type (individual runs, or whole threads once they go idle), a filter, a sampling rate and an action. The actions listed in the docs include: add to an annotation queue for human review; add to a dataset; trigger a webhook; run an online evaluator; run a custom code evaluator; and extend the retention of matching traces. A rule can be applied to past runs when it is created.
That is the plumbing for a loop:
A release gate is the rule in that diamond: before a prompt, model or tool change goes out, an offline experiment must beat the baseline on the agreed metrics with no slice worse, ideally run in the CI pipeline pinned to a specific dataset version so the test set does not shift under you. After release, online evaluators watch the live traffic. Dashboards and alerts exist in the product for traffic, errors, latency and cost; check the current docs for their exact scope.
LangSmith and the alternatives
Several other platforms cover tracing and evaluation, and you can emit OpenTelemetry-compatible traces to a general observability backend. A sound answer for an interview: use open formats where you can to avoid lock-in, and choose the platform whose evaluation and annotation workflow your team will actually use. Differentiators are depth with your framework, hosting and data-residency options, workflow ergonomics, price and retention.
Real-World Application
A user reports a wrong answer from yesterday. You filter traces by the user’s tenant and the thread id and open the one with the complaint. The retriever run returned three chunks; the third is the current policy, but the first two are the old one and the model followed the first. Cause: a retrieval and context problem, not a model problem. You reproduce it with the exact prompt, fix the retrieval filter, and add the trace to the regressions split with the right answer as the reference. The offline experiment shows the fix works and that no other split got worse. The change ships behind a gradual release, and an online evaluator that checks groundedness against the retrieved text keeps watching. The complaint is now a permanent test.
Interview Perspective
Expect: “Define run, trace, thread and project.”, “A user reports a wrong answer yesterday; walk from complaint to shipped fix with a regression test.”, “Your judge says v2 is six points better but users complain.”, “Online evaluators have no reference answers; what do you measure and how do you validate them?”, “How do you handle PII in traces?”
A strong answer for the walk-through: find the trace by metadata or feedback, inspect the run inputs, classify the cause, reproduce, add to a dataset, run a targeted evaluator, compare to baseline across slices, gate, release gradually, and monitor with an online evaluator.
Common mistakes: tracing without metadata; a dataset of only happy paths; trusting one judge score; comparing experiments on different dataset versions; tracing secrets to a third party without a policy; reading only the average; evaluating only the final answer of an agent; no link from a production failure to a dataset.
Provenance: Common industry pattern. These are the questions this topic tends to draw for agent and ML-platform roles; none is verified for a named company.
Practice Questions
- Basic: Define run, trace, thread and project.
- Intermediate: Build a 40-example evaluation for a support bot over a help centre: where the examples come from, three evaluators, and the slices.
- Advanced: Your judge says v2 beats v1 by six points but users complain. Give the reasons and the check for each.
- Product-Company: Design the release gate and gradual rollout for a prompt change that touches a fifth of traffic.
Activity
Pick an application you know. Write down five tags or metadata fields you would add to every trace, three things you must redact before tracing, and the trace filter you would use to find yesterday’s worst failure.
Homework
Write a one-page evaluation plan for a retrieval-based support bot. Include the dataset sources and splits, an evaluator for each of retrieval quality, answer quality and cost, how you would calibrate the judge, the repetitions and hold-out policy, the release gate with its thresholds, and the online checks that need no reference answer.
Quick Revision
- Run, trace, thread, project, feedback, tags, metadata. A trace is a tree of runs for one operation.
- Tracing on:
LANGSMITH_TRACING,LANGSMITH_API_KEY, optionalLANGSMITH_PROJECT. Plain code: decorator or context manager. - Add version, model, tenant and thread id from day one. Flush in short-lived processes. Redact before data leaves.
- Method: find, read top down, check exact inputs, classify, reproduce, add to a dataset.
- Dataset, example, split, experiment, evaluator. Reference outputs are for evaluators, not the application.
- Code, judge, human, pairwise. Score agent trajectories too.
- Trust: calibrate the judge, use slices, repeat runs, hold out a set, watch for gaming.
- Offline before release, online after, with no reference answer.
- Rule = filter + sampling + action. Gate = beat baseline, no slice worse.
Check yourself
- Walk-through: From a user complaint to a shipped fix with a regression test, naming the platform feature at each step.
- Variation: Repeat it for an agent that called the wrong tool, not one that retrieved the wrong page.
- Common misconception: “Tracing is the same as evaluation.” A trace records what happened; evaluation scores whether it was good.
Related
Resources & Further Reading
Checked sources to go deeper. The essential ones come first in each group.
Official documentation
OpenTelemetry GenAI Semantic Conventions (opens in a new tab)
A vendor-neutral convention for tracing model calls, useful when you want traces that are not tied to one platform.
Further reading
Your AI Product Needs Evals (opens in a new tab)Essential
A practitioner article on reading traces and writing fast checks that grow as new failures appear, which matches the failure-to-test loop of this lesson.
Demystifying evals for AI agents (opens in a new tab)
Explains grader types, repeated trials and reading transcripts for agent evaluations, which extends the trust habits here from single answers to agent runs.
Using LLM-as-a-Judge For Evaluation: A Complete Guide (opens in a new tab)
A practical guide to building and checking an LLM judge, the next step after the calibration habit in this lesson.
Hands-on
langchain-ai/langsmith-python (GitHub repository) (opens in a new tab)
The Python SDK source, including the decorator, the client and the evaluation functions used in the code slides.
More for this module: LangChain ecosystem resources
Practice
Test what you just read. Quizzes and cards are grouped by module: LangChain ecosystem.
Check yourself14 questions on what this lesson set out to teach
Checking answers needs JavaScript. You can still read every question and option below.
Keyboard: arrow keys move between options. Space or Enter selects the focused option.