Slides · LangChain ecosystem
LangSmith: tracing, datasets and evaluation
1 / 29
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
Compare
The vocabulary, as the docs define it
| Term | Meaning |
|---|---|
| Run | One unit of work, such as a model call, prompt formatting or a retrieval. Comparable to a span in OpenTelemetry |
| Trace | The runs for one operation, bound by a trace id |
| Thread | A sequence of traces from one multi-turn session; group them by passing a thread_id metadata key |
| Project | A container for the traces of one application or service (project-based workspaces; agent-based workspaces group traces by agent and environment instead) |
| Feedback | A tag and a score on one run, continuous or categorical |
| Tags and metadata | Strings 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).
Sources[1] Observability concepts (LangSmith documentation)[2] Usage and billing (LangSmith documentation)
Diagram
How the pieces nest
Code
Turning tracing on
For LangChain and LangGraph, environment variables are enough:
LANGSMITH_TRACING=true
LANGSMITH_API_KEY=<your key>
LANGSMITH_PROJECT=support-agent-prodLANGSMITH_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.
Sources[3] 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 afinallyblock. - Or make callbacks synchronous by setting
LANGCHAIN_CALLBACKS_BACKGROUNDtofalse. 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.
Source[3] Trace LangChain applications (Python and JS/TS) (LangSmith documentation)
Compare
Privacy: what leaves your system
| Control | What it does | Watch out |
|---|---|---|
LANGSMITH_HIDE_INPUTS, LANGSMITH_HIDE_OUTPUTS | Hide all inputs or all outputs | Hides what you need for debugging too |
create_anonymizer with regex pairs or a function | Replaces matching text before it is sent | Only catches patterns you wrote; large payloads and complex patterns slow it |
process_inputs, process_outputs on a traced function | Transforms the data of one function | Applies 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.
Source[4] 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 text | Output |
|---|---|
| Name, email, hyphenated card, order number | name kept, <EMAIL>, <CARD>, order kept |
| Card written with spaces | unchanged |
| Card as 16 digits, no separator | unchanged |
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.
Source[4] 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.
Source[4] 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.
| Rule | Filter | Sampling | Action | Root runs per day |
|---|---|---|---|---|
| 1 | error | 100% | Add to annotation queue | 600 |
| 2 | no error | 5% | Add to annotation queue | 470 |
| Total | 1,070 |
Rule 2 applies to 9,400 root runs: 9,400×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.
Process
From a complaint to a failing run
- Find the trace. Filter by error, high latency, negative feedback, tenant or tag.
- Read top down. Which run was slow, costly or wrong?
- Open what that run was handed: the prompt as rendered, the chunks it retrieved, the arguments it passed to tools.
- Classify the cause: retrieval miss, prompt or context bug, tool error, model reasoning error, routing error, a loop, a truncation.
- 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
| Term | Meaning |
|---|---|
| Dataset | A collection of examples used to evaluate an application |
| Example | Inputs, optional reference outputs and optional metadata |
| Reference output | The expected answer. It is not passed to your application, only to evaluators |
| Split | A named subset, such as regressions or a category. One example can sit in several splits |
| Experiment | The results of one application version on a dataset: outputs, scores and traces |
| Evaluator | A function or a person that scores an output |
Diagram
What an experiment is made of
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 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.
Sources[7] How to evaluate agents (LangSmith documentation)[8] How to evaluate with repetitions (LangSmith documentation)
Compare
Choosing an evaluator type
| Type | Best for | Watch out |
|---|---|---|
| Code | Deterministic rules: format, exact match, non-empty output | Brittle for open-ended text |
| LLM as judge | Criteria in a prompt; can be reference-free or reference-based | Needs careful score review and prompt tuning |
| Human | A common starting point; builds the rubric and the labels | Cost; use annotation queues |
| Pairwise | Comparing two versions when that is easier than scoring each | Randomise the order (course advice) |
| Decision model | A decision model as judge, answering typed questions (such as a probability) instead of using a prompt and output schema | Each 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.
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.
Compare
Offline and online evaluation
| Aspect | Offline | Online |
|---|---|---|
| Runs on | A dataset, before deployment | Production runs and threads |
| Reference outputs | Available | None |
| Used for | Benchmarking, regression and unit tests, backtesting | Monitoring, anomaly detection, collecting feedback |
| Limit | Only as good as the dataset | Must 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.
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).
| Slice | Examples | v1 | v2 | Change |
|---|---|---|---|---|
| English | 80 | 75% | 85% | +10 |
| Hindi | 20 | 45% | 25% | -20 |
| All | 100 | 69% | 73% | +4 |
The averages: v1=(80×0.75+20×0.45)/100=(60+9)/100=69%. v2=(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
- 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.
- Repeat runs.
num_repetitionsruns 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. - Compare versions on the same dataset version, and read paired differences.
- Keep a hold-out set you never tune on (course advice).
- Watch for gaming. If you optimise against the judge, its quirks become the target. Recheck against humans from time to time.
Sources[6] 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=76. Mean v2=(74+78+80)/3≈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.
Source[8] How to evaluate with repetitions (LangSmith documentation)
Compare
Automation rules
| Part | What the docs say |
|---|---|
| Item type | Runs, or threads (a thread rule waits until the conversation goes idle) |
| Filter | Chosen with the filter builder |
| Sampling rate | The share of filtered items that trigger the action |
| Actions on runs | Add to annotation queue, add to dataset, trigger webhooks, extend data retention |
| Actions on threads | Annotation queue, dataset and webhooks (a separate section of the page also describes a thread rule extending retention, so read both) |
| Backfill | Optional, 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.
Diagram
Production failure to release
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.
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.
| Slice | Examples | Baseline | Candidate |
|---|---|---|---|
| Billing | 40 | 80% | 82% |
| Shipping | 30 | 70% | 74% |
| Returns | 20 | 65% | 60% |
| Other | 10 | 60% | 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%. Candidate =(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)
Observability concepts (LangSmith documentation) (opens in a new tab)
LangChain2026Documentation
https://docs.langchain.com/langsmith/observability-concepts
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).
Usage and billing (LangSmith documentation) (opens in a new tab)
LangChain2026Documentation
https://docs.langchain.com/langsmith/usage-and-billing
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).
Trace LangChain applications (Python and JS/TS) (LangSmith documentation) (opens in a new tab)
LangChain2026Documentation
https://docs.langchain.com/langsmith/trace-with-langchain
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).
Prevent logging of sensitive data in traces (LangSmith documentation) (opens in a new tab)
LangChain2026Documentation
https://docs.langchain.com/langsmith/mask-inputs-outputs
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).
Set up automation rules (LangSmith documentation) (opens in a new tab)
LangChain2026Documentation
https://docs.langchain.com/langsmith/rules
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)
Evaluation concepts (LangSmith documentation) (opens in a new tab)
LangChain2026Documentation
https://docs.langchain.com/langsmith/evaluation-concepts
Used for Definitions of dataset, example, reference output, split and experiment, the evaluator types, and offline versus online evaluation (page read 24 October 2026).
How to evaluate agents (LangSmith documentation) (opens in a new tab)
LangChain2026Documentation
https://docs.langchain.com/langsmith/evaluate-llm-application
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).
How to evaluate with repetitions (LangSmith documentation) (opens in a new tab)
LangChain2026Documentation
https://docs.langchain.com/langsmith/repetition
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).
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
arXiv 2306.05685 (opens in a new tab)https://proceedings.neurips.cc/paper_files/paper/2023/hash/91f18a1287b398d378ef22505bf41832-Abstract-Datasets_and_Benchmarks.html
Used for Examines position, verbosity and self-enhancement biases in model judges, which is why a judge needs calibration.
Keys: ← → move, Home End first and last, F full screen.