Slides · LangChain ecosystem

LangSmith: tracing, datasets and evaluation

LangSmith: tracing, datasets and evaluation

How to see what an agent did, turn a failure into a permanent test, and decide whether a change is really better before it ships.

By the end you can trace safely, debug from a trace, build an experiment, judge whether a score deserves trust, and close the loop from production back to a release gate.

Concept

One wrong answer, no trail

Last night’s answer was wrong. Nobody can say which page was read, which was fetched, or why. The dashboard says all is well.

  • A recorder on every step gives the team the trace, and one trace is circled.
  • The question is what to do with it so the same mistake cannot happen twice. The next slide shows the answer: a path from trace to gate.

Diagram

The thread of the lesson

Diagram: A trace shows what happened, a dataset keeps the failure as a test, and experiments measure a fix.

Trace: what happened

Dataset: keep the case

Experiment: did it help

Fix

Experiment again

Rule or release gate

Diagram summary: A trace shows what happened, a dataset keeps the failure as a test, and experiments measure a fix. A rule or release gate then stops the regression returning.

Compare

The vocabulary, as the docs define it

TermMeaning
RunOne unit of work, such as a model call, prompt formatting or a retrieval. Comparable to a span in OpenTelemetry
TraceThe runs for one operation, bound by a trace id
ThreadA sequence of traces from one multi-turn session; group them by passing a thread_id metadata key
ProjectA container for the traces of one application or service (project-based workspaces; agent-based workspaces group traces by agent and environment instead)
FeedbackA tag and a score on one run, continuous or categorical
Tags and metadataStrings and key-value pairs on runs, for filtering and grouping

The docs name tags and metadata such as application version or environment as the way to filter and group runs.

Limits that shape what you keep: a trace holds at most 25,000 runs. On the hosted (SaaS) service, the usage page lists a base retention of 14 days and an extended retention of 180 days, and says most traces use base retention. Automation rules and online evaluators can upgrade a trace to extended. Datasets are kept indefinitely, so copy important failures into a dataset. Add version, model, tenant and environment as tags or metadata from day one, and pass the thread id on every turn (course guidance on top of the docs).

Sources1 Observability concepts (LangSmith documentation)2 Usage and billing (LangSmith documentation)

Diagram

How the pieces nest

Diagram: A project holds traces and a trace is made of runs for one operation.

Project

Trace: one operation

Thread: a conversation

Run: retriever

Run: model call

Run: tool

Feedback: score

Diagram summary: A project holds traces and a trace is made of runs for one operation. A thread groups the traces of one conversation, and feedback attaches to an individual run.

Source1 Observability concepts (LangSmith documentation)

Code

Turning tracing on

For LangChain and LangGraph, environment variables are enough:

LANGSMITH_TRACING=true
LANGSMITH_API_KEY=<your key>
LANGSMITH_PROJECT=support-agent-prod

LANGSMITH_PROJECT applies to project-based workspaces; agent-based workspaces organise traces by agent and environment. Without a project name, traces go to a project called default. LANGSMITH_WORKSPACE_ID is needed only if the key spans several workspaces, and LANGSMITH_ENDPOINT for accounts outside the default region, which the docs call US (the endpoints table lists endpoints for GCP US, GCP EU, GCP APAC and AWS US). For code outside those frameworks the docs name a decorator, a context manager and a low-level run-tree API.

Python

import langsmith as ls
from langsmith import traceable

@traceable(run_type="chain", name="answer_question", tags=["rag"],
           metadata={"app_version": "1.4.2"},
           process_inputs=lambda inputs: {"question": "<hidden>"})
def answer(question: str) -> str:
    return question[::-1]

answer("abc", langsmith_extra={"metadata": {"thread_id": "conv-1"}})
with ls.tracing_context(enabled=False):     # skip tracing for calls inside
    answer("xyz")

Run on 2026-10-24 with langsmith 0.14.12 and tracing switched off: the decorator accepted these arguments and the calls returned cba and zyx. Sending to the platform needs an API key and was not tested.

Sources3 Trace LangChain applications (Python and JS/TS) (LangSmith documentation)1 Observability concepts (LangSmith documentation)

Concept

Short-lived processes can exit before traces are sent

  • Tracing runs in a background thread, so a process may end before its traces post. The docs flag serverless environments as the likely place.
  • Python fix: call wait_for_all_tracers() in a finally block.
  • Or make callbacks synchronous by setting LANGCHAIN_CALLBACKS_BACKGROUND to false. The serverless recommendation to use the synchronous setting appears in the docs’ LangChain.js note; the Python section only describes the option.
  • Trade-off: synchronous sending waits on the network, so each call is slower.

Source3 Trace LangChain applications (Python and JS/TS) (LangSmith documentation)

Compare

Privacy: what leaves your system

ControlWhat it doesWatch out
LANGSMITH_HIDE_INPUTS, LANGSMITH_HIDE_OUTPUTSHide all inputs or all outputsHides what you need for debugging too
create_anonymizer with regex pairs or a functionReplaces matching text before it is sentOnly catches patterns you wrote; large payloads and complex patterns slow it
process_inputs, process_outputs on a traced functionTransforms the data of one functionApplies to that function only

Precedence, tested on 2026-10-24 (langsmith 0.14.12): the environment flags apply only when the Client has no hide_inputs function of its own. A true flag sends {}. With a client hide_inputs function plus an anonymizer, the anonymizer’s output is sent. A process_inputs function runs first and the client-level hiding then runs on its result, so a true flag still gives {}. The docs describe function-level processing as taking precedence, so test your own combination. Decide region and retention up front as well.

Source4 Prevent logging of sensitive data in traces (LangSmith documentation)

Code

A redaction rule only catches what it describes

Python

from langsmith.anonymizer import create_anonymizer

anon = create_anonymizer([
    {"pattern": r"[\w.+-]+@[\w-]+\.[\w.]+", "replace": "<EMAIL>"},
    {"pattern": r"\b\d{4}-\d{4}-\d{4}-\d{4}\b", "replace": "<CARD>"},
])
anon({"messages": [{"role": "user", "content":
      "I am Priya Nair, mail priya.nair@example.com, card 4111-1111-1111-1111, order 8841"}]})
anon({"q": "card 4111 1111 1111 1111"})
anon({"q": "card 4111111111111111"})

Results on 2026-10-24 (langsmith 0.14.12, test card number):

Input textOutput
Name, email, hyphenated card, order numbername kept, <EMAIL>, <CARD>, order kept
Card written with spacesunchanged
Card as 16 digits, no separatorunchanged

The name and the spaced card number went through. A pattern only protects the formats you listed. Pair patterns with a policy for what is traced at all.

Source4 Prevent logging of sensitive data in traces (LangSmith documentation)

Check yourself

Check: is the rule enough

A team ships the two-pattern anonymizer above to production and reports “traces are now safe”. Name two gaps and one change for each.

Answer

Gap one: formats the patterns do not describe, such as a card typed with spaces or without separators, or a name in free text. The email pattern shown also swallows a trailing full stop. Change: widen the card pattern to take an optional separator, such as \b(?:\d{4}[ -]?){3}\d{4}\b (tested: it replaces the hyphenated, spaced and unseparated forms), and add a name-detection step through the function form of the anonymizer. Gap two: nobody has measured what still leaks. Change: run the rule over a sample of real prompts, read what remains, and hide inputs entirely for the flows that carry the most sensitive text. The docs also warn that the anonymizer serialises the whole payload, so measure its overhead on large traces.

Source4 Prevent logging of sensitive data in traces (LangSmith documentation)

Worked example

Worked example: review volume with sampling rules

An automation rule has a filter and a sampling rate: the share of filtered items that trigger the action. Illustrative day: 10,000 traces, filtered on each trace’s root run (one per trace), of which 600 ended in an error.

RuleFilterSamplingActionRoot runs per day
1error100%Add to annotation queue600
2no error5%Add to annotation queue470
Total1,070

Rule 2 applies to 9,400 root runs: 9,400×0.05=4709{,}400 \times 0.05 = 470. A queue of 1,070 items is 10.7 percent of traffic. If one reviewer can read about 150 items a day (an assumed figure), that queue needs roughly 7 reviewer-days, so lower the rate, narrow the filter, or let an online evaluator pre-screen. Tracing everything and reviewing a sample is a course policy, not a documented default.

Source5 Set up automation rules (LangSmith documentation)

Process

From a complaint to a failing run

  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?
  3. Open what that run was handed: the prompt as rendered, the chunks it retrieved, the arguments it passed to tools.
  4. Classify the cause: retrieval miss, prompt or context bug, tool error, model reasoning error, routing error, a loop, a truncation.
  5. Reproduce the failure, change a single thing, then save the trace into a dataset so the case is tested every time.

Steps 3 and 5 carry the weight. A common pattern is to check the inputs before blaming the model, and a fix without a saved case can quietly regress.

Check yourself

Check: classify this trace

A user asks about the return window for sale items. The trace tree shows the retriever run returned zero chunks, then the model run produced a confident 30-day answer, and no tool ran. The real policy is 14 days. Where did the failure start, what second defect is visible, and what do you save?

Answer

It started in retrieval: nothing came back, so the model had no policy text. The second defect is in the prompt or context design: the model answered without grounding instead of saying it had no source. Save the question with the correct 14-day answer as a reference output, in a split such as regressions. Fix retrieval first (query or index), then add a check that an empty retrieval produces a refusal or a handoff, and test both on the dataset.

Compare

Dataset, example, split, experiment

TermMeaning
DatasetA collection of examples used to evaluate an application
ExampleInputs, optional reference outputs and optional metadata
Reference outputThe expected answer. It is not passed to your application, only to evaluators
SplitA named subset, such as regressions or a category. One example can sit in several splits
ExperimentThe results of one application version on a dataset: outputs, scores and traces
EvaluatorA function or a person that scores an output

Source6 Evaluation concepts (LangSmith documentation)

Diagram

What an experiment is made of

Diagram: The examples feed one version of the application and its outputs go to evaluators.

reference outputs

Dataset: examples

Run one app version

Outputs

Evaluators

Experiment: scores

Diagram summary: The examples feed one version of the application and its outputs go to evaluators. The reference outputs go only to the evaluators, never to the application. The scores form an experiment that you compare across versions.

Source6 Evaluation concepts (LangSmith documentation)

Code

Running an experiment

Python

from langsmith import evaluate

def target(inputs: dict) -> dict:
    return {"answer": inputs["question"].upper()}     # stand-in for the app version

def exact(inputs, outputs, reference_outputs):
    return outputs["answer"] == reference_outputs["label"]

def length(inputs, outputs, reference_outputs):
    return {"key": "length", "score": len(outputs["answer"])}

results = evaluate(target, data=examples, evaluators=[exact, length],
                   num_repetitions=2, max_concurrency=2,
                   experiment_prefix="v7", upload_results=False)

examples is built like this; in a project you pass a dataset name instead:

Python

import uuid, datetime
from langsmith.schemas import Example

def make_example(q, label):
    return Example(id=uuid.uuid4(), dataset_id=uuid.uuid4(), created_at=datetime.datetime.now(datetime.timezone.utc),
                   inputs={"question": q}, outputs={"label": label})

examples = [make_example("a", "A"), make_example("b", "B"), make_example("c", "X")]

upload_results=False keeps the run local; the installed SDK marks that option as beta. The docs show a code evaluator that returns a boolean, and the SDK also accepted a dictionary with a key and score.

Result on 2026-10-24 (langsmith 0.14.12): 6 rows (3 examples×2 repetitions3\ \text{examples} \times 2\ \text{repetitions}), 4 passes of exact and 2 failures, both for the example labelled X. The evaluate page does not show num_repetitions; the separate repetitions page does.

Sources7 How to evaluate agents (LangSmith documentation)8 How to evaluate with repetitions (LangSmith documentation)

Compare

Choosing an evaluator type

TypeBest forWatch out
CodeDeterministic rules: format, exact match, non-empty outputBrittle for open-ended text
LLM as judgeCriteria in a prompt; can be reference-free or reference-basedNeeds careful score review and prompt tuning
HumanA common starting point; builds the rubric and the labelsCost; use annotation queues
PairwiseComparing two versions when that is easier than scoring eachRandomise the order (course advice)
Decision modelA decision model as judge, answering typed questions (such as a probability) instead of using a prompt and output schemaEach answer becomes its own feedback item

For agents, the docs suggest also checking the trajectory the agent took, meaning its sequence of steps, not only the final answer.

Source6 Evaluation concepts (LangSmith documentation)

Check yourself

Check: match the check to the evaluator

Choose code, LLM judge or pairwise for each: (a) the reply is at most 120 words; (b) the reply sounds calm and empathetic to an upset customer; (c) of two prompt versions, which reads better; (d) the reply names a policy section id that appears in the retrieved text.

Answer

(a) Code: counting words is deterministic. (b) LLM judge with a rubric, calibrated against human labels, because tone has no exact rule. (c) Pairwise, with the order of the two replies randomised, since comparing is easier than scoring each. (d) Code: compare the cited id against the retrieved chunks; no model is needed. Use code wherever a rule exists and a judge where only judgement can decide.

Source6 Evaluation concepts (LangSmith documentation)

Compare

Offline and online evaluation

AspectOfflineOnline
Runs onA dataset, before deploymentProduction runs and threads
Reference outputsAvailableNone
Used forBenchmarking, regression and unit tests, backtestingMonitoring, anomaly detection, collecting feedback
LimitOnly as good as the datasetMust judge quality without knowing the correct answer

Because an online check has no right answer to compare to, validate it against human labels before trusting it.

Source6 Evaluation concepts (LangSmith documentation)

Worked example

Worked example: 69 percent or 73 percent

Two prompt versions on the same 100 examples: 80 in English and 20 in Hindi (illustrative scores).

SliceExamplesv1v2Change
English8075%85%+10
Hindi2045%25%-20
All10069%73%+4

The averages: v1=(80×0.75+20×0.45)/100=(60+9)/100=69%v_1 = (80 \times 0.75 + 20 \times 0.45) / 100 = (60 + 9) / 100 = 69\%. v2=(68+5)/100=73%v_2 = (68 + 5) / 100 = 73\%. The overall score rose four points while one group lost twenty. The large English slice carries the total, so a small group can lose badly and barely move it. Show each slice beside the total.

Process

Making a score trustworthy

  1. Calibrate the judge. Have people label a sample, then measure how often the judge matches them. The LLM-as-judge paper examines position, verbosity and self-enhancement biases, and the docs say judge scores need careful review.
  2. Repeat runs. num_repetitions runs each example several times, and the table shows the average for each score. Click a score to see the individual runs or the standard deviation across repetitions.
  3. Compare versions on the same dataset version, and read paired differences.
  4. Keep a hold-out set you never tune on (course advice).
  5. Watch for gaming. If you optimise against the judge, its quirks become the target. Recheck against humans from time to time.

Sources6 Evaluation concepts (LangSmith documentation)8 How to evaluate with repetitions (LangSmith documentation)9 Judging LLM-as-a-Judge with MT-Bench and Chatbot Arena

Check yourself

Check: is a one-point gain real

Version 1 scored 75, 76 and 77 over three repetitions. Version 2 scored 74, 78 and 80. A report says “v2 wins by 1.3 points”. Compute the means and say what you would do.

Answer

Mean v1=(75+76+77)/3=76v_1 = (75 + 76 + 77) / 3 = 76. Mean v2=(74+78+80)/3≈77.3v_2 = (74 + 78 + 80) / 3 \approx 77.3, so the gap is about 1.3. The runs of v2 span 6 points (74 to 80) and v1 spans 2, so the gap is smaller than the spread of one version and could be noise. Run more repetitions, compare on the same examples, check slices, and read some failures before calling it a win. One mean from one run would have hidden this.

Source8 How to evaluate with repetitions (LangSmith documentation)

Compare

Automation rules

PartWhat the docs say
Item typeRuns, or threads (a thread rule waits until the conversation goes idle)
FilterChosen with the filter builder
Sampling rateThe share of filtered items that trigger the action
Actions on runsAdd to annotation queue, add to dataset, trigger webhooks, extend data retention
Actions on threadsAnnotation queue, dataset and webhooks (a separate section of the page also describes a thread rule extending retention, so read both)
BackfillOptional, set only when the rule is created

The idle time for thread rules defaults to 10 minutes and cannot go below 2. The rule page also lists online evaluator and code evaluator steps in a rule’s execution order.

Source5 Set up automation rules (LangSmith documentation)

Diagram

Production failure to release

Diagram: Bad production runs go to review and into a dataset, and a candidate fix is tested against the baseline.

yes

no

Production traces and online evals

Review queue, then dataset

Experiment on the fix

Gate: beats baseline, no slice worse?

Gradual release

Change prompt or tools

Diagram summary: Bad production runs go to review and into a dataset, and a candidate fix is tested against the baseline. Only a version that passes the gate is released, and one that fails goes back for another change.

Concept

A release gate, defined

  • A check in the release path: a prompt, model or tool change ships only if its offline experiment meets the agreed metrics against the current version.
  • Decide how much a single slice may drop before you see results, since small slices are noisy (course advice).
  • The docs advise targeting specific dataset versions in CI pipelines, so dataset updates do not break the workflow.
  • After release, online evaluators watch live traffic for what offline checks could not cover.
  • Cost and latency belong in the gate beside quality. A gain that doubles the bill is a decision, not a win.

Source6 Evaluation concepts (LangSmith documentation)

Check yourself

Check: does this candidate ship

Gate rule: the candidate must score higher overall and must not fall below the baseline on any slice.

SliceExamplesBaselineCandidate
Billing4080%82%
Shipping3070%74%
Returns2065%60%
Other1060%64%

Compute both overall scores, apply the rule, and say what you would do next.

Answer

Baseline =(40×0.80+30×0.70+20×0.65+10×0.60)/100=(32+21+13+6)/100=72%= (40 \times 0.80 + 30 \times 0.70 + 20 \times 0.65 + 10 \times 0.60) / 100 = (32 + 21 + 13 + 6) / 100 = 72\%. Candidate =(32.8+22.2+12+6.4)/100=73.4%= (32.8 + 22.2 + 12 + 6.4) / 100 = 73.4\%. It beats the baseline overall, but Returns fell from 13 to 12 correct out of 20, so under the rule as written the gate fails. A single example is a thin reason, so look at that failure, add repetitions for the slice and grow it, and write a tolerance into the gate if you want one. Do not loosen the rule after seeing the result.

Summary

Recap

  • A trace is the runs for one operation. Tag it with version, model, tenant and thread id from day one.
  • Flush traces in short-lived processes, and redact before data leaves. Rules catch only what they describe.
  • Debug from the trace: find it, read down, open the exact input, classify, fix one thing, save the case.
  • Dataset, example, split, experiment, evaluator. Reference outputs go to evaluators only.
  • Use code where a rule exists, a calibrated judge where judgement is needed, and pairwise for noisy scores.
  • Read slices and repetitions, not one average. Offline checks gate a release; online checks watch it.
  • Rules route runs to annotation queues and datasets, closing the loop from production to the next experiment.

References

References & Sources (1 of 2)

  1. Observability concepts (LangSmith documentation) (opens in a new tab)

    LangChain2026Documentation

    Used for Definitions of run, trace, thread, project, feedback, tags and metadata, the project-based versus agent-based workspace split, and the 25,000-run cap per trace (page read 24 October 2026).

  2. Usage and billing (LangSmith documentation) (opens in a new tab)

    LangChain2026Documentation

    Used for Base retention of 14 days and extended retention of 180 days, most traces using base retention, upgrades through rules and online evaluators, and datasets kept indefinitely (page read 24 October 2026).

  3. Trace LangChain applications (Python and JS/TS) (LangSmith documentation) (opens in a new tab)

    LangChain2026Documentation

    Used for The environment variables that switch tracing on, the default project name, selective tracing, and the flushing guidance for serverless code (page read 24 October 2026).

  4. Prevent logging of sensitive data in traces (LangSmith documentation) (opens in a new tab)

    LangChain2026Documentation

    Used for The hide-inputs and hide-outputs flags, the anonymizer and its precedence, function-level processing, and the performance caveats (page read 24 October 2026).

  5. Set up automation rules (LangSmith documentation) (opens in a new tab)

    LangChain2026Documentation

    Used for Automation rule parts: item type, filter, sampling rate, actions, backfill and the thread idle time (page read 24 October 2026).

References

References & Sources (2 of 2)

  1. Evaluation concepts (LangSmith documentation) (opens in a new tab)

    LangChain2026Documentation

    Used for Definitions of dataset, example, reference output, split and experiment, the evaluator types, and offline versus online evaluation (page read 24 October 2026).

  2. How to evaluate agents (LangSmith documentation) (opens in a new tab)

    LangChain2026Documentation

    Used for The shape of an evaluate call with a target function, evaluators and the optional experiment prefix and concurrency settings (page read 24 October 2026).

  3. How to evaluate with repetitions (LangSmith documentation) (opens in a new tab)

    LangChain2026Documentation

    Used for The num_repetitions argument, and the results table showing the average of each score, with the individual runs and standard deviation one click away (page read 24 October 2026).

  4. Judging LLM-as-a-Judge with MT-Bench and Chatbot Arena (opens in a new tab)

    Lianmin Zheng, Wei-Lin Chiang, Ying Sheng, Siyuan Zhuang, et al.2023NeurIPS 2023 Datasets and Benchmarks TrackPaper

    Used for Examines position, verbosity and self-enhancement biases in model judges, which is why a judge needs calibration.