LangSmith: tracing, datasets and evaluation

  • Advanced
  • 40 min
  • Lesson 5 of 7 in LangChain ecosystem
  • Last verified

Open slides(29 slides)

Before you start

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.

Diagram: One thread runs through the lesson.

Trace
what happened

Dataset
keep the failure as a test case

Experiment
does a change help?

Fix

Experiment again

Rule or release gate
stop the next regression

Diagram summary: One thread runs through the lesson. A trace shows what happened, a dataset turns a failure into a permanent test case, an experiment measures whether a change helped, and a rule or release gate stops the same regression from returning.

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.

TermMeaning
RunOne 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 entryThe collection of runs for one operation, tied together by a trace id. The docs state a cap of 25,000 runs per trace
ProjectA container for the traces of one application or service
ThreadA sequence of traces from one multi-turn conversation, grouped by a thread_id metadata key
FeedbackA tag and score attached to a run, continuous or categorical
Tags and metadataStrings and key-value pairs on runs, for filtering and grouping: version, environment, tenant
Diagram: A project holds traces; a trace is a tree of runs for one operation; a thread groups traces from the same conversation; feedback attaches...

Project: one app or environment

Trace: one end-to-end operation

Run: chain

Run: retriever

Run: model call

Run: tool

Thread: a conversation

Feedback: score or label

Diagram summary: A project holds traces; a trace is a tree of runs for one operation; a thread groups traces from the same conversation; feedback attaches to an individual run.

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-prod

Without 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.

Python

# 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 finally block, 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

  1. Find the trace. Filter by error, high latency, negative feedback, tenant or tag.
  2. Read top down. Which run was slow, costly or wrong? Token counts and latency per run narrow it quickly.
  3. 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.
  4. Classify the cause. Retrieval miss, prompt or context bug, tool error, model reasoning error, routing error, a loop, a truncation.
  5. 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.
Diagram: Start from a filtered trace, read down to the run that went wrong, look at its exact input, and classify the cause.

Find the trace:
filter by error, latency, feedback, tag

Read top down:
which run was slow, costly or wrong?

Look at that run's exact input:
rendered prompt, chunks, tool arguments

Classify the cause

Retrieval miss

Prompt or context bug

Tool error

Model reasoning error, routing, loop, truncation

Fix one thing, then add the failing trace
to a dataset as a regression test

Diagram summary: Start from a filtered trace, read down to the run that went wrong, look at its exact input, and classify the cause. Whatever the cause, change one thing and save the failing trace as a dataset example so it becomes a permanent 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.
Diagram: A dataset’s examples feed one version of the application, and the outputs are scored by evaluators.

reference outputs go only to evaluators

Dataset
examples: input, optional reference output, metadata

Run one version
of the application

Outputs

Evaluators
(also see the reference outputs)

Experiment: scores for this version

Diagram summary: A dataset’s examples feed one version of the application, and the outputs are scored by evaluators. The reference outputs are never passed to the application, only to the evaluators. The result is an experiment, which you compare across versions.

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.

Python

# 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):

TypeBest forWatch out
CodeFormat, schema validity, exact match, tool-call correctness, cost and latency thresholdsBrittle 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 entryHelpfulness, groundedness, tone against a rubric; can run without a referenceBias toward long or first-placed answers, drift; calibrate it
HumanGround truth, writing the rubric, calibrating the judgeCost; reviewers disagree, so use annotation queues
PairwiseComparing two versions when absolute scores are noisyRandomise 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.

AspectOffline evaluationOnline evaluation
Runs onA dataset, before releaseLive production runs and threads
Reference outputsAvailableNone
Can checkCorrectness against a gold answer, regressions, version comparisonsFormat, groundedness against retrieved context, refusal rate, user frustration
Used forThe release gateWatching traffic after release

Making evaluation trustworthy

A single number from a single run is an anecdote. Five habits make it evidence.

  1. 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.
  2. 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).
  3. Compare versions on the same examples and the same dataset version, and look at paired differences.
  4. Keep a hold-out set that you never tune on, so a score is not just memorisation of your own test.
  5. 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:

Diagram: Production runs are traced and scored; bad ones go to human review and then into a dataset; a candidate fix is tested on that dataset...

yes

no

Production traffic

Traces and online evaluators

Low score or negative feedback

Annotation queue

Dataset

Experiment on the candidate fix

Beats baseline, no slice worse?

Release gradually

Change prompt, tools or retrieval

Diagram summary: Production runs are traced and scored; bad ones go to human review and then into a dataset; a candidate fix is tested on that dataset against the baseline; only a version that wins and does not regress a slice is released, gradually, and monitored again.

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, optional LANGSMITH_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.

Resources & Further Reading

Checked sources to go deeper. The essential ones come first in each group.

Official documentation

Further reading

Hands-on

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.

0 of 14 answered

Keyboard: arrow keys move between options. Space or Enter selects the focused option.

ObjectiveTurn 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.

  1. Question 1 of 14In the platform's data model, which description of a trace is correct?

    Choose one answer.

  2. Question 2 of 14A LangGraph agent runs in production and no code change is allowed. How is tracing switched on?

    Choose one answer.

  3. Question 3 of 14A serverless function calls a traced chain and returns. Some traces never appear. What is the likely cause and fix?

    Choose one answer.

  4. Question 4 of 14Prompts and retrieved text in traces contain customer emails. Which is the most direct control over what leaves your system?

    Choose one answer.

ObjectiveFollow a method that takes you from a complaint to a failing run, classifies the cause and turns the failure into a test.

  1. Question 5 of 14A user complains about yesterday's answer. After finding the trace, what should you look at first inside it?

    Choose one answer.

  2. Question 6 of 14You have reproduced the failure and fixed the retrieval filter. What turns this one-off incident into protection against a repeat?

    Choose one answer.

ObjectiveDefine dataset, example, split, reference output, experiment and evaluator, and choose an evaluator type for a given check.

  1. Question 7 of 14What is the purpose of a reference output on a dataset example?

    Choose one answer.

  2. Question 8 of 14Which evaluator type fits "the reply must be valid JSON and must include a source field"?

    Choose one answer.

  3. Question 9 of 14An agent answers correctly but called the search tool nine times where two would do. Which evaluation catches this?

    Choose one answer.

ObjectiveSay why an evaluation score may mislead, and name the checks that make it trustworthy: judge calibration, slices, repetitions and a hold-out set.

  1. Question 10 of 14A judge model scores version 2 six points above version 1, but users complain. Which first check best tests whether the judge is the problem?

    Choose one answer.

  2. Question 11 of 14Why compare two versions on the same examples and look at slices as well as the average?

    Choose one answer.

  3. Question 12 of 14Online evaluators run on live traffic. What limits what they can check?

    Choose one answer.

ObjectiveDescribe an automation rule and a release gate, and close the loop from production failure to dataset to experiment to release.

  1. Question 13 of 14Which statements describe an automation rule in the platform? Select all that apply.

    Choose all that apply.

  2. Question 14 of 14A team wants a release gate for prompt changes. Which design is the strongest?

    Choose one answer.