11A.5 LangSmith, Testing and Deployment
You can now build agents and graphs (08F.8 to 08F.14). This lesson is about the three things that stand between a demo and a service: seeing what the system did, proving that it still works after a change, and running it somewhere other than your laptop. LangChain's answer to each lives in a different place, and the first job of the lesson is to keep them apart. Seeing is tracing in LangSmith, the hosted platform from the LangChain team. Proving is testing (plain pytest with fake models and in-memory checkpointers, which needs no account) and evaluation (LangSmith datasets, experiments and evaluators, which measure a real model). Running is LangSmith Agent Server (the runtime that older material calls LangGraph Server), plus LangSmith Studio, the visual debugger that talks to a local copy of it.
Most of what you read about this topic is marketing or a screenshot tour. This lesson is the engineering version: which environment variable really switches tracing on (and the one that silently does not), what a trace actually contains before it leaves your process, how to test your tracing and masking configuration with no network, why evaluate(..., upload_results=False) is not the offline switch its name suggests, how to write the unit tests that make a graph change safe, what the Agent Server stores and where, what a cron expression means there, what a "success" webhook can hide, which parts are open source and which are not, and what the platform costs as of 14 November 2026. Everything keyless was run on the author's machine against the packages listed in the Versions line, and the output you see is the real output. The parts that need a LangSmith account or a running server are labelled illustrative.
What you'll learn
- The three layers (library, platform, server), the names that changed in 2025 and 2026, and what works with no LangSmith account at all (Part 1)
- Tracing: the data model (run, trace, thread), every environment variable that matters, the new agent-based workspaces,
@traceable, tags and metadata, selective tracing, short-lived processes, what a payload contains, masking, sampling,TracePolicy, retention and limits (Part 2) - Datasets, experiments and evaluators: code, LLM-as-judge and trajectory evaluators,
evaluate, evaluating a graph, the pytest plugin, and what the offline observation means (Part 3) - Testing without LangSmith: fake models, the
bind_toolstrap, per-test compilation,update_statewithas_node, interrupts, tracing-configuration tests, integration markers, record and replay (Part 4) - Studio and the local server:
langgraph.jsonin full,langgraph validate,devversusupversusbuild, the generated Dockerfile, and what Studio sends where (Part 5) - Agent Server and the Agent Protocol: architecture, assistants, threads, runs, double texting, cron jobs, webhooks, the client SDK,
RemoteGraph, MCP and A2A endpoints, authentication (Part 6) - Hosting, licences and cost (dated and sourced), security notes, and a production checklist (Parts 7, 8 and 10)
What you don't need
- A LangSmith account for Parts 4, 5 (validation) and most samples. Every runnable sample here uses scripted fake models, plain Python and a small recorder that catches what the SDK would upload instead of uploading it. No sample in this lesson sends data anywhere.
- The agent and graph APIs. 08F.8 owns
create_agent, 08F.10 ownsStateGraph, 08F.11 checkpointers and the store, 08F.12 interrupts. This lesson uses them and points back. - The general theory of evaluation and observability. Module 10A owns eval design (datasets, metrics, judges, calibration), Module 11A owns observability platforms and SLOs, and Module 11C owns deployment strategy, and Module 12 owns the security model. Here you get the LangChain-specific mechanics and a pointer when a general topic is owned elsewhere.
Setup
You need Python 3.11 or newer and uv (08F.4, Part 5). New to uv? The first uv add fails outside a project, so create one first.
uv init langsmith-lab --bare --python 3.13 && cd langsmith-lab # first time only
uv add langchain langgraph langsmith
uv add --dev pytest
uv add openevals agentevals # Part 3: ready-made evaluators
uv add "langgraph-cli[inmem]" # Part 5: langgraph validate, dev, dockerfile
# or: pip install langchain langgraph langsmith pytest openevals agentevals "langgraph-cli[inmem]"No == pins: the lockfile records what uv resolves. Three small helper files are used by the samples. The first is the scripted model of 08F.8, 1.3, reduced to the part this lesson needs:
# fakes.py: a scripted chat model that create_agent accepts (the same idea as the file in 08F.8)
from langchain_core.language_models.fake_chat_models import GenericFakeChatModel
class FakeToolCallingModel(GenericFakeChatModel):
"""Replays the AIMessages you give it, one per model call, and ignores the prompt."""
def bind_tools(self, tools, **kwargs):
return self # create_agent calls this; the plain fake does not implement itThe second is the recorder (a tool of this lesson, not of LangSmith): a real langsmith.Client whose HTTP session records requests and answers with a fake success instead of sending anything. It is how this lesson shows you real run trees, real payloads and real masking, with no key and no network. Part 2 explains why it works.
# trace_recorder.py: a langsmith Client whose HTTP session records requests instead of sending them
import json
import time
import requests
from langsmith import Client
class _RecordingSession(requests.Session):
def __init__(self) -> None:
super().__init__()
self.requests_seen: list[tuple[str, str, dict | None]] = []
def request(self, method, url, **kwargs):
body = kwargs.get("data") or kwargs.get("json")
if isinstance(body, (bytes, str)):
body = json.loads(body)
self.requests_seen.append((method, url, body))
response = requests.Response() # a fake 200: nothing leaves the process
response.status_code, response._content, response.url = 200, b"{}", url
return response
class Recorder:
"""Use `recorder.client` wherever a langsmith Client is accepted; read `recorder.runs()` afterwards."""
def __init__(self, **client_kwargs) -> None:
self.session = _RecordingSession()
self.client = Client(api_url="http://recorder.invalid", api_key="not-a-real-key",
session=self.session, auto_batch_tracing=False, **client_kwargs)
def runs(self) -> list[dict]:
self.client.flush()
time.sleep(0.5) # the SDK posts from a background thread
merged: dict[str, dict] = {}
for _method, _url, body in self.session.requests_seen:
if body: # a run is POSTed at start and PATCHed at end: merge them
merged.setdefault(body["id"], {}).update({k: v for k, v in body.items() if v is not None})
return sorted(merged.values(), key=lambda run: run["dotted_order"])
def print_tree(self, show=("tags",)) -> None:
for run in self.runs():
depth = run["dotted_order"].count(".")
extras = " ".join(f"{key}={sorted(run[key]) if key == 'tags' else run[key]}" for key in show if run.get(key))
print(" " * depth + f"{run['name']} [{run['run_type']}] {extras}".rstrip())The third, support_app.py, appears in Part 4. Put all three next to your sample files and run each sample with uv run python file.py.
Versions (current at time of writing, verified 14 November 2026 by installing them and running every sample marked as run): langsmith 0.14.17, langchain 1.5.0, langchain-core 1.8.0, langgraph 1.2.22, langgraph-checkpoint 4.3.2, langgraph-prebuilt 1.1.2, langgraph-sdk 0.4.14, langgraph-cli 0.4.43, langgraph-api 0.18.0 (stable; 0.19.0rc1 is the current release candidate; 0.18.3 by 18 November), langgraph-runtime-inmem 0.38.0, openevals 0.2.5, agentevals 0.0.9 (its last PyPI release is dated 24 July 2025), langchain-protocol 0.0.21 and pytest 9.2.0. Samples ran on Python 3.13. These packages move weekly: 08F.4, 5.10 is the upgrade routine, and the Agent Server publishes its own release streams (Part 6). Re-checked on 18 November 2026 with langsmith 0.15.0, langchain-core 1.8.2 and langgraph-api 0.18.3: the environment switches (2.2), tracing off (2.7), masking (2.11), TracePolicy, the offline evaluate measurement (3.5), the local evaluators, the cron and webhook samples and the unit tests gave the same results as the outputs shown below, apart from version strings and the additions that this re-check made (2.9, 2.10 and 4.4). That is the habit to copy: re-run your samples after each upgrade.
Where LangSmith fits next to vendor-neutral tooling#
LangSmith is one vendor option for tracing, evaluation and deployment, not the only way and not a requirement for building agents. It is the hosted platform from the LangChain team, and it is the most convenient choice if you build on LangChain and LangGraph. The vendor-neutral alternative is taught in 11A.1 Tracing and Observability: emit OpenTelemetry spans that follow the GenAI semantic conventions (11A.1, Part 3), then send them to whichever backend you choose. 11A.1, 4.1 compares proxy-based, SDK-based and OpenTelemetry-based instrumentation, including lock-in. Module 11A also has a lesson on the OpenTelemetry GenAI approach.
Three practical points before you start:
- The ideas transfer. A LangSmith run is an OpenTelemetry span, a trace is a trace, and the testing and deployment parts of this lesson (fake models,
pytest, the Agent Server) work without a LangSmith account (1.2). - LangSmith can sit inside an OpenTelemetry stack. It can emit and ingest OpenTelemetry data, so choosing it does not force you to give up the vendor-neutral layer (see the going-deeper note in Part 2).
- Choose on your constraints. Check data residency, retention, price and lock-in for any hosted tracing vendor, LangSmith included (Part 7 and Part 8 cover these for LangSmith).
What you must be able to do after this lesson#
- Name the three LangSmith layers (library, platform, server), their licences and which one needs an account
- Switch tracing on with the correct environment variable and set tags and metadata with @traceable
- Write an evaluator and run evaluate on a dataset with upload_results=False
- Test a LangGraph agent without an account using a fake model and the bind_tools workaround
- Validate langgraph.json and start the local server with langgraph dev
- Explain assistants, threads and runs in the Agent Server
- Apply the production checklist and the hide_inputs privacy caveats before enabling tracing
Why this matters for an AI engineer#
| You'll hear... | You'll understand it after... |
|---|---|
| "Is LangSmith required for LangChain?" / "What does Studio send out?" | 1.2 and 5.7 |
| "LangGraph Server, LangSmith Deployment, Agent Server: which is it?" | 1.1 |
| "I set the variable and nothing shows up." | 2.2 |
| "Traces now belong to an agent and an environment." | 2.3 |
| "Tag every call so we can filter in production." | 2.5 |
"Decorate it with @traceable." |
2.6 |
| "Our traces contain customer emails." | 2.10, 2.11 and Part 8 |
| "What does tracing cost and how long is it kept?" | 2.12 |
| "Build a dataset and run an experiment." | Part 3 |
| "Did the agent call the right tools?" | 3.6 |
"Why does upload_results=False still make network calls?" |
3.5 |
| "How do we unit test an agent with no model?" | Part 4 |
"GenericFakeChatModel has no bind_tools." |
4.2 |
| "Run it locally in Studio." | Part 5 |
"What is in langgraph.json?" |
5.2 |
| "Assistants, threads, runs: what are they?" | 6.3, 6.4 and 6.5 |
| "What happens if the user sends a second message while it is still running?" | 6.7 |
| "Schedule it with cron." | 6.8 |
| "The webhook said success but the agent was waiting for approval." | 6.9 |
| "What is the Agent Protocol?" | 6.12 |
| "Can we self-host it? What does it cost?" | Part 7 |
Part 1: The map: libraries, platform and server#
1.1 Three layers and their names#
08F.4, Part 1 drew the whole ecosystem. For this lesson only three things matter, and they differ in kind:
| Layer | What it is | Examples | Licence | Needs an account? |
|---|---|---|---|---|
| Libraries | Python packages you import | langchain, langgraph, langsmith (the SDK), langgraph-sdk, langgraph-cli, openevals |
MIT on PyPI | No |
| The LangSmith platform | A hosted (or self-hosted) service | Tracing, datasets, experiments, annotation queues, Studio | Closed source service | Yes (free tier exists) |
| The Agent Server runtime | A server that runs your graphs as an API | langgraph-api, langgraph-runtime-inmem, the langchain/langgraph-api image |
Elastic-2.0 on PyPI |
Local use needs a free LangSmith key; production needs a licence |
The SDK being MIT while the service is not is the source of most confusion: pip install langsmith gives you code that can talk to a service, and does nothing until you tell it to.
The names changed several times. 08F.4, 1.7 has the full map; the part you need here:
| You will see in older material | The current name (docs, 14 November 2026) | Notes |
|---|---|---|
| LangGraph Platform, then LangSmith Deployment, then LangGraph Server | LangSmith Agent Server | The docs say verbatim: "LangSmith Deployment is now LangSmith Agent Server." It is the same runtime. |
| LangGraph Studio | LangSmith Studio | The LangSmith changelog entry for 13-17 October 2025 says "LangGraph Platform is now LangSmith Deployment and LangGraph Studio is now LangSmith Studio" (changelog). Some READMEs still say "LangGraph Studio". |
langgraph-* package names, the langgraph command |
unchanged | The CLI, the SDK and the image keep the old prefix. |
So when a tutorial says "LangGraph Server", read "Agent Server"; when it says "LangSmith Deployment", read "Agent Server hosted by LangChain". Part 6 and Part 7 separate the runtime from the places you can host it.
1.2 What needs an account, and what does not#
LangSmith is optional. Nothing in LangChain or LangGraph requires it: tracing is opt-in through environment variables, the libraries are MIT, and they run without it. Here is what needs what:
| Capability | Needs a LangSmith account and key? | Where in this lesson |
|---|---|---|
| Running agents and graphs | No | 08F.8 to 08F.14 |
| Unit tests with fake models and in-memory checkpointers | No | Part 4 |
Writing and calling evaluators as plain functions (openevals, agentevals, your own) |
No | 3.3 and 3.6 |
langgraph validate, langgraph dockerfile |
No | 5.2 and 5.4 |
| Tracing | Yes (an API key, set as LANGSMITH_API_KEY) |
Part 2 |
Datasets and experiments (client.evaluate, create_dataset) |
Yes | Part 3 |
langgraph dev and Studio against a local server |
A free account and API key | Part 5 |
langgraph up, a standalone server in production |
A key and a licence | Part 7 |
| Assistants, double texting, server-side cron | Agent Server only (not in the open-source library) | Part 6 |
The last row matters for design: the docs state explicitly that "Assistants are a LangSmith Agent Server concept. They are not available in the open source LangGraph library", and the same for double texting. If you build on those and later want to leave the platform, you rebuild them. Checkpointers, threads and the store, by contrast, are library features (08F.11) that the server provides for you.
1.3 The lifecycle in one picture#
flowchart LR
dev["Develop<br/>agent or graph"] --> unit["Unit tests<br/>fakes, no account"]
unit --> studio["Studio<br/>local server"]
studio --> exp["Experiments<br/>dataset + evaluators"]
exp --> deploy["Agent Server<br/>assistants, threads, runs"]
deploy --> prod["Production traffic"]
prod --> trace["Traces, feedback,<br/>online evaluators"]
trace -->|"failures become examples"| exp
dev -.->|"tracing on from day one"| traceThe loop is the point: production traces feed datasets, datasets feed experiments, experiments gate the next release. Each arrow is a section of this lesson. 11C.2 covers the release gating in general terms.
1.4 What to adopt, and when#
| Stage of the project | Adopt | Why |
|---|---|---|
| First prototype | Nothing extra; maybe tracing on | Tracing costs one environment variable and saves hours of print debugging |
| Second week | Unit tests with fakes (Part 4) | Cheap, deterministic, protects control flow |
| Before the first user | A small dataset and 2 to 3 evaluators (Part 3); masking decided (2.11) | You need a number to compare changes against, and you need to decide what leaves your process |
| Debugging a graph | Studio on a local server (Part 5) | See the graph, replay and fork, edit state |
| When a service is needed | Agent Server (managed or self-hosted) or your own HTTP layer (Part 6 and Part 7) | Long-running, resumable, multi-user work |
Part 2: Tracing with LangSmith#
2.1 The vocabulary#
LangSmith's concepts page defines a handful of words. Learn them once; every later section uses them.
| Term | Meaning | Compare with |
|---|---|---|
| Run | One unit of work: a model call, a tool call, a retriever call, a graph node | An OpenTelemetry span (the docs say so) |
| Trace | The tree of runs for one operation, tied together by a trace ID | A trace |
| Thread | A sequence of traces that form one multi-turn conversation, grouped by a thread_id metadata key |
A session |
| Trajectory | A flat, ordered list of messages, a projection over a thread's traces | A transcript |
| Tags | Strings for filtering ("production", "v1.4") |
Labels |
| Metadata | Key-value pairs (user_id, app_version, environment) |
Span attributes |
| Feedback | A score on a run: a key, a score (number) or value (category), an optional comment |
A rating or an assertion result |
One hard limit: a trace holds at most 25,000 runs, and LangSmith rejects extra runs. A long agent loop with many tool calls is nowhere near it; a loop that fans out in a Send over thousands of items can be.
There are two ways to get runs into LangSmith: integrations (automatic: LangChain, LangGraph, and wrappers for the OpenAI, Anthropic and other SDKs) and manual instrumentation (@traceable, the trace context manager, the low-level RunTree). You will use both, often in the same program.
2.2 Switching tracing on, and the variable that silently does not#
For LangChain and LangGraph, tracing needs no code change. In the shell or in .env (loaded with load_dotenv() before your first traced call):
export LANGSMITH_TRACING=true
export LANGSMITH_API_KEY=... # created in the LangSmith UI, Settings, API Keys
export LANGSMITH_PROJECT=support-bot # project-based workspaces: the project that groups your traces
# export LANGSMITH_ENDPOINT=https://eu.api.smith.langchain.com # only for non-US regions (below)
# export LANGSMITH_WORKSPACE_ID=... # only if your key is linked to several workspacesThe current docs also describe an agent-based way to say where traces go (2.3). The variables that matter, with the facts the docs and the SDK give:
| Variable | What it does | Note |
|---|---|---|
LANGSMITH_TRACING |
true switches tracing on |
The only spelling the current tracing pages use |
LANGSMITH_API_KEY |
Authenticates the upload | LANGCHAIN_API_KEY is accepted by the CLI as an alias |
LANGSMITH_PROJECT |
Names the project that receives the traces | Legacy aliases LANGCHAIN_PROJECT and LANGCHAIN_SESSION still work in project-based workspaces; do not combine them with the agent variables |
LANGSMITH_ENDPOINT |
The API URL for a non-US region or a self-hosted instance | Without it in a non-US region "your API key won't be recognized" (docs) |
LANGSMITH_WORKSPACE_ID |
Chooses a workspace when the key is linked to several | |
LANGSMITH_TRACING_SAMPLING_RATE |
A float from 0 to 1: the share of traces kept (default: all) | 2.11 |
LANGSMITH_HIDE_INPUTS, LANGSMITH_HIDE_OUTPUTS, LANGSMITH_HIDE_METADATA |
true replaces that part of every run with nothing |
2.11 |
LANGCHAIN_CALLBACKS_BACKGROUND |
Documented as a switch between background and synchronous uploads; no Python code in langchain-core 1.8 or langsmith 0.14 and 0.15 reads it (measured in 2.9). A LangChain.js setting in practice |
2.9 |
LANGSMITH_OTEL_ENABLED |
Switches to OpenTelemetry mode | Survey only: see the OpenTelemetry pages in the docs |
LANGSMITH_TEST_SUITE, LANGSMITH_TEST_CACHE, LANGSMITH_TEST_TRACKING |
The pytest plugin | 3.7 |
Regional endpoints (docs, 14 November 2026): US (the default) https://api.smith.langchain.com, EU https://eu.api.smith.langchain.com, APAC https://apac.api.smith.langchain.com, AWS US https://aws.api.smith.langchain.com, Azure US https://azure.api.smith.langchain.com. Use the endpoint of the region where your account lives; the docs warn that a key sent to the wrong region's endpoint is not recognised.
Which spellings does the SDK really honour? The current tracing pages mention only LANGSMITH_TRACING, and 08F.4, 5.7 said it could not confirm the older names. The SDK is the authority, so ask it. This sample starts a child process per setting and asks langsmith.utils.tracing_is_enabled():
# s03_env_switches.py: which environment variables switch tracing on? Ask the SDK, in a child process per setting
import os
import subprocess
import sys
PROBE = "from langsmith.utils import tracing_is_enabled; print(tracing_is_enabled())"
CASES = [
{},
{"LANGSMITH_TRACING": "true"},
{"LANGSMITH_TRACING": "True"},
{"LANGSMITH_TRACING": "1"},
{"LANGCHAIN_TRACING_V2": "true"}, # the pre-2025 spelling
{"LANGCHAIN_TRACING": "true"},
{"LANGSMITH_TRACING": "true", "LANGCHAIN_TRACING_V2": "false"},
{"LANGSMITH_TRACING": "false", "LANGCHAIN_TRACING_V2": "true"},
]
for case in CASES:
env = {k: v for k, v in os.environ.items() if not k.startswith(("LANGSMITH_", "LANGCHAIN_"))}
env.update(case)
out = subprocess.run([sys.executable, "-c", PROBE], env=env, capture_output=True, text=True)
print(f"{str(case):<68} -> {out.stdout.strip()}")
# The value is read once and cached: setting it after the first check changes nothing.
import langsmith.utils as u
print("in-process, before:", u.tracing_is_enabled())
os.environ["LANGSMITH_TRACING"] = "true"
print("in-process, after setting the variable:", u.tracing_is_enabled()){} -> False
{'LANGSMITH_TRACING': 'true'} -> True
{'LANGSMITH_TRACING': 'True'} -> False
{'LANGSMITH_TRACING': '1'} -> False
{'LANGCHAIN_TRACING_V2': 'true'} -> True
{'LANGCHAIN_TRACING': 'true'} -> True
{'LANGSMITH_TRACING': 'true', 'LANGCHAIN_TRACING_V2': 'false'} -> False
{'LANGSMITH_TRACING': 'false', 'LANGCHAIN_TRACING_V2': 'true'} -> True
in-process, before: False
in-process, after setting the variable: FalseFour facts fall out of that:
- The value must be exactly the lowercase string
true.Trueand1do not switch tracing on, and nothing warns you. This is the most common "I set it and nothing shows up" cause. - The old names still work in 0.14.17.
LANGCHAIN_TRACING_V2=trueandLANGCHAIN_TRACING=trueboth enable tracing, because the SDK reads each name under both theLANGSMITH_andLANGCHAIN_prefixes. Old tutorials still work, which is useful and hides the fact that the docs have moved on. Write the new names in new code. (Unofficial, but measured:LANGSMITH_TRACING_V2=truealso works, for the same reason. Do not rely on it.) TRACING_V2beatsTRACING. WithLANGSMITH_TRACING=trueandLANGCHAIN_TRACING_V2=falsetracing is off; withLANGSMITH_TRACING=falseandLANGCHAIN_TRACING_V2=trueit is on. A leftover line from an old.envcan silently override the new variable. Search your environment for both.- The value is read once and cached. Setting
os.environ["LANGSMITH_TRACING"]after the first check changes nothing in that process. Callload_dotenv()(or export the variable) before the first traced call; in notebooks, restart the kernel after changing it. For a block-level switch usetracing_context(2.7).
2.3 Agent-based workspaces#
New in 2026 on LangSmith Cloud: traces can belong to an agent (a stable identifier you choose) running in one of four fixed environments, instead of to a free-form project. The pages are log-traces-to-agent, agent-registry and migrate-to-agent-based-workspaces under docs.langchain.com/langsmith/.
export LANGSMITH_TRACING=true
export LANGSMITH_API_KEY=...
export LANGSMITH_AGENT_ID="checkout" # a stable identifier you choose
export LANGSMITH_AGENT_ENVIRONMENT="local" # local | development | staging | production (case-insensitive)What the docs say, and what to watch for:
- Both variables are needed. If only one is set, the SDK logs a warning and leaves untraced every call that names no destination in code.
- Do not combine the old and new settings. Remove
LANGSMITH_PROJECT,LANGCHAIN_PROJECTandLANGCHAIN_SESSIONwhen you use the agent variables (the quickstart says so). - An address in code beats the variables. The code form is
@traceable(address=ls.agent_address("checkout", "local"))orwith tracing_context(address=...). - Versions. Python needs
langsmith>=0.14.9; the TypeScript SDK needs>=0.11.0. - Cloud only. Agent-based workspaces are "not available on self-hosted LangSmith", where project-based workspaces and
LANGSMITH_PROJECTstill apply. For existing organisations the migration page says "Timing is not published"; new Cloud organisations get agent-based workspaces. So you may meet either model, depending on when the organisation was created, and a tutorial written for one will confuse a learner on the other.
This sample builds an address and traces one function. The recorder catches the payload, so you see what the address turns into on the wire:
# s15_agent_address.py: agent-based workspaces: a trace belongs to an agent id and one of four environments (recorded, not sent)
import langsmith as ls
from langsmith import traceable
from langsmith.utils import LangSmithUserError
from trace_recorder import Recorder
rec = Recorder()
address = ls.agent_address("checkout", "local") # (agent id, environment)
print(address)
@traceable(client=rec.client, address=address)
def total(prices: list[float]) -> float:
return round(sum(prices), 2)
with ls.tracing_context(enabled=True):
total([4.5, 5.5])
run = rec.runs()[0]
print("address field:", run["address"], "| project field present:", "session_name" in run)
try:
ls.agent_address("checkout", "prod") # only four environments exist
except LangSmithUserError as exc:
print(exc){'kind': 'AGENT', 'id': 'checkout', 'environment': 'LOCAL'}
address field: lrn:agents/checkout/environments/local | project field present: False
Address environment must be one of local, development, staging, production, got 'prod'.On the wire the run carries a single address string (lrn:agents/<id>/environments/<environment>) and no project (session_name) field, and an unknown environment name (prod here) is rejected before anything is sent. That is a tidy design for filtering ("show me production runs of checkout") and a trap for dashboards built on project names, which will not see agent-addressed traces.
2.4 Tracing agents and graphs: no code at all#
With the environment set, every create_agent agent, LCEL chain and compiled graph is traced. The docs' phrase is "No extra code is needed". For the other pieces inside a graph, the pages say to "wrap or decorate" them: a call to a provider SDK from inside a node is invisible until you decorate the function with @traceable or wrap the client (2.6), whereas LangChain components inside a node are traced for free.
To see what the trace of an agent looks like with no account, the recorder routes a real run into a list. The model is the scripted fake of 08F.8, so there is no provider call, but the agent, tool node and callbacks are all real:
# s11_trace_agent.py: what a create_agent run looks like as a LangSmith trace (scripted model, recorded, not sent)
import langsmith as ls
from langchain.agents import create_agent
from langchain.messages import AIMessage, HumanMessage, ToolCall
from langchain.tools import tool
from langgraph.checkpoint.memory import InMemorySaver
from fakes import FakeToolCallingModel
from trace_recorder import Recorder
@tool
def get_order_status(order_id: str) -> str:
"""Look up an order."""
return f"Order {order_id}: shipped"
model = FakeToolCallingModel(messages=iter([
AIMessage(content="", tool_calls=[ToolCall(name="get_order_status", args={"order_id": "A17"}, id="c1")]),
AIMessage(content="Order A17 has shipped."),
]))
agent = create_agent(model, tools=[get_order_status], checkpointer=InMemorySaver())
rec = Recorder()
with ls.tracing_context(enabled=True, client=rec.client):
agent.invoke(
{"messages": [HumanMessage("Where is A17?")]},
config={
"run_name": "support-agent", # renames the root run only
"tags": ["production", "support"], # inherited by every child run
"metadata": {"user_id": "u_42", "app_version": "1.4.0"}, # so is this
"configurable": {"thread_id": "conv-001"},
},
)
rec.print_tree(show=("tags",))
tool_run = next(r for r in rec.runs() if r["run_type"] == "tool")
meta = tool_run["extra"]["metadata"]
print({k: meta[k] for k in ("user_id", "app_version", "thread_id", "langgraph_node", "ls_integration") if k in meta})
print("tool run inputs:", tool_run["inputs"], "| tool call id:", tool_run["extra"]["tool_call_id"])support-agent [chain] tags=['production', 'support']
model [chain] tags=['graph:step:1', 'production', 'support']
FakeToolCallingModel [llm] tags=['production', 'seq:step:1', 'support']
tools [chain] tags=['graph:step:2', 'production', 'support']
get_order_status [tool] tags=['production', 'seq:step:1', 'support']
model [chain] tags=['graph:step:3', 'production', 'support']
FakeToolCallingModel [llm] tags=['production', 'seq:step:1', 'support']
{'user_id': 'u_42', 'app_version': '1.4.0', 'thread_id': 'conv-001', 'langgraph_node': 'tools', 'ls_integration': 'langchain_create_agent'}
tool run inputs: {'order_id': 'A17'} | tool call id: c1Read it as the agent loop of 08A.2 drawn as a tree. The root is the whole invoke, renamed by run_name. Under it, model and tools are the graph's nodes, in order (graph:step:1, 2, 3 in the tags), and under each node sits the thing the node called: the chat-model run (llm) and the tool run. Three details are worth knowing:
- Tags and metadata passed in
configreach every child. Every run in the tree carriesproductionandsupport, and the tool run carriesuser_idandapp_versionin its metadata. That is what makes "show me everything from app version 1.4.0" a one-line filter. - LangGraph adds its own metadata.
thread_id(fromconfigurable),langgraph_nodeandls_integrationappear without you setting them. Thethread_idis what groups the traces of one conversation (2.8). - The tool run records the arguments and the tool call id (
{'order_id': 'A17'},c1), which is how you tie a tool result back to the model's request.
Why does the recorder work? A langsmith.Client accepts a custom HTTP session, and tracing_context(client=...) routes runs to a chosen client. The recorder passes a session that stores each request and returns a fake 200. It is a test technique (4.5) as much as a teaching device: everything the SDK would send, you can assert on.
2.5 Tags, metadata, names and IDs on every call#
The same config dictionary you used for threads in 08F.11 carries the tracing knobs:
config = {
"run_name": "support-agent", # renames the root run only, not the nested model run
"tags": ["production", "email-assistant", "v1.4"],
"metadata": {"user_id": "u_42", "session_id": "s_456"},
"configurable": {"thread_id": "conv-001"},
# "run_id": a UUID you choose; at the root it becomes the trace id (use UUID v7)
}
# agent.invoke(inputs, config=config)This fragment is illustrative: it needs an agent to call, and the sample in 2.4 is its runnable form. The rules, from the docs and the run above:
| Knob | Behaviour |
|---|---|
tags |
Inherited by every child run. Good for low-cardinality filters: environment, feature, release |
metadata |
Inherited too. Good for ids you search by (user_id, ticket_id) and for versions |
run_name |
Renames only the run you invoked; nested runs keep their own names |
run_id |
Sets the run's id; at the root it becomes the trace_id. The docs recommend UUID v7 (from langchain_core.utils.uuid import uuid7), which sorts by time |
metadata={"ls_model_name": "..."} on a chat model |
Overrides the model name LangSmith shows (useful behind a gateway) |
tracing_context(enabled=True, tags=[...], metadata={...}) |
The same tags and metadata for a whole block, without touching each call |
2.6 @traceable and manual instrumentation#
LangChain components trace themselves. Your own functions do not, until you decorate them. @traceable turns a function into a run; calls from inside a traced function nest automatically, and tags and metadata can be set at three levels, as this sample shows (recorded, never sent):
# s10_traceable.py: @traceable, nested runs, tags and metadata at three levels. Nothing is sent: a Recorder catches it.
import langsmith as ls
from langsmith import traceable
from trace_recorder import Recorder
rec = Recorder()
@traceable(run_type="tool", name="lookup_order") # a child: it is called from inside another traced function
def lookup_order(order_id: str) -> dict:
return {"order_id": order_id, "status": "shipped"}
@traceable(name="answer_ticket", tags=["support"], metadata={"app_version": "1.4.0"}, client=rec.client)
def answer_ticket(question: str, order_id: str) -> str:
order = lookup_order(order_id)
run = ls.get_current_run_tree() # dynamic: change the run while it executes
run.tags.append("order-found")
run.metadata["order_status"] = order["status"]
return f"Order {order_id} is {order['status']}."
with ls.tracing_context(enabled=True): # same effect as LANGSMITH_TRACING=true, for this block
print(answer_ticket("Where is my order?", "A17",
langsmith_extra={"tags": ["per-call"], "metadata": {"user_id": "u_42"}}))
rec.print_tree(show=("tags",))
root = rec.runs()[0]
print({k: v for k, v in root["extra"]["metadata"].items() if k in ("app_version", "user_id", "order_status")})
print("inputs:", root["inputs"], "| outputs:", root["outputs"])Order A17 is shipped.
answer_ticket [chain] tags=['order-found', 'per-call', 'support']
lookup_order [tool] tags=['per-call', 'support']
{'user_id': 'u_42', 'app_version': '1.4.0', 'order_status': 'shipped'}
inputs: {'question': 'Where is my order?', 'order_id': 'A17'} | outputs: {'output': 'Order A17 is shipped.'}Notice that lookup_order, which has no client and no tags of its own, was captured by the parent's client, inherited the parent's tags (per-call, support) and appears as a child. The tag order-found was added to the root while it ran, through get_current_run_tree(), after the child had already started, so the child lacks it. The three levels are:
| Level | How | When |
|---|---|---|
| Decoration time | @traceable(name=..., tags=[...], metadata={...}, run_type=...) |
Fixed facts about the function |
| Per call | fn(..., langsmith_extra={"tags": [...], "metadata": {...}, "run_id": ...}) |
Facts you know at the call site (the user, the request) |
| While running | ls.get_current_run_tree() then .tags.append(...) or .metadata[...] = ... |
Facts you learn mid-way (the order status) |
run_type takes values such as "llm" and "tool"; the default is a generic chain. Setting run_type="llm" on a function that calls a provider lets the UI show token usage and latency as a model call.
For a block of code that is not a function, use the trace context manager (Python only):
# s17_trace_block.py: trace a block of code that is not a function: the trace() context manager, and a custom run id
import langsmith as ls
from langsmith import traceable, uuid7
from trace_recorder import Recorder
rec = Recorder()
my_id = uuid7() # time-ordered ids sort naturally in the UI (the docs recommend UUID v7)
@traceable(client=rec.client, name="nightly_job")
def nightly_job(tickets: list[str]) -> int:
kept = []
with ls.trace(name="filter_spam", run_type="tool", inputs={"count": len(tickets)}, tags=["cleanup"]) as step:
kept = [t for t in tickets if "viagra" not in t]
step.end(outputs={"kept": len(kept)}) # record what this block produced
return len(kept)
with ls.tracing_context(enabled=True):
nightly_job(["refund", "viagra deal", "login problem"], langsmith_extra={"run_id": my_id})
runs = rec.runs()
print([(r["name"], r["run_type"]) for r in runs])
print("root id is the id we chose:", runs[0]["id"] == str(my_id), "| trace id equals root id:", runs[0]["trace_id"] == runs[0]["id"])
print("child outputs:", runs[1]["outputs"], "| child tags:", runs[1]["tags"])[('nightly_job', 'chain'), ('filter_spam', 'tool')]
root id is the id we chose: True | trace id equals root id: True
child outputs: {'kept': 2} | child tags: ['cleanup']Here the root's id is the UUID v7 chosen by the caller (and the trace id equals the root id), and the block's outputs were recorded explicitly with step.end(outputs=...). A UUID you choose is useful when your own system already has a request id and you want to find the trace without searching: generate the id first, store it next to the request, and pass it as run_id. RunTree is the low-level explicit API under both; reach for it only when the decorator and the context manager cannot express your control flow.
Wrapping provider SDKs. For a provider SDK called outside LangChain, wrap the client and every call becomes a run:
from langsmith.wrappers import wrap_openai
from openai import OpenAI
client = wrap_openai(OpenAI()) # every call made through this client is now tracedThis sketch is illustrative: it needs OPENAI_API_KEY and the openai package to run, and the course's provider conventions apply to the call you make with the client (03.1). Wrappers for Anthropic and Gemini exist in langsmith.wrappers too (the Gemini wrapper is labelled beta in the docs); check the docs for the current list.
2.7 Selective tracing#
Tracing does not have to be all or nothing. tracing_context switches it for a block, and the context beats the environment in both directions. This sample counts what a decorated function sends under each switch:
# s12_tracing_off.py: counting what is sent under different switches (recorded, never sent)
import langsmith as ls
from langsmith import traceable
from trace_recorder import Recorder
def run_once(rec: Recorder) -> int:
@traceable(client=rec.client)
def work(x: int) -> int:
return x + 1
work(1)
return len(rec.runs())
# 1. No environment variable and no context: a decorated function is just a function.
print("default: ", run_once(Recorder()), "runs")
# 2. Switched on for one block only.
with ls.tracing_context(enabled=True):
print("tracing_context(enabled=True): ", run_once(Recorder()), "runs")
# 3. Switched off for one block, which wins over the environment variable (run this file with LANGSMITH_TRACING=true to see it).
with ls.tracing_context(enabled=False):
print("tracing_context(enabled=False): ", run_once(Recorder()), "runs")Output with no environment variable set, then with LANGSMITH_TRACING=true (run on 14 November 2026):
default: 0 runs
tracing_context(enabled=True): 1 runs
tracing_context(enabled=False): 0 runsdefault: 1 runs
tracing_context(enabled=True): 1 runs
tracing_context(enabled=False): 0 runsThe first block shows that a decorated function is just a function until something switches tracing on: with nothing set, zero runs. The second shows the environment variable on, and enabled=False winning over it. So "trace one request in the middle of an otherwise silent service" and "never trace this block even though the service traces everything" are both a with statement. The conditional-tracing page of the docs shows the per-request pattern for customers with zero-retention agreements: decide per request whether the call goes inside tracing_context(enabled=True).
2.8 Threads: grouping a conversation#
One agent turn is one trace. A conversation is many traces, and LangSmith groups them into a thread when each carries the same thread_id in its metadata. With LangGraph you already set configurable={"thread_id": ...}, and the run above shows it reaching the metadata ('thread_id': 'conv-001'). For your own @traceable code, put thread_id in metadata yourself.
The docs' best practice: set thread_id on all runs of a turn, parent and child, or thread filtering, token counting and thread-level evaluation break. A decorated function that forgets it splits the conversation into pieces. When a tracing question is "why did this user's third message go wrong?", the thread view (every turn, in order) is what you open, and it only works if the id is on every run.
2.9 Short-lived processes and serverless#
Python tracing uploads from a background thread, so your code is not slowed down by the network. The cost is that a process that is stopped before the queue is empty loses the last traces. What the docs and the measurements below say about the fixes:
| Situation | Fix |
|---|---|
| A script using LangChain or LangGraph | Call wait_for_all_tracers() before the process can stop: from langchain_core.tracers.langchain import wait_for_all_tracers |
A script using only the SDK (@traceable) |
Client().flush() before the process can stop |
| Serverless (Lambda and similar) | The same two calls, at the end of the handler. Not LANGCHAIN_CALLBACKS_BACKGROUND=false: see below |
| Long-running service | Nothing: the background thread runs for the life of the process |
The variable the docs offer instead. The LangSmith docs ("Trace with LangChain") say, in the Python section, "You can make callbacks synchronous by setting the LANGCHAIN_CALLBACKS_BACKGROUND environment variable to "false"", and their LangChain.js note recommends false for serverless. This lesson's check found that in the installed Python packages nothing reads it: a text search of langchain-core 1.8.2 and langsmith 0.15.0 finds no occurrence, and in langchain-core 1.8 wait_for_all_tracers() is only a call to the global client's flush(). (The only hits in the whole environment are in langgraph-cli and in the server's JavaScript runtime.) Here is the measurement. A slow fake network (every request takes one second), a LangChain runnable traced through the global client, and a process that stops straight after invoke the way a frozen Lambda container does:
# s50_background_flag.py: does LANGCHAIN_CALLBACKS_BACKGROUND change whether a Lambda-style script's traces arrive? (recorded, never sent)
import os
import sys
import time
import langsmith.run_trees as rt
import requests
from langchain_core.runnables import RunnableLambda
from langchain_core.tracers.langchain import LangChainTracer, get_client, wait_for_all_tracers
from langsmith import Client
LOG, FIX = sys.argv[1], sys.argv[2] # a log file, and the fix to apply: none, wait or flush
class SlowRecordingSession(requests.Session):
def request(self, method, url, **kwargs):
time.sleep(1.0) # a slow network: every request takes one second
with open(LOG, "a") as log:
log.write(f"{method} {url.split('recorder.invalid')[1][:12]}\n")
response = requests.Response() # a fake 200: nothing leaves the process
response.status_code, response._content, response.url = 200, b"{}", url
return response
rt._CLIENT = Client(api_url="http://recorder.invalid", api_key="not-a-real-key", session=SlowRecordingSession()) # the global client
chain = RunnableLambda(lambda text: text.upper()).with_config(run_name="shout")
start = time.perf_counter()
result = chain.invoke("hello", config={"callbacks": [LangChainTracer()]})
variable = os.environ.get("LANGCHAIN_CALLBACKS_BACKGROUND", "(unset)")
print(f"{result}: invoke returned after {time.perf_counter() - start:.2f}s; variable={variable}; fix={FIX}", flush=True)
if FIX == "wait":
wait_for_all_tracers() # the LangChain fix
elif FIX == "flush":
get_client().flush() # the SDK fix
os._exit(0) # stands in for a Lambda freeze: no exit hooks runRun four ways, with LOG a fresh empty file each time:
python s50_background_flag.py log.txt none # variable unset
LANGCHAIN_CALLBACKS_BACKGROUND=false python s50_background_flag.py log.txt none
python s50_background_flag.py log.txt wait
python s50_background_flag.py log.txt flushOutput (real, langsmith 0.15.0, langchain-core 1.8.2); the last line of each block is the number of lines in log.txt afterwards:
--- LANGCHAIN_CALLBACKS_BACKGROUND=(unset), fix=none
HELLO: invoke returned after 0.03s; variable=(unset); fix=none
requests logged before exit: 0
--- LANGCHAIN_CALLBACKS_BACKGROUND=false, fix=none
HELLO: invoke returned after 0.02s; variable=false; fix=none
requests logged before exit: 0
--- LANGCHAIN_CALLBACKS_BACKGROUND=(unset), fix=wait
HELLO: invoke returned after 0.02s; variable=(unset); fix=wait
requests logged before exit: 2
--- LANGCHAIN_CALLBACKS_BACKGROUND=(unset), fix=flush
HELLO: invoke returned after 0.03s; variable=(unset); fix=flush
requests logged before exit: 2Read the table the way an engineer would: the variable changed nothing (0 requests arrived with it set to false, exactly as without it, and invoke returned in the same 0.02 seconds, so it did not make the upload synchronous), while wait_for_all_tracers() and flush() each delivered both requests (the run's POST and PATCH). A second check with a normal interpreter exit (sys.exit(0) instead of os._exit(0)) delivered both requests as well, after the process waited about two seconds on the slow network: on a normal exit this SDK drains its queue, so the traces vanish when the runtime freezes or kills the process (Lambda after the handler returns, a container stopped by its orchestrator, os._exit), not on every script exit. The docs still tell scripts to call wait_for_all_tracers(), which costs nothing and does not depend on that behaviour.
2.10 What a trace contains before it leaves your process#
Before you switch tracing on for real data, look at what would be uploaded. The recorder makes that a ten-line script:
# s14_payload_inspection.py: look at what the SDK would upload for one traced function (recorded, never sent)
import re
import langsmith as ls
from langsmith import traceable
from trace_recorder import Recorder
rec = Recorder()
@traceable(client=rec.client, name="classify")
def classify(text: str) -> str:
return "billing"
with ls.tracing_context(enabled=True):
classify("Refund please")
run = rec.runs()[0]
print("run fields: ", sorted(run))
print("metadata keys: ", sorted(run["extra"]["metadata"]))
print("env in metadata:", {k: v for k, v in run["extra"]["metadata"].items() if k.startswith(("LANGSMITH_", "LANGCHAIN_"))})
print("runtime keys: ", sorted(run["extra"]["runtime"]))
print("runtime sample: ", {k: run["extra"]["runtime"][k] for k in ("sdk", "sdk_version", "runtime", "py_implementation")})
print("requests made: ", [(m, re.sub(r"/[0-9a-f-]{36}", "/<run id>", u.split("recorder.invalid")[1])) for m, u, _ in rec.session.requests_seen])run fields: ['attachments', 'dotted_order', 'end_time', 'events', 'extra', 'id', 'inputs', 'name', 'outputs', 'run_type', 'session_name', 'start_time', 'tags', 'trace_id']
metadata keys: ['ls_method', 'revision_id']
env in metadata: {}
runtime keys: ['langchain_core_version', 'langchain_version', 'library', 'platform', 'py_implementation', 'runtime', 'runtime_version', 'sdk', 'sdk_version']
runtime sample: {'sdk': 'langsmith-py', 'sdk_version': '0.15.0', 'runtime': 'python', 'py_implementation': 'CPython'}
requests made: [('POST', '/runs'), ('PATCH', '/runs/<run id>')]That run hides the most important fact. Run the same script after exporting what 2.2 told you to export (plus one invented variable, LANGSMITH_CUSTOMER_ID=cust-4242, to stand for any variable of your own with that prefix):
LANGSMITH_TRACING=true LANGSMITH_API_KEY=not-a-real-key LANGSMITH_PROJECT=support-bot \
LANGSMITH_ENDPOINT=https://eu.api.smith.langchain.com LANGSMITH_WORKSPACE_ID=ws-demo \
LANGSMITH_CUSTOMER_ID=cust-4242 python s14_payload_inspection.pyrun fields: ['attachments', 'dotted_order', 'end_time', 'events', 'extra', 'id', 'inputs', 'name', 'outputs', 'run_type', 'session_name', 'start_time', 'tags', 'trace_id']
metadata keys: ['LANGSMITH_CUSTOMER_ID', 'LANGSMITH_ENDPOINT', 'LANGSMITH_PROJECT', 'LANGSMITH_TRACING', 'LANGSMITH_WORKSPACE_ID', 'ls_method', 'revision_id']
env in metadata: {'LANGSMITH_TRACING': 'true', 'LANGSMITH_PROJECT': 'support-bot', 'LANGSMITH_ENDPOINT': 'https://eu.api.smith.langchain.com', 'LANGSMITH_WORKSPACE_ID': 'ws-demo', 'LANGSMITH_CUSTOMER_ID': 'cust-4242'}Every LANGSMITH_ and LANGCHAIN_ variable except the API key landed in the metadata of the uploaded run: the project, the endpoint, the workspace id and the invented customer id. The key was left out because its name contains key.
The facts:
- Inputs and outputs are uploaded in full: the prompt, the messages, the tool arguments, the tool results. This is the point of tracing and the reason Part 8 exists.
- Each run is two requests: a
POSTat the start and aPATCHat the end. - There is a
runtimeblock describing the SDK and library versions, the platform string (operating system and CPU architecture) and the Python version. It is useful for debugging a library mismatch and it is information about your machines that you did not put there. - Environment variables are copied into metadata. From the SDK source (
langsmith/env/_runtime_env.py, functionget_langchain_env_var_metadata) and the run above: every variable whose name startsLANGSMITH_orLANGCHAIN_is added to theextra.metadataof every run, unless it is on a short exclusion list (the API key,LANGCHAIN_ENDPOINT,LANGCHAIN_PROJECT,LANGCHAIN_SESSION,LANGCHAIN_TRACING_V2, the agent id and environment, and two signing-key variables) or its name containskey,secret,token,password,passwd,pwd,credentialoremail(case-insensitive). Note thatLANGSMITH_ENDPOINTandLANGSMITH_PROJECTare not excluded, as the output shows. So never put data in a variable with those prefixes (a customer id, a tenant name, an internal URL). It happens on both the@traceablepath and the LangChain tracer path (measured,s14c_two_paths.py), the SDK reads the environment once per process (the result is cached, so a variable changed after the first traced run is not picked up), and thehide_metadatasetting of 2.11 removes it (measured below). revision_idisgit describe. The SDK runsgit describe --tags --always --dirtyin the working directory and uploads the result asrevision_id: in this repository it was58740f9-dirty(a short hash, plus-dirtyfor uncommitted changes), and in a repository with tags it would be a tag name such asv1.4.0-3-g58740f9, so tag names are uploaded. SettingLANGSMITH_REVISION_ID(or the legacyLANGCHAIN_REVISION_ID) replaces it, and outside a git working tree it is simply absent (all measured). Under a LangChain component the metadata also gainsls_integrationand similar keys.hide_metadatacovers all of the above.Recorder(hide_metadata=True)produced an empty metadata dictionary for the same function (measured,s14b_revision.py:default:showed{'ls_method': 'traceable', 'LANGSMITH_CUSTOMER_ID': 'cust-4242', 'revision_id': '58740f9-dirty'},hide_metadata:showed{}). The cost is that your own tags in metadata (app_version,thread_id) go too, so prefer not to put sensitive values in prefixed variables over hiding everything.- The project name travels as
session_namefor project-based workspaces (and is absent for agent-addressed runs, 2.3).
2.11 Masking, sampling and TracePolicy#
Five mechanisms stop sensitive data reaching LangSmith. They act at different places, so know which covers what.
| Mechanism | Where it acts | Covers | Does not cover |
|---|---|---|---|
LANGSMITH_HIDE_INPUTS=true / LANGSMITH_HIDE_OUTPUTS=true / LANGSMITH_HIDE_METADATA |
The client, before upload, for every run | The whole part, replaced by an empty value | The other parts: hiding inputs leaves outputs |
Client(hide_inputs=..., hide_outputs=..., hide_metadata=...) |
One client; each accepts True or a function that receives the dict and returns what to upload |
The part you transform | Runs sent by other clients |
Client(anonymizer=create_anonymizer(...)) |
One client; rewrites matching strings inside inputs and outputs | Patterns (emails, card numbers, secrets) anywhere in the data, to a depth of 10 levels by default (max_depth) |
Data that does not match the pattern |
@traceable(process_inputs=..., process_outputs=...) |
One decorated function; each takes a function that receives the dict and returns what to upload | That function's own run, the per-function counterpart of the hide_* functions |
Other functions, and the metadata |
TracePolicy on a node (add_node(..., trace_policy=...)) |
One node's own run | That node's input and output, keeping the span and its timing | The root graph run and child runs of the node |
Measured with the recorder (s13b_process_io.py): a function decorated with process_inputs returning {"email": "<hidden>"} and process_outputs returning {"reply": "<hidden>"} still returned Receipt sent to sam@example.com to its caller, while the upload held {'email': '<hidden>'} and {'reply': '<hidden>'}. Like the client settings, these only cover traces sent through that function's client, which is why the 4.4 tests below use the recorder client.
Two precedence facts from the docs: the anonymizer takes precedence over hide_inputs and hide_outputs functions, and the anonymizer is skipped for inputs when LANGSMITH_HIDE_INPUTS is set (and likewise for outputs). This sample applies the first three to one function whose output echoes its input, the situation of a draft reply that quotes the customer:
# s13_masking.py: masking what a trace contains, three ways (all recorded locally, nothing is sent)
import re
import langsmith as ls
from langsmith import traceable
from langsmith.anonymizer import create_anonymizer, create_secret_anonymizer
from trace_recorder import Recorder
TEXT = "Please refund order A17 to sam@example.com, card ending 4242."
def trace_with(rec: Recorder) -> dict:
@traceable(client=rec.client, name="draft_reply")
def draft_reply(ticket: str) -> str:
return f"Refund queued for the customer who wrote: {ticket}"
with ls.tracing_context(enabled=True):
draft_reply(TEXT)
run = rec.runs()[0]
return {"inputs": run.get("inputs"), "outputs": run.get("outputs")}
print("1. no masking:", trace_with(Recorder()))
print("2. hide_inputs=True:", trace_with(Recorder(hide_inputs=True)))
email = create_anonymizer([{"pattern": re.compile(r"[\w.+-]+@[\w-]+\.[\w.]+"), "replace": "<email>"}])
print("3. anonymizer:", trace_with(Recorder(anonymizer=email)))
# 4. The SDK's preset for provider keys and similar secrets (extra_rules= adds your own patterns)
secrets = create_secret_anonymizer()
print("4. secret preset:", secrets({"note": "my key is sk-ant-abcdefghijklmnopqrstuvwxyz0123, please retry"}))1. no masking: {'inputs': {'ticket': 'Please refund order A17 to sam@example.com, card ending 4242.'}, 'outputs': {'output': 'Refund queued for the customer who wrote: Please refund order A17 to sam@example.com, card ending 4242.'}}
2. hide_inputs=True: {'inputs': {}, 'outputs': {'output': 'Refund queued for the customer who wrote: Please refund order A17 to sam@example.com, card ending 4242.'}}
3. anonymizer: {'inputs': {'ticket': 'Please refund order A17 to <email>, card ending 4242.'}, 'outputs': {'output': 'Refund queued for the customer who wrote: Please refund order A17 to <email>, card ending 4242.'}}
4. secret preset: {'note': 'my key is [SECRET_DETECTED], please retry'}Read line 2 twice. hide_inputs=True removed the input and left the same email in the output, because the function echoed it. Hiding one side is not hiding the data. The anonymizer in line 3 rewrote both sides. Line 4 shows the SDK's preset for provider keys, create_secret_anonymizer(); it accepts extra_rules for your own patterns. The docs also describe LangSmithSecret (Python only, langsmith>=0.12.3), a string subtype that marks a value as secret for uploads: masking applies only to what goes to LangSmith, and f-strings and .format drop the marker, so a secret that has been formatted into a prompt is plain text again. Read the redact-secrets page before relying on it.
Regular expressions catch patterns, not meaning: an anonymizer with an email rule does not know that "my daughter's school is Greenfield Primary" is personal. For regulated data, the stronger controls are not uploading the trace at all (sampling, conditional tracing, LANGSMITH_TRACING=false), a self-hosted LangSmith (Part 7), and a gateway that redacts before data reaches either model or tracer. 12.4 owns PII handling in depth.
TracePolicy is the finer tool: the trace_policy argument of add_node (present in langgraph 1.2.22) and, for the agent-middleware version, langchain>=1.3.15 (08F.8, 8.7 lists TracePolicy, omit_payload and configure_trace_policy). It transforms what one node's own run records with process_inputs and process_outputs, and omit_payload drops a payload entirely while keeping the span and its timing. configure_trace_policy(policy) sets a process-wide default for agent middleware hook spans (call it once at startup; pass None to clear it; a middleware's own policy replaces it wholesale). Here it is on a three-node graph:
# s16_trace_policy.py: TracePolicy: keep a node's span and timing but change or drop its recorded payload (recorded, not sent)
from typing import TypedDict
import langsmith as ls
from langchain.agents.middleware import omit_payload
from langgraph.graph import END, START, StateGraph
from langgraph.types import TracePolicy
from trace_recorder import Recorder
class State(TypedDict, total=False):
ticket: str
reply: str
def draft(state: State) -> dict:
return {"reply": f"Thanks for writing about: {state['ticket']}"}
def audit(state: State) -> dict:
return {}
builder = StateGraph(State)
builder.add_node("draft", draft) # recorded as usual
builder.add_node("audit", audit, trace_policy=TracePolicy(process_inputs=omit_payload, process_outputs=omit_payload))
builder.add_node("shout", lambda s: {"reply": s["reply"].upper()},
trace_policy=TracePolicy(process_outputs=lambda out: {"reply": "<hidden>"}))
builder.add_edge(START, "draft")
builder.add_edge("draft", "audit")
builder.add_edge("audit", "shout")
builder.add_edge("shout", END)
graph = builder.compile()
rec = Recorder()
with ls.tracing_context(enabled=True, client=rec.client):
graph.invoke({"ticket": "card declined"})
for run in rec.runs():
if run["name"] in ("draft", "audit", "shout"):
print(f"{run['name']:<6} inputs={run['inputs']} outputs={run['outputs']}")
root = rec.runs()[0] # the root graph run is not covered by a node's policy
print(f"{root['name']:<6} outputs={root['outputs']}")draft inputs={'ticket': 'card declined'} outputs={'reply': 'Thanks for writing about: card declined'}
audit inputs={} outputs={}
shout inputs={'ticket': 'card declined', 'reply': 'Thanks for writing about: card declined'} outputs={'reply': '<hidden>'}
LangGraph outputs={'ticket': 'card declined', 'reply': 'THANKS FOR WRITING ABOUT: CARD DECLINED'}audit kept its span but lost its payload; shout records a placeholder for its output. And the last line is the lesson: the root LangGraph run still holds the full text, because a node policy changes only that node's own run. The library's own docstring says it is "not intended to redact secrets": for that, use the client-level anonymizer or hide settings, which apply to every run, children included. TracePolicy is for trimming noise and obviously large or sensitive node payloads from the node view, not for security.
Sampling. LANGSMITH_TRACING_SAMPLING_RATE=0.1 keeps about one trace in ten, which cuts cost and exposure at the price of seeing fewer failures. Sample high-volume, low-risk paths; do not sample the paths you debug.
2.12 Retention, limits and what silently extends them#
From the usage-and-billing page (14 November 2026):
- Two retention tiers, and the extended one depends on where you host. The usage-and-billing page ("Retention periods", read in full on 18 November 2026) gives base 14 days everywhere, and extended 180 days on Cloud, 400 days on BYOC (the data-plane default) and 400 days when self-hosted (the Helm chart default). Enterprise customers can pick shorter extended periods on Cloud (30 to 180 days) and longer ones on BYOC (up to 400). A BYOC or self-hosted reader who plans on 180 days is planning on the wrong number. The page also says "Cloud traces ingested before September 14, 2026 keep the retention they had when ingested": a change to the Cloud limits applies to new traces, not to old ones. One older page (the concepts page) says SaaS "retains trace data for 180 days from ingestion"; the billing page is the detailed one.
- Some actions upgrade a base trace to extended retention, at a higher cost. Adding feedback through the API or SDK with
extend_trace_retention=true(inlangsmith0.14.17 and 0.15.0 the signature ofClient.create_feedbackshows that argument defaulting toTrue, so check it before scripting feedback at volume), online evaluators (with an opt-out), automation rules that extend retention (on by default for new evaluators and rules), and experiments (the page's section "How retention affects downstream features" says "Experiments: Runs are created at extended retention by default"). Feedback entered in the UI and manual annotation-queue additions do not upgrade by default. The practical effect: a cheap-looking "trace everything for 14 days" setup becomes more expensive when you attach evaluators to it. - Datasets have indefinite retention. If you add a trace's inputs and outputs to a dataset, they will never be deleted. That is a privacy fact as much as a feature: a dataset built from production traces keeps customer text forever unless you delete the examples.
- Billing metrics on the invoice: "LangSmith Traces (Base Charge)" for all traces and "LangSmith Traces (Extended Data Retention Upgrades)".
- Rate limits. The load balancer returns
429on one-minute windows:POST/PATCH /runs*5,000 per minute,*2,000 per minute,GET /runs/:id30 per minute,POST /feedbacks*5,000 per minute. Plan-level hourly event limits: Developer without a payment method 50,000 events per hour, Developer with one 250,000, Plus 500,000, Enterprise custom; hourly ingest 500 MB, 2.5 GB, 5.0 GB, custom. Developer without a payment method is also capped at 5,000 traces per month. The SDK batches up to 100 runs per call, which keeps most services far below the per-minute limits.
Part 7 gives the prices. All of these numbers are as of 14 November 2026 and can change: the usage-and-billing page is the source.
2.13 Reading a trace, and what to log beyond it#
A short routine when something went wrong, in the order that finds problems fastest:
- Start at the root and read down the tree in order. The first model run whose output looks wrong is usually the culprit, or the tool run before it.
- Check each tool run's arguments against the tool's schema. A model that passes
order_idas"A 17"shows up here, and 08F.8, Part 4 explains the recovery. - Count the loop. Many
modelandtoolspairs mean a loop that is not converging; compare with your limit (08F.8, 7.5). - Compare a good and a bad trace of the same input side by side before changing a prompt.
- Turn the bad trace into a dataset example (Part 3) so the regression stays caught.
Tracing records what happened inside your process. It does not replace business metrics (answers accepted, tickets resolved) or alerting; 11A.2 owns those. 08A.14, Part 3 lists what to log per step on any platform and builds a minimal tracer, which is what you fall back on if you leave LangSmith.
Same idea in JavaScript. The packages differ: langsmith on npm, traceable from langsmith/traceable, wrapOpenAI from langsmith/wrappers, a LangChainTracer callback for selective tracing, and LANGCHAIN_CALLBACKS_BACKGROUND matters on serverless there too. Timeouts and error handlers for LangGraph v1.2 are Python-only.
Part 3: Datasets, experiments and evaluators#
Tracing shows what one request did. Evaluation answers "is this system good, and did my change make it better or worse?" across many requests. This part is the LangSmith mechanics. The design of a good eval set, the choice of metrics, judge calibration and CI gating are Module 10A; for agents specifically, 08A.14, Part 4 built a from-scratch harness, and 08F.9, 12.3 used LangSmith for retrieval.
3.1 The concepts#
| Concept | What it is |
|---|---|
| Dataset | A collection of examples. An example has inputs (a dict), optional outputs (the reference outputs, a dict that is never passed to your app) and optional metadata. |
| Dataset version | Every add, update or delete creates a version, identified by a timestamp by default. A version can be tagged (for example prod), and an evaluation can target a version or a split. |
| Experiment | The result of evaluating one version of your application on a dataset: the outputs, the evaluator scores and a trace per example. Several experiments on the same dataset can be compared side by side. |
| Evaluator | A function (or an LLM judge, or a human) that scores one run. Its result is feedback: a dict, or a list of dicts, with key, score (numeric) or value (categorical) and an optional comment. |
| Offline evaluation | Runs on dataset examples before release. It can use reference outputs, so it fits benchmarks, regression tests and backtests. |
| Online evaluation | Runs on production runs or threads, with no reference outputs. It fits monitoring and anomaly detection. |
Evaluators are workspace-level resources, so one evaluator can be attached to many projects, agent environments or datasets. The techniques the docs list: human review (annotation queues), code evaluators, LLM-as-judge, decision models (typed questions) and pairwise comparison. 10A.4 and 10A.9 own the theory.
3.2 Creating a dataset in code#
This needs langsmith>=0.3.13 and a real account, so it is illustrative:
from dotenv import load_dotenv
from langsmith import Client
load_dotenv() # LANGSMITH_API_KEY must be set before the Client is used
client = Client()
dataset = client.create_dataset(dataset_name="support-triage-v1", description="Hand-labelled tickets")
client.create_examples(
dataset_id=dataset.id,
examples=[
{"inputs": {"text": "URGENT: card charged twice"}, "outputs": {"label": "urgent"}},
{"inputs": {"text": "How do I change my email?"}, "outputs": {"label": "account"}},
{"inputs": {"text": "Where is order A17?"}, "outputs": {"label": "orders"}},
],
)
# Tag the current state of the dataset so experiments can be pinned to it later.
from datetime import datetime, timezone
client.update_dataset_tag(dataset_name="support-triage-v1", as_of=datetime.now(timezone.utc), tag="prod")This sample is illustrative: it writes to your LangSmith workspace, and the argument names (dataset_name, examples, as_of, tag) match the 0.14.17 signatures read from the installed package. In langsmith 0.14.17 create_examples has a max_concurrency argument constrained to 1 to 3. Datasets are normally built from three sources, in this order of value: failures from production traces (add the run's inputs and outputs from the UI), hand-written edge cases you know matter, and synthetic examples (Module 05 owns synthetic data). client.list_examples(dataset_name=..., as_of=..., splits=[...]) reads a version or a split back.
3.3 Evaluators are functions#
The most useful fact in this part: an evaluator is a plain Python function, so you can write it, call it and unit-test it before any experiment exists. A code evaluator asks for any subset of five argument names (run, example, inputs, outputs, reference_outputs) and returns one of:
| Return type | Meaning |
|---|---|
dict with key and score or value |
One named metric (Python and JavaScript) |
bool, int, float |
One metric, named after the function (Python) |
str |
A categorical result (Python) |
list[dict] |
Several metrics from one function (Python) |
The sample calls three evaluators of those shapes on one hand-made run, then two ready-made ones from openevals and agentevals (3.6):
# s20_local_evaluators.py: evaluators are plain functions: write them, call them, test them before any experiment exists
from openevals.exact import exact_match
from agentevals.trajectory.match import create_trajectory_match_evaluator
# --- 1. a code evaluator: ask for only the arguments you need -------------------------------
def correct(outputs: dict, reference_outputs: dict) -> bool: # bool: the metric is named after the function
return outputs["label"] == reference_outputs["label"]
def short_enough(outputs: dict) -> dict: # dict: you name the key and give a score
return {"key": "short_enough", "score": len(outputs["answer"].split()) <= 12}
def triage_quality(inputs: dict, outputs: dict, reference_outputs: dict) -> list[dict]: # list: several metrics at once
return [
{"key": "label_match", "score": outputs["label"] == reference_outputs["label"]},
{"key": "urgent_caught", "score": not ("urgent" in inputs["text"].lower() and outputs["label"] != "urgent")},
]
example_inputs = {"text": "URGENT: card charged twice"}
example_reference = {"label": "urgent"}
run_outputs = {"label": "billing", "answer": "We will refund the duplicate charge within five days."}
print(correct(run_outputs, example_reference))
print(short_enough(run_outputs))
print(triage_quality(example_inputs, run_outputs, example_reference))
# --- 2. a ready-made evaluator from openevals (deterministic, no model) --------------------------
print(exact_match(outputs="Paris", reference_outputs="Paris"))
print(exact_match(outputs="paris", reference_outputs="Paris"))
# --- 3. trajectory evaluators from agentevals: did the agent call the right tools? ---------------
def call(name: str, **args) -> dict:
import json
return {"role": "assistant", "content": "", "tool_calls": [{"function": {"name": name, "arguments": json.dumps(args)}}]}
reference = [
{"role": "user", "content": "Where is order A17?"},
call("get_order_status", order_id="A17"),
{"role": "tool", "content": "shipped"},
{"role": "assistant", "content": "Order A17 has shipped."},
]
extra_step = [
{"role": "user", "content": "Where is order A17?"},
call("get_customer", customer_id="c9"), # an extra tool call the reference does not have
{"role": "tool", "content": "Sam"},
call("get_order_status", order_id="A17"),
{"role": "tool", "content": "shipped"},
{"role": "assistant", "content": "Order A17 has shipped."},
]
for mode in ("strict", "unordered", "subset", "superset"):
result = create_trajectory_match_evaluator(trajectory_match_mode=mode)(outputs=extra_step, reference_outputs=reference)
print(f"{mode:<10} {result['key']:<28} {result['score']}")False
{'key': 'short_enough', 'score': True}
[{'key': 'label_match', 'score': False}, {'key': 'urgent_caught', 'score': False}]
{'key': 'exact_match', 'score': True, 'comment': None, 'metadata': None}
{'key': 'exact_match', 'score': False, 'comment': None, 'metadata': None}
strict trajectory_strict_match False
unordered trajectory_unordered_match False
subset trajectory_subset_match False
superset trajectory_superset_match TrueWhat to read in it:
correctreturnedFalse: the model saidbillingand the reference saysurgent. The one metric is namedcorrectin an experiment.triage_qualityreturned two metrics at once, and its second one encodes a domain rule ("an urgent ticket must be labelled urgent") that a plain label match would not.exact_matchis case-sensitive:parisagainstParisis a miss. Know what your evaluators are strict about.- The four trajectory modes disagree on the same pair, which is the point of having four. The agent made one extra tool call (
get_customer) before the one the reference expects.strict(same calls, same order) andunordered(same calls, any order) fail;subset(the agent called only tools that appear in the reference) fails;superset(the agent called every tool in the reference, and possibly more) passes. Choose the mode that states your actual requirement:supersetfor "must at least do this",strictfor a fixed procedure.
3.4 Running an experiment#
client.evaluate(target, data=..., evaluators=[...]) runs target on every example, scores each run, uploads the traces and results, and returns the results. It can also be imported as from langsmith import evaluate, and the async twin is aevaluate. The target takes the example's inputs dict and returns an outputs dict. Illustrative (it needs an account and a dataset):
from langsmith import Client
client = Client()
def triage(inputs: dict) -> dict:
# Your application: here a call into your agent or chain, returning a dict.
return {"label": "urgent" if "urgent" in inputs["text"].lower() else "orders"}
def correct(outputs: dict, reference_outputs: dict) -> bool:
return outputs["label"] == reference_outputs["label"]
results = client.evaluate(
triage,
data="support-triage-v1", # a dataset name or id; or an iterable of examples
evaluators=[correct],
experiment_prefix="triage-baseline",
description="Keyword rule, before the model",
max_concurrency=4, # the docs advise setting this for large jobs
metadata={"app_version": "1.4.0"},
)This sample is illustrative, because it talks to LangSmith. The signature in langsmith 0.14.17 shows the other options you will use:
| Argument | Use |
|---|---|
summary_evaluators |
Score the whole experiment (a precision across all examples) instead of one run |
num_repetitions |
Run each example several times, for stochastic apps |
experiment |
Add evaluators to, or continue, an existing experiment |
blocking |
True by default: wait for the run to finish |
error_handling |
'log' (default) or 'ignore' for failing examples |
upload_results |
Beta. See 3.5 before trusting it |
disable_evaluator_tracing |
Do not trace the evaluators themselves |
The target argument also accepts a Runnable, so a compiled graph can be passed directly when its input and output keys match the dataset's. Dataset evaluators configured in the UI are triggered too. Python-only helpers exist to add evaluators to an existing experiment, run locally, and retry failed runs.
Evaluating a graph. The how-to builds a StateGraph, wraps graph.invoke in a target function and passes that to evaluate. The wrapper is where you map the dataset's inputs to the graph's input state and the final state to the outputs dict. Inside the wrapper, give the call a thread_id unique to the example (uuid4()), or examples share conversation state through the checkpointer. The docs add that you can evaluate intermediate steps (the output of one node or tool call) and trajectories, by reading them from the run's child runs or from the graph's state (evaluate-on-intermediate-steps and trajectory-evals).
3.5 An observation: evaluate offline is not offline#
A natural thought: "I want to try my evaluators in CI without sending anything, so I will pass upload_results=False". This is the one place where the parameter name promises more than the behaviour. The measurement below was made with the network blocked on purpose: the sample replaces the HTTP adapter with one that records each attempted request and fails it, so nothing leaves the machine, and passes local Example objects so no dataset is read from the server.
# s21_evaluate_offline.py: does langsmith.evaluate(..., upload_results=False) stay offline? Measured with the network blocked.
import time
import uuid
import requests
attempts: list[tuple[str, str]] = []
def refuse(self, request, **kwargs): # record the attempt, then fail: nothing leaves this machine
attempts.append((request.method, request.url.replace("https://api.smith.langchain.com", "")))
raise requests.ConnectionError("blocked on purpose")
requests.adapters.HTTPAdapter.send = refuse
import langsmith as ls
from langchain_core.language_models import FakeListChatModel
from langchain_core.runnables import RunnableLambda
from langsmith import evaluate
from langsmith.schemas import Example
chain = RunnableLambda(lambda x: x["text"]) | FakeListChatModel(responses=["Toxic", "Not toxic"])
def plain_target(inputs: dict) -> dict: # no LangChain object inside
return {"label": "Toxic" if "idiot" in inputs["text"] else "Not toxic"}
def chain_target(inputs: dict) -> dict: # a LangChain runnable inside
return {"label": chain.invoke(inputs).text}
def correct(outputs: dict, reference_outputs: dict) -> bool:
return outputs["label"] == reference_outputs["label"]
def examples() -> list[Example]: # local Example objects: no dataset is read from the server
rows = [("Shut up, idiot", "Toxic"), ("Have a nice day", "Not toxic")]
return [Example(id=uuid.uuid4(), dataset_id=uuid.uuid4(), inputs={"text": t}, outputs={"label": label}) for t, label in rows]
def attempted(label: str, run) -> None:
attempts.clear()
results = run()
time.sleep(1.5) # uploads happen on a background thread
print(f"{label}: scores={[r['evaluation_results']['results'][0].score for r in results]} attempted={sorted(set(attempts))}")
kwargs = dict(evaluators=[correct], upload_results=False, blocking=True)
attempted("plain target", lambda: evaluate(plain_target, data=examples(), **kwargs))
attempted("LangChain chain in target", lambda: evaluate(chain_target, data=examples(), **kwargs))
def wrapped():
with ls.tracing_context(enabled=False):
return evaluate(chain_target, data=examples(), **kwargs)
attempted("same, inside tracing_context(enabled=False)", wrapped)plain target: scores=[True, True] attempted=[('GET', '/info')]
LangChain chain in target: scores=[True, True] attempted=[('POST', '/runs/multipart')]
same, inside tracing_context(enabled=False): scores=[True, True] attempted=[('POST', '/runs/multipart')]What it shows:
- The scores are computed locally in every case:
[True, True]. - With a plain-Python target, the only attempt was a
GET /info(the client asking the server what it supports). - With a LangChain runnable inside the target, a
POST /runs/multipartwas attempted, which is the trace upload, even withupload_results=False. An earlier lesson of this module (08F.9) saw the same thing without the blocker: toy questions and retrieved text were POSTed toapi.smith.langchain.comand answered with a 401 because there was no key. - Wrapping the call in
tracing_context(enabled=False)did not stop it, and neither didLANGSMITH_TRACING=false(also tried, with the same result). - Setting
LANGSMITH_TRACING_SAMPLING_RATE=0did. Running the same file with that variable set (a separate run) printed:
plain target: scores=[True, True] attempted=[('GET', '/info')]
LangChain chain in target: scores=[True, True] attempted=[]
same, inside tracing_context(enabled=False): scores=[True, True] attempted=[]So the parameter keeps the evaluation results local in beta, but traces of LangChain components inside the target are still handed to the default tracer. This is an observation about one SDK version, not a statement about how the docs describe the feature. What to do about it:
| Goal | Do this |
|---|---|
| Try an evaluator on a few hand-made runs | Call it as a function (3.3). No SDK machinery, no network |
Run the full evaluate machinery in CI with no upload |
Do not rely on upload_results=False alone. Block egress in the CI job, or set the sampling rate to 0 for that job, and test that nothing is attempted with a blocked adapter like the one above |
| Run experiments properly | Use a real key and a dedicated project or environment, and accept the retention cost |
3.6 LLM-as-judge and trajectory evaluators#
Some qualities cannot be checked with ==: whether an answer is correct in different words, whether a tone is polite. The usual answer is LLM-as-judge: a model scores the output against a rubric. LangChain's open-source packages openevals (single-turn, MIT) and agentevals (trajectories, MIT) ship the plumbing. A judge makes a model call, so this sample is illustrative:
from dotenv import load_dotenv
from openevals.llm import create_llm_as_judge
from openevals.prompts import CORRECTNESS_PROMPT
load_dotenv()
correctness = create_llm_as_judge(
prompt=CORRECTNESS_PROMPT,
feedback_key="correctness",
model="openai:your-current-model-id", # "<provider>:<model>"; pick a current model from the provider's page
)
# Called like any evaluator, with the arguments your experiment provides:
# correctness(inputs=..., outputs=..., reference_outputs=...) -> {"key": "correctness", "score": True, ...}This sample is illustrative: it calls a provider, and the judge model id is yours to choose (the course's current ids are in 02.9). The signature in openevals 0.2.5 also accepts judge= (an existing chat model), continuous (a score from 0 to 1), choices, use_reasoning and few_shot_examples. Judges drift, favour their own family's phrasing and are biased by length and position, so calibrate against human labels before trusting one: 10A.5 is the lesson for it, and 10A.4 for the design.
Trajectory evaluators (agentevals) answer the agent-specific question "did it take a sensible path?". The deterministic one, create_trajectory_match_evaluator, ran in 3.3 with four modes; it needs no model. The model-based one, create_trajectory_llm_as_judge, takes a prompt (TRAJECTORY_ACCURACY_PROMPT is the default) and a model. Async variants add async after create_ in the function name. A graph-trajectory helper (extract_langgraph_trajectory_from_thread in agentevals.graph_trajectory.utils) exists for evaluating a LangGraph thread. The official page for the layered approach is the LangChain "Evals" page under Test.
3.7 The pytest plugin#
For teams that want evals to live in the test suite, langsmith ships a pytest plugin (pip install -U "langsmith[pytest]", langsmith>=0.3.4). Mark a test with @pytest.mark.langsmith, log inputs, outputs and reference outputs with from langsmith import testing as t, and run with LANGSMITH_TEST_SUITE='My suite' pytest tests/ (add --langsmith-output for a table). Each test file becomes a dataset, each run an experiment, and each test gets a default pass boolean feedback key. Logging a value twice overwrites the first. The docs' example:
# test_langsmith_marker.py: the LangSmith pytest plugin. Without tracking, the same test is an ordinary pytest test.
import pytest
from langsmith import testing as t
@pytest.mark.langsmith
def test_sum_is_logged():
t.log_inputs({"a": 1, "b": 2})
result = 1 + 2
t.log_outputs({"sum": result})
t.log_reference_outputs({"sum": 3})
assert result == 3
t.log_feedback(key="exact", score=1)Run with LANGSMITH_TEST_TRACKING=false pytest test_langsmith_marker.py (real result, network blocked):
test_langsmith_marker.py . [100%]
1 passedThe plugin registers itself when langsmith is installed (pytest's plugin list shows langsmith-0.14.17), so the marker is live in every project that has the SDK. The author ran this test twice with the network blocked:
- Default settings: the test failed, with a connection error from
GET /datasets: the plugin tries to create the dataset and experiment before it runs your assertions. - With
LANGSMITH_TEST_TRACKING=false: the test passed and no request was attempted (the pytest summary line was1 passed). Thet.log_*calls become no-ops, and the test is an ordinary pytest test.
So a marked test cannot run offline unless tracking is switched off. Put LANGSMITH_TEST_TRACKING=false in the default test environment, and set it to true only in the CI job that has a key and wants the experiment. Two more variables control the plugin: LANGSMITH_TEST_SUITE (the dataset name) and LANGSMITH_TEST_CACHE (response caching for faster, cheaper re-runs; check the docs for the exact behaviour, which this lesson did not test).
3.8 The rest of the evaluation toolbox, in one line each#
| Piece | One line |
|---|---|
| Annotation queues | Route runs to human reviewers; manual additions do not upgrade retention by default |
| Online evaluators and automation rules | Score production runs automatically; they can upgrade retention (2.12). The rule webhooks are not the Agent Server run webhooks of 6.9 |
| Playground | Edit a prompt and run it against a dataset in the browser |
| Engine | An agent that turns traces into tracked issues and proposed fixes (survey only: 08F.4, 6.3) |
| Fleet | No-code agents (formerly Agent Builder) |
The index of the whole agent-development lifecycle is in the docs under docs.langchain.com/_llms/agent-development-lifecycle.txt; start there when a feature name in this table is new to you.
Part 4: Testing agents and graphs without an account#
4.1 Three layers#
LangChain's official testing pages split the work into three layers, and the split is worth adopting as it stands:
| Layer | What it checks | Needs | Speed and cost |
|---|---|---|---|
| Unit tests | Your control flow: routing, state updates, tool wiring, middleware, persistence behaviour | In-memory fakes, no network | Milliseconds, free |
| Integration tests | That real components work together: a real model, real tools, real network | Keys, network | Seconds, costs money, can be flaky |
| Evals | How good the behaviour is: trajectory scores by deterministic matching or an LLM judge | A dataset, usually a key | Minutes, costs money |
The docs add a remark that explains why a LangChain project cannot stop at unit tests: "Agentic applications tend to lean more on integration because they chain multiple components together." A fake proves your wiring. It cannot prove that a real model picks the right tool, which is what Parts 3 and the last section of this part are for.
Earlier lessons already gave you the basic keyless tools, and this part builds on them rather than repeating them: 08F.8, Part 12 (what to test in an agent and with what), 08F.10, 13.3 (a node, a path and the topology), 08F.7 (testing chains), and the general mocking material of 03.10. New here: the exact traps the official pages call out, the patterns for partial execution and interrupts, tests for your tracing and masking configuration, and the integration layer.
4.2 Fake models and the bind_tools trap#
GenericFakeChatModel (in langchain_core.language_models.fake_chat_models) takes an iterator of AIMessage objects or plain strings and returns the next one on every call. It supports invoke and streaming. Two consequences, one gentle and one nasty:
- An iterator is used up. Call the model more times than you scripted and it stops (
StopIteration). Keep pytest fixtures at the default function scope so each test gets a fresh script; a module-scoped fixture is the classic way to get a test that passes alone and fails in the suite. create_agentcallsbind_tools, and the plain fake does not implement it. The docs say so explicitly and prescribe the two-line subclass infakes.py.
The sample runs both failures and the fix:
# s01_bind_tools_gotcha.py: why a plain GenericFakeChatModel cannot drive create_agent, and the two-line fix
from langchain.agents import create_agent
from langchain.messages import AIMessage, HumanMessage, ToolCall
from langchain.tools import tool
from langchain_core.language_models.fake_chat_models import GenericFakeChatModel
@tool
def get_weather(city: str) -> str:
"""Get the weather for a city."""
return f"Sunny in {city}"
def script():
return iter([
AIMessage(content="", tool_calls=[ToolCall(name="get_weather", args={"city": "Paris"}, id="call_1")]),
AIMessage(content="It is sunny in Paris."),
])
# 1. The plain fake: create_agent calls model.bind_tools(...) and the fake does not implement it.
try:
create_agent(GenericFakeChatModel(messages=script()), tools=[get_weather]).invoke(
{"messages": [HumanMessage("Weather in Paris?")]}
)
except Exception as exc:
print("plain fake ->", type(exc).__name__)
# 2. The fix from the docs: return the model unchanged from bind_tools.
class FakeToolCallingModel(GenericFakeChatModel):
def bind_tools(self, tools, **kwargs):
return self
agent = create_agent(FakeToolCallingModel(messages=script()), tools=[get_weather])
result = agent.invoke({"messages": [HumanMessage("Weather in Paris?")]})
for message in result["messages"]:
print(type(message).__name__, "|", message.text or message.tool_calls)plain fake -> NotImplementedError
HumanMessage | Weather in Paris?
AIMessage | [{'name': 'get_weather', 'args': {'city': 'Paris'}, 'id': 'call_1', 'type': 'tool_call'}]
ToolMessage | Sunny in Paris
AIMessage | It is sunny in Paris.And the iterator behaviour, plus the other fake, FakeListChatModel (from langchain_core.language_models), which takes a list of responses and cycles when called more often than the list is long:
# s02_exhausted_script.py: a scripted model is an iterator: call it more often than you scripted and it stops
from langchain.messages import AIMessage
from langchain_core.language_models import FakeListChatModel
from langchain_core.language_models.fake_chat_models import GenericFakeChatModel
generic = GenericFakeChatModel(messages=iter([AIMessage(content="one"), "two"])) # strings are accepted too
print(generic.invoke("a").text, generic.invoke("b").text)
try:
generic.invoke("c")
except BaseException as exc: # the exact type depends on where the iterator ran out
print("third call ->", type(exc).__name__)
cycling = FakeListChatModel(responses=["Paris", "The Eiffel Tower"])
print([cycling.invoke("q").text for _ in range(3)]) # FakeListChatModel starts again from the top
# streaming works on both; the generic fake splits the text into word-like chunks
streamer = GenericFakeChatModel(messages=iter(["hello brave new world"]))
print([chunk.text for chunk in streamer.stream("hi")])one two
third call -> StopIteration
['Paris', 'The Eiffel Tower', 'Paris']
['hello', ' ', 'brave', ' ', 'new', ' ', 'world']Pick by need. FakeListChatModel for a chain that makes one call per test (a prompt-and-parser chain, a node that calls a model once): its cycling is harmless there and sometimes convenient, though it can hide a bug in which the code calls the model more often than it should. GenericFakeChatModel (and the bind_tools subclass) when you need tool-call messages, or when a test should fail loudly if the model is called a third time. The generic fake splits streamed text into word-and-space chunks, so a streaming test sees realistic token-like chunks.
4.3 A graph under test#
Design for testability from the start: build the graph in a function that takes the model and the checkpointer. The unit test supplies a fake and an in-memory saver; production supplies the real ones. This is the graph used for the tests below: classify a ticket in plain Python, draft a reply with a model, and pause for human approval.
# support_app.py: a small support-ticket graph used by the tests (the model is injected, so tests can fake it)
from typing import TypedDict
from langchain_core.language_models import BaseChatModel
from langgraph.checkpoint.base import BaseCheckpointSaver
from langgraph.graph import END, START, StateGraph
from langgraph.types import interrupt
class TicketState(TypedDict, total=False):
ticket: str
category: str
draft: str
approved: bool
def build_graph(model: BaseChatModel, checkpointer: BaseCheckpointSaver | None = None):
def classify(state: TicketState) -> dict:
# Plain Python: deterministic, so a unit test needs no model at all.
category = "billing" if "refund" in state["ticket"].lower() else "general"
return {"category": category}
def draft(state: TicketState) -> dict:
reply = model.invoke(f"Write a short {state['category']} reply to: {state['ticket']}")
return {"draft": reply.text}
def approve(state: TicketState) -> dict:
decision = interrupt({"draft": state["draft"], "question": "Send this reply?"})
return {"approved": decision == "yes"}
builder = StateGraph(TicketState)
builder.add_node("classify", classify)
builder.add_node("draft", draft)
builder.add_node("approve", approve)
builder.add_edge(START, "classify")
builder.add_edge("classify", "draft")
builder.add_edge("draft", "approve")
builder.add_edge("approve", END)
return builder.compile(checkpointer=checkpointer)And the tests. Each one has a reason:
# test_support_app.py: unit tests for support_app.py. No key, no network, no LangSmith.
import pytest
from langchain.agents import create_agent
from langchain.messages import AIMessage, HumanMessage, ToolCall
from langchain.tools import tool
from langchain_core.language_models import FakeListChatModel
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.types import Command
from fakes import FakeToolCallingModel
from support_app import build_graph
@pytest.fixture
def graph():
# function scope (the default): a fresh checkpointer and a fresh fake for every test
model = FakeListChatModel(responses=["Your refund is on its way."])
return build_graph(model, checkpointer=InMemorySaver())
def test_one_node_alone(graph):
# Runs just this node. The checkpointer is bypassed, and so are the other nodes.
assert graph.nodes["classify"].invoke({"ticket": "I want a REFUND"}) == {"category": "billing"}
assert graph.nodes["classify"].invoke({"ticket": "Where is my parcel?"}) == {"category": "general"}
def test_partial_run(graph):
config = {"configurable": {"thread_id": "t-partial"}}
# Pretend `classify` already ran, then run only `draft` and stop before `approve`.
graph.update_state(config, {"ticket": "Refund please", "category": "billing"}, as_node="classify")
graph.invoke(None, config, interrupt_after="draft")
snapshot = graph.get_state(config)
assert snapshot.values["draft"] == "Your refund is on its way."
assert snapshot.next == ("approve",)
@pytest.mark.parametrize("answer, approved", [("yes", True), ("no", False)])
def test_interrupt_and_resume(graph, answer, approved):
config = {"configurable": {"thread_id": f"t-{answer}"}}
first = graph.invoke({"ticket": "Refund please"}, config)
assert first["__interrupt__"][0].value["draft"] == "Your refund is on its way."
final = graph.invoke(Command(resume=answer), config)
assert final["approved"] is approved
def test_resume_in_a_fresh_graph_instance():
# Rehearses a restart: a second graph object that shares only the saver picks the paused thread up.
saver = InMemorySaver()
config = {"configurable": {"thread_id": "t-restart"}}
first = build_graph(FakeListChatModel(responses=["Original draft."]), saver)
first.invoke({"ticket": "Refund please"}, config) # pauses at approve()
del first # the "process" ends
second = build_graph(FakeListChatModel(responses=["MUST NOT BE USED"]), saver)
final = second.invoke(Command(resume="yes"), config)
assert final["draft"] == "Original draft." and final["approved"] is True # draft was not regenerated
@tool
def get_order_status(order_id: str) -> str:
"""Look up an order."""
return f"Order {order_id}: shipped"
def test_tool_loop_with_scripted_model():
model = FakeToolCallingModel(messages=iter([
AIMessage(content="", tool_calls=[ToolCall(name="get_order_status", args={"order_id": "A17"}, id="c1")]),
AIMessage(content="Order A17 has shipped."),
]))
agent = create_agent(model, tools=[get_order_status])
result = agent.invoke({"messages": [HumanMessage("Where is A17?")]})
kinds = [type(m).__name__ for m in result["messages"]]
assert kinds == ["HumanMessage", "AIMessage", "ToolMessage", "AIMessage"] # structure, not wording
assert result["messages"][1].tool_calls[0]["name"] == "get_order_status"
assert result["messages"][2].content == "Order A17: shipped"
assert result["messages"][-1].text == "Order A17 has shipped."
def test_two_turns_share_a_thread():
model = FakeToolCallingModel(messages=iter([AIMessage(content="Hello Sam."), AIMessage(content="You are Sam.")]))
agent = create_agent(model, tools=[], checkpointer=InMemorySaver())
config = {"configurable": {"thread_id": "session-1"}}
agent.invoke({"messages": [HumanMessage("I am Sam")]}, config)
second = agent.invoke({"messages": [HumanMessage("Who am I?")]}, config)
assert len(second["messages"]) == 4 # turn 1 survived
other = agent.get_state({"configurable": {"thread_id": "session-2"}})
assert other.values == {} # another thread is empty
def test_list_model_cycles():
model = FakeListChatModel(responses=["a", "b"])
assert [model.invoke("x").text for _ in range(5)] == ["a", "b", "a", "b", "a"]test_support_app.py::test_one_node_alone PASSED
test_support_app.py::test_partial_run PASSED
test_support_app.py::test_interrupt_and_resume[yes-True] PASSED
test_support_app.py::test_interrupt_and_resume[no-False] PASSED
test_support_app.py::test_resume_in_a_fresh_graph_instance PASSED
test_support_app.py::test_tool_loop_with_scripted_model PASSED
test_support_app.py::test_two_turns_share_a_thread PASSED
test_support_app.py::test_list_model_cycles PASSED
8 passedWhat each test is for, and the docs' guidance behind it:
| Test | Technique | Notes |
|---|---|---|
test_one_node_alone |
graph.nodes["classify"].invoke({...}) |
Runs only that node. It bypasses the checkpointer and the other nodes, so it tests the function in isolation. Use it for every deterministic node |
test_partial_run |
update_state(config, values, as_node="classify"), then invoke(None, config, interrupt_after="draft") |
Pretends the first node already ran and executes only the middle one. The docs use exactly this pattern to run "just nodes 2 and 3". snapshot.next == ("approve",) proves the graph stopped where you said |
test_interrupt_and_resume |
first["__interrupt__"], then invoke(Command(resume=answer), config) |
The approval path both ways, parametrized. The interrupt payload is data you can assert on (08F.12) |
test_resume_in_a_fresh_graph_instance |
Two graph objects, one shared InMemorySaver, the same thread_id |
Rehearses a restart: the first pauses at the approval and is deleted; the second resumes and must not regenerate the draft (a model that fails the test if called). The in-memory form of 08F.11, Part 4 |
test_tool_loop_with_scripted_model |
Two scripted turns: a tool call, then a final answer | Assert on structure (message types, the tool name, the tool message), not on wording |
test_two_turns_share_a_thread |
InMemorySaver plus a fixed thread_id; a second thread_id is empty |
The way to simulate multi-turn state without a database |
test_list_model_cycles |
FakeListChatModel |
Documents the cycling so nobody is surprised |
Four practices the official pages recommend and the tests follow:
- Compile per test with a new checkpointer. A compiled graph with a checkpointer is stateful; a module-level graph shared by tests leaks state between them. The
graphfixture builds a fresh graph and a freshInMemorySaverper test. (The LangGraph test page importsMemorySaver;InMemorySaveris the same class under the current name, inlanggraph.checkpoint.memory.) - Assert on structure, not content. Message types, tool-call names, argument shapes and message counts survive a prompt edit. Exact wording does not.
- One behaviour per test. A failing test should name one thing.
- Test the topology as well (
graph.get_graph().edges, 08F.10) so that a refactor which rewires the graph fails a test instead of silently changing behaviour.
InMemorySaver forgets everything when the process ends, which is what you want in a test and exactly what you do not want in production (08F.11, Part 5). A test that passes on InMemorySaver proves the logic of persistence (state is carried between calls on a thread), not the behaviour of your production database; a separate integration test against a real Postgres is the test for that. bulk_update_state (08F.11) is the batch form of update_state when a test needs to seed several steps.
4.4 Testing your tracing and masking configuration#
A privacy control that is not tested is a hope. The recorder from Setup makes the tracing configuration a unit-testable thing: run the real agent with tracing on, capture what would be uploaded, and assert on it.
# test_tracing_config.py: tests for your tracing setup itself: tags, metadata and masking, checked on recorded runs
import re
import langsmith as ls
from langchain.agents import create_agent
from langchain.messages import AIMessage, HumanMessage, ToolCall
from langchain.tools import tool
from langsmith.anonymizer import create_anonymizer
from langsmith.env import get_langchain_env_var_metadata
from fakes import FakeToolCallingModel
from trace_recorder import Recorder
@tool
def send_receipt(email: str) -> str:
"""Email a receipt."""
return f"sent to {email}"
def run_agent(rec: Recorder) -> list[dict]:
model = FakeToolCallingModel(messages=iter([
AIMessage(content="", tool_calls=[ToolCall(name="send_receipt", args={"email": "sam@example.com"}, id="c1")]),
AIMessage(content="Done."),
]))
agent = create_agent(model, tools=[send_receipt])
with ls.tracing_context(enabled=True, client=rec.client):
agent.invoke(
{"messages": [HumanMessage("Send my receipt")]},
config={"tags": ["support"], "metadata": {"app_version": "1.4.0"}},
)
return rec.runs()
def test_every_run_carries_the_release_tags():
runs = run_agent(Recorder())
assert len(runs) >= 5
assert all("support" in run["tags"] for run in runs)
assert all(run["extra"]["metadata"]["app_version"] == "1.4.0" for run in runs)
def test_email_addresses_never_reach_the_upload():
email = create_anonymizer([{"pattern": re.compile(r"[\w.+-]+@[\w-]+\.[\w.]+"), "replace": "<email>"}])
uploaded = str(run_agent(Recorder(anonymizer=email)))
assert "sam@example.com" not in uploaded
assert "<email>" in uploaded
def test_without_the_anonymizer_the_address_is_uploaded(): # the control: proves the test above can fail
assert "sam@example.com" in str(run_agent(Recorder()))
def test_prefixed_variables_are_uploaded_unless_metadata_is_hidden(monkeypatch):
monkeypatch.setenv("LANGSMITH_CUSTOMER_ID", "cust-4242") # any LANGSMITH_ or LANGCHAIN_ variable is copied into metadata (2.10)
get_langchain_env_var_metadata.cache_clear() # the SDK reads the environment once per process
try:
assert "cust-4242" in str(run_agent(Recorder())) # the control: the leak is real
assert "cust-4242" not in str(run_agent(Recorder(hide_metadata=True)))
finally:
monkeypatch.undo()
get_langchain_env_var_metadata.cache_clear()test_tracing_config.py::test_every_run_carries_the_release_tags PASSED [ 25%]
test_tracing_config.py::test_email_addresses_never_reach_the_upload PASSED [ 50%]
test_tracing_config.py::test_without_the_anonymizer_the_address_is_uploaded PASSED [ 75%]
test_tracing_config.py::test_prefixed_variables_are_uploaded_unless_metadata_is_hidden PASSED [100%]
4 passedFour tests, four jobs. The first checks that every run in the tree carries the tags and metadata your dashboards depend on (a decorated helper that drops them is a bug you would otherwise find in production). The second checks that an email address in a tool call never appears anywhere in the upload, including the model's tool-call arguments, which are easy to forget. The third is the control: without the anonymizer the address is uploaded, which proves the second test can fail. The fourth test guards the leak of 2.10: a LANGSMITH_-prefixed variable that carries data is uploaded in metadata, and hide_metadata=True removes it (its first assertion is again a control). A test that cannot fail is not a test. Put this in your suite and a future refactor that bypasses the masking client breaks the build.
Note what the tests do not need: no key, no network, no account. The recorder's session answers every request itself.
4.5 Integration tests#
The second layer uses a real model and real tools. The docs' advice, in the order you will need it:
Separate them with a marker and keep them out of the default run.
# pytest.ini
[pytest]
markers =
integration: tests that call real models or services (need keys, cost money)
addopts = -m "not integration"pytest then runs only unit tests; pytest -m integration runs the others. In the test module, mark the tests (@pytest.mark.integration).
Skip, do not fail, when keys are missing. An autouse fixture in conftest.py keeps a laptop without keys green:
# conftest.py
import os
import pytest
@pytest.fixture(autouse=True)
def require_key_for_integration(request):
if request.node.get_closest_marker("integration") and not os.environ.get("OPENAI_API_KEY"):
pytest.skip("OPENAI_API_KEY not set")These two files are illustrative: they are configuration shapes, and the key name is whichever provider your integration tests use. Keep the .env out of git (.gitignore) and inject secrets in CI from the provider's secret store (12.7 covers the supply side).
Keep them cheap and specific.
- Use a small model, cap
max_tokens, test one behaviour per test, and run them selectively, not on every commit. - Assert on structure again: that the model called
get_order_statuswith anorder_idstring, that there are four messages, not that the sentence contains a word. Models paraphrase. - Expect occasional flakiness and decide your policy (retry once and report, or run each test three times and require two passes: 08A.14, 4.4 on pass@k).
Record and replay. vcrpy with pytest-recording captures a real HTTP exchange once and replays it from a file, which gives integration-style coverage at unit-test speed:
import pytest
@pytest.mark.vcr() # cassette stored under tests/cassettes/
def test_order_lookup_with_recorded_model():
... # call the real agent: the first run records, later runs replayThis fragment is illustrative: a real test needs your agent and a one-time recording run (pytest --record-mode=once). The rules the docs attach to cassettes, which matter more than the decorator: filter the authorization and x-api-key headers and the api_key and key query parameters out of what is recorded (a cassette is a file that gets committed), delete stale cassettes when the prompt or the tools change (a replay of an old exchange passes while the real behaviour has moved), and treat a cassette as a record of one model version's behaviour, not as a spec. Cassettes also contain whatever the model saw, so scrub personal data before committing one.
4.6 A CI layout that fits#
| Job | Runs | Needs | When |
|---|---|---|---|
unit |
Everything not marked integration, with LANGSMITH_TEST_TRACKING=false |
Nothing | Every push |
integration |
pytest -m integration |
Provider keys | On merge to main, or nightly |
evals |
client.evaluate(...) against the prod-tagged dataset, comparing with the last experiment |
A LangSmith key and provider keys | Before release, and when prompts, tools or models change |
package audit |
Lockfile and licence checks | Nothing | Every push (08F.15 and Module 12 cover dependency hygiene) |
The general principles of eval gating in CI are 10A.8; what is specific here is that unit tests need no account at all, and the other two layers do.
4.7 What fakes cannot tell you#
A scripted model always makes the call you scripted. It cannot tell you whether the real model picks the right tool, writes good arguments, stops at the right moment, follows the prompt, or recovers when a tool returns an error. Those depend on the model, your tool descriptions and your prompt, and they are measured by evals (Part 3) and by a small set of integration tests, not by unit tests. The healthy balance: many unit tests for control flow, a handful of integration tests for the model boundary, and an eval set that grows from production failures.
Part 5: Studio and the local server#
Deep-dive
5.1 What Studio is#
LangSmith Studio (formerly LangGraph Studio) is, in the docs' words, "a specialized agent IDE that enables visualization, interaction, and debugging of agentic systems that implement the Agent Server API protocol." In practice: a web UI that connects to a running Agent Server (a local one while you develop) and lets you see your graph drawn, send it input, watch each node run, and change things while it is paused.
| Feature | What you do with it |
|---|---|
| Graph visualisation | See the nodes and edges (08F.10, 10.4 drew the same picture from code) |
| Run and interact | Submit input, stream the steps, answer an interrupt in the UI (08F.12) |
| Assistants and threads | Create and switch assistants (6.3) and threads (6.4) |
| Time travel | Replay or fork from an earlier checkpoint: buttons over the API of 08F.11, Part 3 |
| Edit state | Change state while paused, then continue |
| Prompts and experiments | Iterate on a prompt, run an experiment over a dataset (Part 3) |
| Long-term memory | Browse the store (08F.11, Part 7) |
| One-click deploy | Push to LangSmith Cloud (Part 7) |
Two modes: Graph mode shows everything (nodes, state, per-step detail), and Chat mode is a simple chat window and works only for graphs whose state includes or extends MessagesState (an agent from create_agent qualifies). A no-code agent builder exists on Cloud only. The OSS page calls Studio "a free visual interface": it needs a free LangSmith account and an API key, not a paid plan.
5.2 langgraph.json in full#
Everything the server and Studio know about your project is in one file, langgraph.json, at the project root. The smallest useful version:
{
"dependencies": ["."],
"graphs": {"support": "./src/agent.py:graph"},
"env": ".env",
"python_version": "3.12",
"image_distro": "wolfi"
}graphs maps a graph id (what clients call it) to path/to/file.py:variable. The variable must be a compiled graph: create_agent returns one (08F.8, 7.8), so graph = create_agent(...) at module level works as is. A function that builds the graph (a factory) also works and runs on every invocation, so use it only for per-run customisation.
The keys, from the CLI docs and the CLI itself (0.4.43):
| Key | Purpose | Notes |
|---|---|---|
dependencies (required) |
What to install | "." finds pyproject.toml, setup.py or requirements.txt in the app folder; paths like "./local_package" and package names also work |
graphs (required) |
Graph id to file:variable |
Every graph here gets a default assistant (6.3) |
env |
A .env path, or a mapping of variables |
Keep keys out of the image: see Part 8 |
python_version |
3.11, 3.12 or 3.13 |
Default 3.11; the CLI rejects anything below 3.11 (run below) |
node_version |
For JavaScript graphs | |
image_distro |
The base image's Linux flavour | The CLI accepted debian, wolfi and bookworm; the docs also mention bullseye. The docs call Wolfi "recommended ... smaller and more secure" |
pip_installer |
auto, pip or uv |
The CLI rejects other values and suggests source instead |
source |
{"kind": "uv", ...} installs from uv.lock |
See the supply-chain warning in 5.4 |
pip_config_file, dockerfile_lines, base_image, api_version |
Image customisation and pinning the server release | api_version pins the Agent Server version; new deployments otherwise use the newest stable (Part 6) |
auth |
Custom authentication handlers | 6.11 |
store |
Store configuration: semantic-search index and TTL | 08F.11, Part 7 |
checkpointer |
The default is Postgres; mongo and custom exist |
Server-side only |
http |
A custom app to mount and CORS settings | |
webhooks |
Header templates and URL restrictions for run webhooks | 6.9 |
A richer file that uses the security-relevant ones (a custom auth handler, a store TTL, CORS for one origin, webhook URL restrictions) validated with the CLI in this lesson:
{
"dependencies": ["."],
"graphs": {"support": "./src/agent.py:graph"},
"env": ".env",
"python_version": "3.12",
"image_distro": "wolfi",
"pip_installer": "uv",
"auth": {"path": "./src/auth.py:auth"},
"store": {"ttl": {"default_ttl": 1440, "refresh_on_read": true}},
"http": {"cors": {"allow_origins": ["https://app.example.com"]}},
"webhooks": {"url": {"require_https": true, "allowed_domains": ["hooks.example.com"], "disable_loopback": true}},
"api_version": "0.18"
}That file is real configuration, accepted by langgraph validate in 0.4.43; the values (the domain, the TTL) are examples. And src/agent.py for the graph it points at, which needs a provider and is therefore illustrative:
from langchain.agents import create_agent
from langchain.tools import tool
@tool
def get_order_status(order_id: str) -> str:
"""Look up an order."""
return f"Order {order_id}: shipped"
# Compiled graph, no checkpointer: the server provides one. Pick a current model id from your provider.
graph = create_agent("openai:your-current-model-id", tools=[get_order_status])This sample is illustrative: it calls a provider when run, and the get_order_status tool returns canned data. Check the file without Docker, a server or a network with langgraph validate. The author ran it against the two configurations above and four broken ones (paths shortened):
langgraph validate # the nearest langgraph.json
langgraph validate -c langgraph.rich.json$ langgraph validate
Configuration file ./langgraph.json is valid. (1 graph found)
$ langgraph validate -c langgraph.rich.json
Configuration file ./langgraph.rich.json is valid. (1 graph found)
$ langgraph validate -c bad1.json (image_distro "alpine")
Error: Invalid image_distro: 'alpine'. Must be one of: 'debian', 'wolfi', 'bookworm'.
"image_distro": "wolfi" (recommended)
$ langgraph validate -c bad2.json (python_version "3.9")
Error: Python version 3.9 is not supported. Minimum required version is 3.11.
"python_version": "3.11"
$ langgraph validate -c bad3.json (unknown key)
Configuration file bad3.json is valid. (1 graph found)
warning: Unknown key 'foo' is not a recognized config field.
$ langgraph validate -c bad4.json (graph variable that does not exist)
Configuration file bad4.json is valid. (1 graph found)
$ langgraph validate -c bad5.json (graph file that does not exist: "./src/nofile.py:graph")
Configuration file bad5.json is valid. (1 graph found)validate is a static check: it caught an unsupported image_distro, a Python below the 3.11 floor and an unknown key (as a warning), and it did not catch a graph variable that does not exist (bad4.json is "valid") or a graph file that does not exist (bad5.json, re-run on 18 November with langgraph-cli 0.4.43). It never imports your code and never checks that the file exists. A typo in file.py:graph is found when the server starts, so a CI step that really imports the module (a unit test that does from src.agent import graph) is the real check.
5.3 Running the server locally: langgraph dev#
The steps from the OSS Studio page (illustrative here: starting a server is outside this lesson's rules, and it needs a free LangSmith key):
uv add "langgraph-cli[inmem]" # Python 3.11 or newer; the `dev` command needs it
export LANGSMITH_API_KEY=... # a free account is enough
langgraph devThat command is illustrative: it starts a server, and it needs the key. What the docs say happens:
- The API is served at
http://127.0.0.1:2024, with interactive API docs at/docs. - Studio opens at
https://smith.langchain.com/studio/?baseUrl=http://127.0.0.1:2024. The page is hosted by LangSmith, but it runs in your browser and connects directly to your local server. - Hot reload is on by default (
--no-reloadturns it off). The state is kept in memory and pickled to a local folder (.langgraph_api), which is how it can outlast a restart oflanggraph devin the same folder (check the docs for the exact guarantees). Add the folder to.gitignore. - Safari blocks
localhostconnections from an HTTPS page: use--tunnel, or another browser. - Debugging:
langgraph dev --debug-port 5678listens for a debugger (DAP), and--wait-for-clientwaits for one.
Flags in langgraph dev --help (0.4.43) worth knowing, besides --port, --host, --config and --no-browser: --n-jobs-per-worker (concurrent runs per worker; the default for dev is 1, against 10 on a deployed worker), --allow-blocking (stop raising errors for synchronous blocking calls inside async code, which the dev server flags), --server-log-level, --studio-url, --tunnel, and TLS options (--ssl-keyfile, --ssl-certfile).
5.4 dev, up, build, dockerfile and deploy#
The CLI has more commands than dev, and they differ in what they need:
| Command | What it does | Needs | Port |
|---|---|---|---|
langgraph validate |
Static check of langgraph.json |
Nothing | n/a |
langgraph dev |
The server in your Python process, with hot reload and in-memory (pickled) state | A free LangSmith key; no Docker | 2024 |
langgraph up |
The server in Docker with PostgreSQL and Redis containers: closer to production | Docker running; a LangSmith key for local dev; "license for production" (docs) | 8123 |
langgraph build |
Builds the Docker image | Docker | n/a |
langgraph dockerfile PATH |
Writes the Dockerfile (and optionally Docker Compose files, with --add-docker-compose) |
Nothing | n/a |
langgraph deploy |
Beta. Builds the image and deploys it to LangSmith Agent Server; has subcommands list, logs, metrics, revisions and delete |
A LangSmith key; a Plus plan or above for Cloud (Part 7) | n/a |
langgraph new |
Creates a project from a template | Nothing | n/a |
langgraph deploy is listed as [Beta] in the CLI itself. Its options include --name, --agent-id and --agent-environment (the agent-based workspaces of 2.3: development, staging or production), --agent-server-type (serverless by default, or dedicated) and --no-wait. Read langgraph deploy --help before using it: a beta deployment command is exactly where options move between releases. The advisory list in Part 8 includes one in this exact area (the CLI printing a registry push token under --verbose), so do not run it with --verbose in a CI log.
langgraph dockerfile shows what an image is built from without needing Docker. The author generated one for the small config above and these are its load-bearing lines (the folder name here is the project's, support-agent):
FROM langchain/langgraph-api:3.12-wolfi
ADD . /deps/support-agent
RUN for dep in /deps/*; do ... -c /api/constraints.txt -e .); fi; done
ENV LANGSERVE_GRAPHS='{"support": "/deps/support-agent/src/agent.py:graph"}'
RUN PYTHONDONTWRITEBYTECODE=1 uv pip install --system --no-cache-dir --no-deps -e /apiThree things to notice. The base image is the server itself (langchain/langgraph-api, tagged with the Python version and distro), so your code is layered over a published image whose release stream you can pin with api_version. Your project is installed with uv pip install ... -c /api/constraints.txt -e .: the -c is a constraints file shipped with the server, which keeps your dependencies from overwriting the server's own packages. And the install is -e ., resolved from your pyproject.toml.
5.5 What to do in Studio, in order#
A routine that uses Studio for what only it does well:
- Open your graph in Graph mode and confirm the drawing matches your intent (a missing edge shows immediately).
- Run one real input and watch the steps. Click a step to see its state in and out.
- Fork from the step that went wrong: edit the state at that checkpoint, rerun from there, and compare. This is the fastest way to test "what if the retrieval had returned this?" without rerunning the earlier steps.
- Answer an interrupt in the UI to test your approval flow.
- Save the failing input as a dataset example and write the evaluator that catches it (Part 3).
Studio is for exploration. Anything you find there that should never regress becomes a unit test (Part 4) or a dataset example.
5.6 When it does not connect#
| Symptom | Likely cause | Fix |
|---|---|---|
| Studio loads but cannot reach the server (Safari) | Safari blocks localhost from an HTTPS page |
langgraph dev --tunnel, or use another browser |
langgraph dev complains about a missing key |
The docs say local use needs a LangSmith API key | Set LANGSMITH_API_KEY (a free account is enough) |
| Python version error | python_version below 3.11, or the CLI is run with an older Python |
langgraph validate; use 3.11 or newer |
| Graph not found at startup | file.py:variable wrong, or the module raises on import |
Import it in a Python shell; validate will not catch this |
| Blocking-call errors | Synchronous I/O inside an async node |
Make the call async, or use --allow-blocking while you fix it |
| Behaviour differs from this lesson | The 0.19 release candidate's Go core | Check the Agent Server changelog (5.3) |
5.7 What leaves your machine#
The Studio UI is served from smith.langchain.com, but it runs in your browser and connects directly to your local server. The data-storage-and-privacy page says that with LANGSMITH_TRACING=false, "no data leaves your local server", apart from CLI telemetry. Three kinds of traffic to know about:
| Traffic | What | How to stop it |
|---|---|---|
| Traces | The runs of your graph, to LangSmith | LANGSMITH_TRACING=false |
| CLI analytics | One event per command: OS, Python version, CLI version, command name and the flags as booleans | LANGGRAPH_CLI_NO_ANALYTICS=1 |
| Studio usage analytics | For logged-in users: page visits, clicks, browser, screen size. No application data | Not documented as switchable here; check the page |
Also remember that local use needs a LangSmith key. "Local" means "your code and your data stay on your machine if tracing is off", not "no network at all": the docs' own list above is the list of what leaves.
Part 6: Agent Server: assistants, threads and runs#
Deep-dive
This part is a survey of the server's concepts with the details that matter in practice, as the module plan intends: 08F.4, 6.2 introduced it, and the official docs are more complete than any lesson (pages are listed in Further resources). Nothing here starts a server; the snippets that call one are labelled illustrative, and the keyless pieces that can be run (a cron conversion, a webhook handler, the API surface) were.
6.1 What it is#
LangSmith Agent Server (the docs' definition) "is a workflow orchestration runtime for agent workloads. It offers an API for creating and managing agent-based applications ... built on the concept of assistants ... includes built-in persistence and a task queue." In plainer terms: you give it compiled graphs, and it gives you back an HTTP API with durable conversations, background jobs and streaming. It is framework-agnostic: LangGraph and LangChain graphs, and agents from other frameworks (the docs name the Claude Agent SDK, Strands, CrewAI, AutoGen and Google ADK) through the Functional API (08F.14) or a wrapper package.
What you stop writing when you adopt it: the HTTP layer, the job queue, the persistence of checkpoints, threads and the store, cancellation, scheduling and streaming plumbing. What you accept: the server's model of the world (assistants, threads and runs), its release cadence, and a licence and hosting decision (Part 7). Its alternative is your own FastAPI service around the library (08F.11 for the saver you would then configure yourself).
6.2 Architecture#
You deploy graphs, a database and a task queue. This is the whole picture:
flowchart LR
client["Your app<br/>SDK, REST, Studio"] --> api["API servers"]
api --> pg[("PostgreSQL<br/>assistants, threads, runs, crons,<br/>checkpoints, store")]
api --> redis[("Redis<br/>signalling, cancellation,<br/>streaming pub/sub")]
redis --> workers["Queue workers<br/>run your graphs"]
workers --> pg
workers --> model["Model providers<br/>and your tools"]
workers -.->|"traces"| ls["LangSmith"]The facts the architecture page gives:
- Graph loading. Export an already-compiled graph (recommended: loaded once at start-up) or a factory function (run per invocation; use it only for per-run customisation). "The server automatically injects the checkpointer and memory store ... Do not configure these in your graph code" (5.2).
- Persistence. PostgreSQL by default for the core resources (assistants, threads, runs, crons), for checkpoints and for the long-term store. The checkpoint durability mode is
asyncby default (each step is written, in the background) orexit(only the final state is stored); MongoDB or custom checkpointers are possible throughlanggraph.json. Redis is for signalling, cancellation and streaming pub/sub only: the docs state that "no user or run data persists in Redis". - Runtime modes. A single host (the default self-hosted shape: API and workers together), a split API and queue (
queue.enabled: true: API servers and queue workers are separate container pools, and at least one worker must always be listening), and a distributed runtime. - Concurrency. "At most 1 run can be executed for a given thread at one time." Each worker runs up to
N_JOBS_PER_WORKERruns (default 10;langgraph devdefaults to 1). - Timeouts. A background run is bounded by
BG_JOB_TIMEOUT_SECS(default 86,400 seconds, a day).
Release streams (the Agent Server changelog): latest every morning, rc every three weeks, stable every three weeks from the rc. New deployments use the newest stable. Pin a version with api_version in langgraph.json (5.2) when you need repeatability, and read the changelog before moving it: the server is a moving runtime.
6.3 Assistants: versioned configurations#
An assistant is "an instance of a graph with a specific configuration": prompts, model and tools managed separately from the graph's logic, so one graph can back several variants (a formal support assistant and a casual one, a cheap one and a strong one).
- Default assistant. Deploying creates one default assistant per graph in
langgraph.json. A run can address a graph id (the default assistant) or an assistant UUID (a specific configuration). - Versioning. Every update creates a new version automatically. You can set any version as the active (latest) one, which is also how you roll back. All versions stay available.
- The update trap. The docs warn that updating "creates new versions from scratch and does not merge", so you "must provide the entire configuration payload". A partial update silently drops the fields you left out. Treat an assistant update as
PUT, notPATCH, even though the endpoint is aPATCH. - Not in the library. "Assistants are a LangSmith Agent Server concept. They are not available in the open source LangGraph library." (1.2)
The SDK groups these under client.assistants (create, update, get, search, delete, get_versions, set_latest, get_graph, get_schemas, get_subgraphs, count). get_schemas returns the graph's input, output and state schemas (08F.10 described the schemas): a generated client can use it for validation.
6.4 Threads#
A thread is a persistent conversation container with a unique id. The state is updated after each run, and the history of checkpoints is kept (08F.11, Part 2 taught the same objects from the library side). Thread statuses in langgraph-sdk 0.4.14 are idle, busy, interrupted and error. client.threads offers create, get, update, delete, search, copy, prune, get_state, update_state, get_history, stream and join_stream. copy and get_history are the server forms of forking and time travel.
Two production notes from the OpenAPI spec and the SDK: threads.create accepts a ttl, so you can let idle threads expire instead of keeping every conversation forever (which is also a data-retention decision), and threads.prune exists for clean-up. Deleting a user's data means deleting their threads and any store items you keyed by user (08F.11, Part 7).
6.5 Runs#
A run is one invocation of an assistant. It is either stateless (no thread: the SDK is passed None for the thread id, and nothing is persisted) or stateful (on a thread). Ways to start one:
| Style | SDK call | Behaviour |
|---|---|---|
| Wait | client.runs.wait(thread_id, assistant_id, input=...) |
Blocks until the run finishes and returns the final state |
| Stream | client.runs.stream(...) |
Yields events as the run progresses; stream_mode takes the modes of 08F.14 |
| Background | client.runs.create(...) |
Returns at once with a run id; poll with runs.get, or runs.join to wait, or attach a webhook (6.9) |
| Batch | client.runs.create_batch(...) |
Start several |
| Cancel | client.runs.cancel(thread_id, run_id, action=...) |
action is interrupt (stop, keep progress) or rollback (stop, discard) |
Options you will use on a run, from the SDK signature (0.4.14): input or command (to resume an interrupt: 08F.12), config and context, metadata, interrupt_before and interrupt_after, webhook, multitask_strategy (6.7), if_not_exists (create or reject: create the thread when it is missing), on_completion (delete or keep: for stateless runs, what happens to the thread afterwards), on_disconnect (cancel or continue: what happens to a streamed run when the client goes away; in langgraph-sdk 0.4.14 it is a parameter of runs.stream and runs.wait only, not of the background runs.create), after_seconds (delay the start), durability (sync, async or exit), and langsmith_tracing. Run statuses: pending, running, error, success, timeout, interrupted.
An illustrative client session putting these together (it needs a running server, and langgraph-sdk is installed with langgraph):
import asyncio
from langgraph_sdk import get_client
async def main() -> None:
client = get_client(url="http://127.0.0.1:2024") # a deployed server also needs api_key=...
thread = await client.threads.create()
thread_id = thread["thread_id"]
async for part in client.runs.stream(
thread_id,
"support", # a graph id (default assistant) or an assistant UUID
input={"messages": [{"role": "user", "content": "Where is order A17?"}]},
stream_mode="updates",
):
print(part.event, part.data)
state = await client.threads.get_state(thread_id)
print(state["values"]["messages"][-1]) # the final state of the thread
if state["next"]: # a non-empty `next` means the run paused (an interrupt)
await client.runs.wait(thread_id, "support", command={"resume": "yes"})
asyncio.run(main())This sample is illustrative: it needs the server of Part 5 running and a graph named support, and the shape of the events depends on stream_mode. The JavaScript client is Client from @langchain/langgraph-sdk with apiUrl. get_sync_client is the synchronous twin of get_client.
Calling a deployment as if it were a local graph. RemoteGraph (from langgraph.pregel.remote import RemoteGraph) wraps a deployed assistant in the interface of a compiled graph: RemoteGraph("support", url=..., api_key=...). It is what lets one graph call another deployed graph as a subgraph or a tool (08F.13). Its signature in langgraph 1.2.22 also has headers, client and sync_client arguments and a distributed_tracing flag (see the docs for what it does to traces).
6.6 Streaming, human-in-the-loop and time travel over HTTP#
All three are the library features of 08F.12, 08F.11 and 08F.14 exposed as endpoints. Streaming comes in values, updates, messages and the other modes (the SDK's list in 0.4.14 also includes events, tasks, checkpoints, debug, custom, tools and lifecycle; check the docs for the modes your server version supports). A paused run is a thread with a non-empty next and an interrupt payload; you resume it with a new run that carries command. Time travel is get_history plus a run from a chosen checkpoint_id. Because the server persists everything, a browser can close and reopen the conversation days later: that is the property you are buying.
6.7 Double texting#
A user sends a second message while the first is still being processed: double texting. The server's multitask_strategy decides what happens, and it is a server feature, not a library one ("not available in the LangGraph open source framework").
| Strategy | What happens to the new input | What happens to the running run | The catch |
|---|---|---|---|
enqueue (the default) |
Waits in a queue and runs after | Finishes first | The user waits for two answers in turn |
reject |
Refused | Continues undisturbed | The client must handle the refusal and tell the user |
interrupt |
Added to the thread, and the graph continues from that state | Stops, but keeps the progress made so far | "A tool call may have been initiated but not yet completed at the time of interruption": a dangling tool call that your graph must repair or remove |
rollback |
Runs fresh from the initial state | Stops and reverts its progress, including the original input | The first message is lost to the model; tell the user |
You choose per run (multitask_strategy="interrupt" on runs.create, stream or wait) and a thread still has at most one run executing at a time. Pick by product: a support chat usually wants enqueue or interrupt (with a graph that tolerates the dangling tool call, the same invariant as 08F.13, 4.3); a payment flow wants reject. Test your choice: send two quick messages in Studio and read the trace.
6.8 Cron jobs and the UTC rule#
A cron job runs an assistant on a schedule. The docs: "All cron schedules are interpreted in UTC." Each firing creates a new thread (or uses the thread you named) and sends the same input every time. The SDK:
cron = await client.crons.create_for_thread(
thread_id, "support",
schedule="27 15 * * *", # 15:27 UTC daily
input={"messages": [{"role": "user", "content": "Summarise today's open tickets"}]},
)
# stateless form: await client.crons.create("support", schedule=..., input=...)
# clean up: await client.crons.delete(cron["cron_id"])
# crons.create also takes end_time (stop firing after a date) and enabled (create it paused): checked in the 0.4.14 signatureThis is illustrative (it needs a server). Four things to know:
- Convert to UTC yourself, and remember daylight saving: a fixed UTC expression drifts against local time twice a year. This keyless sample shows the conversion and the drift for two cities:
# s40_cron_utc.py: Agent Server docs say cron schedules are read as UTC: convert your local time before you write one
from datetime import datetime
from zoneinfo import ZoneInfo
def utc_cron(hour: int, minute: int, tz: str, on: datetime) -> str:
"""Return a daily cron expression, in UTC, that fires at hour:minute local time on the given date."""
local = datetime(on.year, on.month, on.day, hour, minute, tzinfo=ZoneInfo(tz))
utc = local.astimezone(ZoneInfo("UTC"))
return f"{utc.minute} {utc.hour} * * *"
# Every morning at 09:00 in Kolkata: no daylight saving, so the UTC expression never changes.
print("Kolkata :", utc_cron(9, 0, "Asia/Kolkata", datetime(2026, 1, 15)), "|", utc_cron(9, 0, "Asia/Kolkata", datetime(2026, 7, 15)))
# Every morning at 09:00 in New York: a fixed UTC expression drifts by an hour twice a year.
print("New York :", utc_cron(9, 0, "America/New_York", datetime(2026, 1, 15)), "|", utc_cron(9, 0, "America/New_York", datetime(2026, 7, 15)))Kolkata : 30 3 * * * | 30 3 * * *
New York : 0 14 * * * | 0 13 * * *Kolkata has no daylight saving, so one expression works all year. New York needs 0 14 * * * in winter and 0 13 * * * in summer, so a "9 a.m." job fixed in UTC is an hour off for half the year.
- An SDK/docs difference.
langgraph-sdk0.4.14'scrons.createandcreate_for_threadhave atimezoneargument (an IANA name such asAmerica/New_York, or atzinfo) documented as "Schedules are interpreted in UTC unless a timezone is specified". The docs page on cron jobs, fetched on 14 November 2026, says schedules are always UTC and shows no timezone argument. The argument may need a recentlanggraph-api; test it on your server before relying on it, and use the UTC conversion above if you cannot. - Crons cost money. Each firing runs your graph, which calls a model. The docs say: "it is very important to delete Cron jobs that are no longer useful. Otherwise you could rack up unwanted API charges to the LLM!" Enabled crons also wake scale-to-zero (Serverless) deployments, up to ten minutes early, which the billing page lists as a cost (Part 7).
- Same input every time. A job that needs "today's date" must read it inside the graph (a node that calls the clock), not from the input.
6.9 Webhooks and the "success" that is not done#
A run webhook is a callback the server makes when a run completes: pass webhook="https://..." to the create, stream and wait endpoints and to cron endpoints. (These are not the LangSmith rule webhooks of 3.8, which belong to automation rules.) The payload fields, from the docs: run_id, thread_id, assistant_id, status (success, error, timeout, interrupted, rollback), created_at, updated_at, run_started_at, run_ended_at, webhook_sent_at, metadata, kwargs, values (stateful runs only), multitask_strategy and error.
Here is a receiver's logic with no web framework in it, so that it can be tested. It checks a secret token (the docs recommend adding a secret token as a query parameter and validating it) in constant time, then turns a payload into an action, looking at the thread when the status is success:
# s41_webhook_handler.py: the logic of a run-completion webhook receiver, kept free of any web framework so it can be tested
import hmac
from typing import Callable
EXPECTED_TOKEN = "replace-with-a-long-random-secret-from-your-secret-store"
def token_ok(received: str | None) -> bool:
# Constant-time comparison. The docs suggest putting a secret token in the URL's query string and validating it.
return received is not None and hmac.compare_digest(received, EXPECTED_TOKEN)
def decide(payload: dict, get_thread_next: Callable[[str], list[str]]) -> str:
"""Turn a webhook payload into an action. `get_thread_next(thread_id)` returns the thread's pending nodes."""
status = payload["status"]
if status == "success":
# A run that paused at interrupt() is reported as "success": look at the thread before you celebrate.
if get_thread_next(payload["thread_id"]):
return "waiting_for_human"
return "done"
if status in ("error", "timeout"):
return "alert"
if status == "rollback":
return "ignore"
return f"unhandled:{status}"
paused = {"run_id": "r1", "thread_id": "t1", "assistant_id": "a1", "status": "success"}
finished = {"run_id": "r2", "thread_id": "t2", "assistant_id": "a1", "status": "success"}
failed = {"run_id": "r3", "thread_id": "t3", "assistant_id": "a1", "status": "error", "error": "ToolError"}
pending = {"t1": ["approve"], "t2": [], "t3": []}
for payload in (paused, finished, failed):
print(payload["run_id"], payload["status"], "->", decide(payload, lambda thread_id: pending[thread_id]))
print("token ok:", token_ok(EXPECTED_TOKEN), "| wrong token:", token_ok("guess"), "| missing:", token_ok(None))r1 success -> waiting_for_human
r2 success -> done
r3 error -> alert
token ok: True | wrong token: False | missing: FalseIn a real receiver, get_thread_next is client.threads.get_state(thread_id) and a check of next. Beyond this handler, make a real receiver idempotent (the same webhook can arrive twice), return quickly and do the work asynchronously, and treat the payload's values and error as untrusted data.
Server-side controls for webhooks, all in langgraph.json (5.2): webhooks.headers (custom headers, with ${{ env.LG_WEBHOOK_* }} templates, needing langgraph-api>=0.5.36) and webhooks.url restrictions: allowed_domains, require_https, allowed_ports, disable_loopback, max_url_length. disable_loopback is on by default from langgraph-api 0.10.0, which blocks localhost receivers: a webhook test against langgraph dev and a receiver on your machine fails until you relax it deliberately for development.
6.10 The API surface#
The server's OpenAPI document (docs.langchain.com/langsmith/agent-server-openapi.json, titled "LangSmith Agent Server", version 0.1.0) listed 50 paths and 64 operations when fetched on 14 November 2026. The groups, so that you know where to look:
| Tag | Representative paths |
|---|---|
| Assistants | /assistants, /assistants/search, /assistants/{assistant_id}/graph, /schemas, /subgraphs, /versions, /latest |
| Threads | /threads, /threads/search, /threads/{thread_id}/state, /history, /copy, /storage, /commands, /threads/prune |
| Thread runs | /threads/{thread_id}/runs, /runs/stream, /runs/wait, /runs/{run_id}/cancel, /join, /stream |
| Stateless runs | /runs, /runs/stream, /runs/wait, /runs/batch, /runs/cancel |
| Crons | /runs/crons, /threads/{thread_id}/runs/crons, /runs/crons/search |
| Store | /store/items, /store/items/search, /store/namespaces |
| A2A and MCP | /a2a/{assistant_id}, /mcp/ |
| System | /info, /ok, /metrics, /docs |
langgraph dev serves interactive documentation at /docs: open it and click through a thread, a run and a cron once, before reading any client library. The /metrics endpoint is the server's own metrics, separate from LangSmith traces (check the docs for what it exposes and in which format).
Two more doors into the same graphs. The server can expose each assistant as an MCP server at /mcp (Streamable HTTP; the docs list protocol revisions 2024-11-05 to 2026-07-28; it needs langgraph-api>=0.18.0), so an MCP client such as a coding agent can call your agent as a tool (08E.1 owns MCP). And it exposes an A2A (agent-to-agent) endpoint at /a2a/{assistant_id} (the A2A v1.0 JSON-RPC binding, and it also accepts the v0.3 method names). Both inherit the server's authentication (6.11): publishing an agent over MCP or A2A without checking who is calling is a way to expose its tools to the internet.
6.11 Authentication#
By default, LangSmith deployments require a LangSmith API key in the x-api-key header, and self-hosted servers have no default authentication (the docs' words). Either way you add your own with two decorators from langgraph_sdk (Auth), available on all plans: @auth.authenticate decides who the caller is, and @auth.on handlers decide what that caller may see, by adding metadata to resources on the way in and returning a filter on the way out. The shape (illustrative: the identity check is a placeholder for your provider):
# src/auth.py: referenced from langgraph.json as {"auth": {"path": "./src/auth.py:auth"}}
from langgraph_sdk import Auth
auth = Auth()
@auth.authenticate
async def authenticate(authorization: str | None) -> Auth.types.MinimalUserDict:
# Validate the bearer token against your identity provider here; raise to reject.
if not authorization:
raise Auth.exceptions.HTTPException(status_code=401, detail="Missing token")
return {"identity": "user-123", "permissions": []}
@auth.on
async def owner_only(ctx: Auth.types.AuthContext, value: dict):
metadata = value.setdefault("metadata", {})
metadata["owner"] = ctx.user.identity # tag every new resource with its owner
return {"owner": ctx.user.identity} # and filter every read by itThat file is illustrative: it needs a running server to exercise and the identity check is a placeholder. The docs also cover auth.allow_langsmith_api_keys (Agent Server v0.14.0rc2 and later) to accept LangSmith keys alongside your own, per-user store isolation, and encryption at rest: built-in AES encryption when LANGGRAPH_AES_KEY is set (with lazy key rotation), or custom handlers for per-tenant keys. A security advisory in Part 8 concerns exactly this area (an SDK custom-auth actions= parameter silently ignored in an old release), so after any upgrade test that user B cannot read user A's thread: a two-user test against a local server is five lines and the most valuable test a multi-tenant deployment has. 08F.11 noted that the store has no access control of its own; here is where you add it.
6.12 The Agent Protocol#
"Agent Protocol" now means two related things in the official material, and the older meaning is easy to confuse with a separate project:
- In the repository
github.com/langchain-ai/agent-protocol(MIT; created by LangChain; last pushed 5 November 2026 when checked): "an attempt to codify framework-agnostic APIs for serving LLM agents in production", built on three concepts: Runs, Threads and Store. It contains anopenapi.json, a Python client, server stubs and astreaming/folder with a CDDL schema and generated bindings. Its README says LangGraph Platform implements a superset of the protocol. So the Agent Server API of 6.10 is a superset of this open specification, and a client written against the protocol's three concepts is a client of the same ideas. - In the streaming docs: the wire-level event and command formats of agent streaming (event streaming "v3", in beta, started with
stream_events(version="v3")), "defined in the Agent Protocol repository and consumable aslangchain-protocolon PyPI (0.0.21) and@langchain/protocolon npm". Studio is described as a tool for systems that implement the Agent Server API protocol.
The fetched README does not mention agentprotocol.ai or the AI Engineer Foundation, so this lesson does not claim any equivalence with that older, separately named project. When you read "Agent Protocol" in an article, check which one it means. For your design the practical point is portability: a deployment that speaks Runs, Threads and Store through a documented OpenAPI contract is much easier to put behind your own client (or replace) than one that speaks a private protocol. 08E.1 and 08F.1, Part 5 cover the neighbouring interoperability standards.
Part 7: Hosting, licences and cost#
Reference
Everything in this part is a fact as of 14 November 2026 from the official pages named in the text, and prices and plan rules change. Treat each number as a snapshot, re-check langchain.com/pricing and the usage-and-billing page before you budget, and note that this lesson is not legal advice about licences.
7.1 Where the Agent Server can run#
| Option | Who runs the control plane | Who runs servers and databases | What the docs say it needs |
|---|---|---|---|
| Cloud | LangChain | LangChain, "fully managed ... on AWS, Azure, and GCP"; deploy from GitHub in the UI or with langgraph deploy |
"Requires a Plus plan or above"; a deploy takes "about 15 minutes" |
| Hybrid | LangChain | You: Agent Servers and the data plane in your infrastructure; traces go to Cloud or self-hosted LangSmith | The deployment page names no plan. The pricing page lists "Self-hosted and hybrid deployment options" under Enterprise |
| Self-hosted with control plane | You | You, in your own Kubernetes alongside self-hosted LangSmith | "Requires the Enterprise plan with Agent Server hosting enabled" |
| Standalone server | None | You: Docker, Compose or Kubernetes; "Bring your own PostgreSQL, Redis, and LangSmith license; no control plane" | A licence key (the plan that provides it is not stated on the pages read) |
Local (langgraph dev) |
n/a | Your laptop | A free LangSmith account and key |
For the LangSmith platform itself (tracing and evaluation, not the Agent Server) the setup page lists Cloud, BYOC (LangChain runs the control plane and you run data planes in your VPC) and Self-hosted (you run everything, and upgrades are manual). "Self-hosted and BYOC are available on the Enterprise plan"; self-hosted LangSmith is "an add-on to the Enterprise plan". Its stable channel gets weekly patches and a new major about every six weeks, and it needs ClickHouse (or the optional SmithDB from 0.17), PostgreSQL, Redis and blob storage.
The standalone server deserves a closer look because it is the choice engineers imagine first ("just run the image"):
- Required environment:
REDIS_URI,DATABASE_URI,LANGSMITH_API_KEYandLANGGRAPH_CLOUD_LICENSE_KEY(the licence key is checked once, at start-up), and optionallyLANGSMITH_ENDPOINT. - Egress: it needs to reach
https://beacon.langchain.comfor licence verification and usage reporting unless it is air-gapped. A locked-down network needs an exception, or the air-gapped arrangement your contract allows. - Production means Kubernetes. The docs: "For production deployments, use Kubernetes with the maintained LangSmith Helm chart" (
github.com/langchain-ai/helm, Apache-2.0). Docker and Compose are shown "for local development and testing", and non-Kubernetes deployments have "known gaps that you must implement and maintain yourself". Read that as a warning against putting the image behind a single VM and calling it production. - You operate the databases. Backups, failover, upgrades and the Redis that carries run signalling are yours (check the docs for what happens to in-flight runs when Redis is unavailable).
7.2 Licences, stated exactly#
| Package or thing | Licence | Source |
|---|---|---|
langchain, langchain-core, langgraph, langgraph-sdk, langgraph-cli, langgraph-checkpoint*, langsmith, deepagents |
MIT | PyPI metadata and the GitHub API |
openevals, agentevals, langchain-protocol |
MIT | PyPI |
langgraph-api and langgraph-runtime-inmem (the server that langgraph dev and the images run) |
Elastic-2.0 | PyPI license field and the package's LICENSE file (the license_expression field is empty) |
| The Helm chart | Apache-2.0 | GitHub |
| The LangSmith service | Not open source: a commercial service | |
The agent-protocol specification repository |
MIT | GitHub |
What Elastic-2.0 says. The Elastic License 2.0 is a short public text (elastic.co/licensing/elastic-license, read on 18 November 2026). It grants a broad right to use, copy, distribute and make derivative works, "subject to the limitations and conditions below", and its three limitations are: (1) you may not provide the software to third parties "as a hosted or managed service, where the service provides users with access to any substantial set of the features or functionality of the software"; (2) you may not "move, change, disable, or circumvent the license key functionality in the software", nor remove functionality that the licence key protects; and (3) you may not alter, remove or obscure licensing, copyright or other notices. Using the server inside your own product or company is not on that list; offering the server itself as a managed service to others, or getting round its licence key, is. This is a reading of a public text, not legal advice: take advice if your plan is unusual.
What the LangChain docs add, separately. The docs themselves say that production use of langgraph up and a standalone server need a licence key (7.1: LANGGRAPH_CLOUD_LICENSE_KEY, checked against beacon.langchain.com). That is a product requirement of the packaged server, not a term of the Elastic licence; the two interact only through limitation 2, which stops you removing the check. No public source repository for langgraph-api was found (github.com/langchain-ai/langgraph-api returned 404 when checked), and PyPI's JSON for langgraph-api 0.18.3 shows license: "Elastic-2.0". The rest of the stack you may use under MIT.
7.3 What it costs (14 November 2026)#
Plans (the pricing page):
| Plan | Price | Base traces included per month | Seats | Agent Server |
|---|---|---|---|---|
| Developer | $0 per seat per month | up to 5,000, then pay as you go | 1 | Not available ("N/A") |
| Plus | $39 per seat per month | up to 10,000, then pay as you go | Unlimited seats at $39 each | "1 Small Agent Server included on serverless hosting at no charge"; further servers billed on resource usage |
| Enterprise | Custom | Custom | Custom | Custom; self-hosted, hybrid, SSO, RBAC and an SLA are on this plan |
Startups can apply for "up to $10,000 in credits". The page states no price per thousand traces beyond the included amount ("pay as you go thereafter"), and no amount for upgrading a base trace to extended retention ("an additional fee"). Do not estimate trace overage from memory or from another article: look it up on the page.
Agent Server metering uses the LSU. On the pricing page, 1 LSU = $1.00, and the rates are:
| Resource | Rate |
|---|---|
| Runtime compute | 0.0675 LSU per vCPU-hour |
| Runtime memory | 0.0090 LSU per GiB-hour |
| Database compute | 0.177 LSU per vCPU-hour |
| Database memory | 0.025 LSU per GiB-hour |
The usage-and-billing docs give hourly tables for LangSmith Cloud on GCP. Serverless sizes: Small (0.8 vCPU, 2 GiB) 0.072 LSU per hour, Medium (4 vCPU, 4 GiB) 0.306, Large (8 vCPU, 8 GiB) 0.612; a scaled-down Serverless deployment costs 0 LSU. Dedicated sizes: Small 0.5335 LSU per hour, Medium 1.067, Large 2.134. "Managed Redis is not billed." Serverless is "not yet available for deployments on AWS or Azure, or for self-hosted and hybrid deployments", and Serverless's default "Scale down after" is 1 week, which the docs advise shortening to 1 hour.
A sanity check you can do with the published numbers, which also confirms that the tables and the rates agree: the Serverless Small row is 0.8 vCPU at 0.0675 plus 2 GiB at 0.0090, that is 0.054 + 0.018 = 0.072 LSU per hour. Left running all day for a 30-day month (720 hours) it is 0.072 x 720 = 51.84 LSU, about $51.84 at $1.00 per LSU, if it never scales down; the free Small server on Plus covers one. A Dedicated Small at 0.5335 LSU per hour is about 384 LSU (roughly $384) over the same 720 hours. This is arithmetic on the published rates, not a quote: it ignores model costs, trace charges and anything the page does not state.
Where the cost actually is. For most agent services the dominant cost is model tokens, not the platform: 03.7 and 11B.1 own that. The LangSmith-specific cost drivers are:
| Driver | Why it surprises people | Control |
|---|---|---|
| Trace volume | Every run of every agent step is a run inside a trace | Sampling (2.11), tracing off for low-value paths |
| Retention upgrades | Evaluators, rules and experiments extend retention at an extra fee (2.12) | Review which evaluators attach to which projects; run experiments deliberately |
| Deployments, not agents | The billing page: "charges apply per deployment not per agent" | Put several graphs in one langgraph.json instead of one deployment per graph |
| Unused deployments | A deployment bills while it exists (Dedicated) or while it is up (Serverless) | Delete unused and preview deployments; shorten "Scale down after" |
| Cron jobs | They run your graph, and they wake scale-to-zero deployments early | Delete crons you no longer need (6.8) |
| Seats | Plus is priced per seat | Review who actually needs one |
7.4 Choosing#
| Situation | Reasonable choice | Why |
|---|---|---|
| One agent, one team, an internal tool | Your own small service on the library (a FastAPI app plus a Postgres checkpointer), or Cloud on Plus | You may not need assistants, double texting or cron; the library gives you checkpointers and interrupts |
| Many agents, background and scheduled work, human approvals over days | Agent Server (Cloud to start) | These are what the server provides and what is tedious to build |
| Data must stay in your cloud account | Hybrid (the pricing page puts it under Enterprise) or BYOC (Enterprise, per the platform-setup page) | The data plane is yours; the control plane is LangChain's |
| Data must not leave your network at all | Self-hosted LangSmith and a self-hosted server (Enterprise), or no LangSmith | Only this keeps traces inside |
| A small team that must self-host and does not need LangSmith | The library plus your own service | Elastic-2.0 and the licence-key and Kubernetes demands of the standalone server are heavy for a small team |
| Evaluating the platform | Developer plan plus langgraph dev |
Free; remember datasets and traces then live in LangChain's Cloud |
08F.1, Part 6 compared hosted agent platforms across vendors, and 11C.1 is the general deployment lesson; the build-versus-buy reasoning is the same here.
Part 8: Security notes#
Deep-dive
The general security model of LLM systems is Module 12: 12.4 for personal data, 12.6 for tools and agents, 12.7 for data and dependencies. This part collects what is specific to LangSmith, Studio and Agent Server, as of 14 November 2026.
8.1 Traces are data#
A trace contains your prompts, the tool arguments and the tool results: that is the point of it, and it means a trace store is a copy of your most sensitive conversations, readable by everyone with access to the workspace, kept for 14 or 180 days (or forever, in a dataset: 2.12). The controls, from the narrowest to the broadest:
| Control | Where | Strength | Covered in |
|---|---|---|---|
TracePolicy / omit_payload |
One node's own run | Trims one node's span; not a security control (the library says so) | 2.11 |
Client(anonymizer=...), create_anonymizer, create_secret_anonymizer |
Every run of that client, both directions | Strong for patterns you can write down | 2.11 |
hide_inputs, hide_outputs, hide_metadata, and the LANGSMITH_HIDE_* variables |
Every run | Blunt and complete for that part, but remember the echo (2.11) | 2.11 |
LangSmithSecret |
A string value you mark | Python only, langsmith>=0.12.3, uploads only, lost by f-strings and .format |
2.11 |
tracing_context(enabled=False) and conditional tracing |
One request or block | Complete for that request: nothing is uploaded | 2.7 |
LANGSMITH_TRACING_SAMPLING_RATE |
Statistical | Reduces exposure, does not remove it | 2.11 |
LANGSMITH_TRACING=false |
The whole process | Complete | 2.2 |
| An OpenTelemetry gateway that redacts | Your infrastructure, before the backend | Strong, and independent of the SDK | 2.13 |
| Self-hosted LangSmith | Where the data lives | The traces never leave your network | Part 7 |
Combine them: an anonymizer for the patterns you know, conditional tracing off for the paths you must never record, and the test of 4.4 so the configuration cannot silently regress. Also decide who can open the workspace, because masking protects only what you thought to mask.
8.2 The server#
- Authentication is yours to add on a self-hosted server, which has "No default authentication". On LangSmith deployments the default is a LangSmith API key in
x-api-key, and custom auth is available on all plans (6.11). Authentication also guards the MCP and A2A endpoints (6.10). - Authorisation is the other half. Authenticating a user does not stop user A reading user B's thread: the
@auth.onhandlers do that (6.11), and the store has no access control of its own (08F.11). Test it with two users. - Webhooks are outbound calls to a URL a client can name: restrict the destinations (
allowed_domains,require_https,allowed_ports,disable_loopback,max_url_length), keep loopback blocking on in production, and validate a secret token on the receiving side (6.9). An unrestricted webhook is a server-side request forgery primitive: a caller can make your server contact any internal address. - Encryption at rest is built in with
LANGGRAPH_AES_KEY(lazy rotation), or custom handlers for per-tenant keys (6.11). Keep the key in a secret store, not in the image. - Keys and images. The
.envyou name inlanggraph.jsonis for development. Production secrets belong in your platform's secret store, injected as environment variables at run time; check what your build copies into the image (dockerfile_lines,ADD . /deps/...) so a stray.envor key file never ships inside a layer. A smaller base (image_distro: "wolfi", which the docs recommend as "smaller and more secure") has fewer packages to patch. - Build reproducibility. A
"dependencies": ["."]build re-resolves packages and ignoresuv.lock(5.4). Install from the lock ("source": {"kind": "uv"}) or pin.
8.3 Published advisories#
GitHub's advisory lists show that this stack gets real vulnerabilities and fixes them, which is a reason to keep it updated, not a reason to avoid it. As of 14 November 2026 (counts and examples from the GitHub advisory API, recorded in this lesson's fact sheet; read each advisory for affected versions before acting):
| Repository | Published advisories | Examples |
|---|---|---|
langchain-ai/langchain |
9 | CVE-2025-68664 (critical: serialization injection that can extract secrets in dumps/loads), CVE-2026-44843 (high: unsafe deserialization through overly broad load() allowlists), CVE-2026-34070 (high: path traversal in the legacy load_prompt), CVE-2025-65106 (template injection), and server-side request forgery items |
langchain-ai/langgraph |
13 | CVE-2025-64439 (high: remote code execution in the json mode of JsonPlusSerializer), CVE-2026-28277 (unsafe msgpack deserialization when loading checkpoints), CVE-2026-48775 (unsafe JSON deserialization when loading checkpoints), CVE-2026-104873 (high: SDK custom auth silently ignoring actions=), CVE-2026-115885 (the CLI printing the registry push token in langgraph deploy --verbose) |
langchain-ai/deepagents |
2 | Filesystem permission and shell approval bypasses |
The lessons to take, none of which needs the details:
- Treat checkpoint stores as trusted-only. Several advisories are about deserializing checkpoints. Whoever can write to your checkpoint database can influence what your process loads: restrict write access, and consider the strict msgpack mode in 08F.11, 6.3.
- Keep packages updated, on purpose. Upgrade through a lockfile and a test run (08F.4, 5.10), and subscribe to the advisories of the repositories you use.
- Do not run
langgraph deploy --verbosein CI logs, and rotate any token that has ever been printed. - Re-test authorisation after upgrades (the custom-auth advisory is the example).
- Serialization is an attack surface. Do not load untrusted serialized objects, and do not let user input choose a file path to a prompt loader.
8.4 The official policy, and reporting#
The OSS security policy (docs.langchain.com/oss/python/security-policy) asks you to apply least privilege, to "anticipate potential misuse" and to use defence in depth (for example read-only credentials plus sandboxing for tools that touch files or networks). To report a vulnerability, it points to the Intigriti programmes "LangChain Open Source VDP" (the open-source packages) and "LangChain VDP" (LangSmith); the other contact is security@langchain.dev. Report privately, not in a public issue.
Part 9: Legacy names, and how to read old tutorials#
Reference
Tutorials for this area age fastest of all, because the product names changed three times. Translate before you copy:
| You read | What it means today | Notes |
|---|---|---|
LANGCHAIN_TRACING_V2=true |
LANGSMITH_TRACING=true |
Still honoured by langsmith 0.14.17 (2.2) and still wins over the new variable when both are set. Remove it from old .env files |
LANGCHAIN_API_KEY, LANGCHAIN_PROJECT |
LANGSMITH_API_KEY, LANGSMITH_PROJECT |
The LANGCHAIN_ forms are legacy aliases. Do not mix the project variables with the agent variables (2.3) |
| "LangGraph Platform", "LangSmith Deployment", "LangGraph Server" | LangSmith Agent Server | The same runtime (1.1); packages and the CLI keep langgraph-* |
| "LangGraph Studio" | LangSmith Studio, a web UI that connects to a local server | This lesson verified only the current web flow: check the date of any tutorial that describes something else |
MemorySaver |
InMemorySaver (the same class, langgraph.checkpoint.memory) |
The LangGraph test page still imports MemorySaver |
An evaluator def f(run, example) |
Still valid | An evaluator may ask for any subset of run, example, inputs, outputs, reference_outputs (3.3). The inputs/outputs/reference_outputs form needs langsmith>=0.3.13 |
from langchain.callbacks.tracers import LangChainTracer passed as a callback |
Rarely needed now | Environment variables or tracing_context do the job in Python; JavaScript still uses a LangChainTracer callback for selective tracing |
| Hosting advice that names plans (Developer, Plus) and prices | Check the pricing page | Plan names and what they include changed more than once (Part 7) |
langgraph up as the deployment story |
langgraph up is a local Docker rehearsal; production is a standalone server on Kubernetes, or Cloud |
5.4 and 7.1 |
08F.4, Part 4 is the whole-library migration guide, and 08F.15 covers migration in more depth. The rule from there applies here too: date the tutorial, then translate it.
Part 10: A production checklist#
Use it before the first real user, and again before each major change.
Tracing and privacy
-
LANGSMITH_TRACING=trueis exactly lowercasetrue, set before the first traced call (2.2), and no staleLANGCHAIN_TRACING_V2is in the environment. - A decision is written down about which paths are traced, which are sampled, and which are never traced (2.7, 2.11).
- An anonymizer (or hiding) is configured, and a test like 4.4 proves a sample secret and a sample email never appear in the recorded upload.
- Root runs, tool arguments and metadata are covered by that test, not only the model messages.
- Every request carries
environment,app_versionand a request or user id as tags or metadata (2.5), andthread_idis on every run of a turn (2.8). - Short-lived processes flush (
wait_for_all_tracers()orClient().flush(); do not rely onLANGCHAIN_CALLBACKS_BACKGROUND) (2.9). - Retention, rate limits and the cost of evaluators that extend retention are understood (2.12, 7.3).
Tests and evaluation
- Control flow has unit tests with fakes (Part 4): every router branch, every interrupt path, one test per tool error, one multi-turn test.
-
LANGSMITH_TEST_TRACKING=falseis the default for the unit job (3.7). - Integration tests are marked, excluded by default, skipped without keys, and assert on structure (4.5).
- A dataset exists with failures from production and hand-written edge cases, masked first (3.2).
- At least one trajectory evaluator and one outcome evaluator run before release, and LLM judges are calibrated against human labels (10A.5).
Deployment
-
langgraph validateruns in CI, and a test imports the graph module for real (5.2). - The graph exported to the server has no checkpointer or store of its own (5.2).
- The build installs from the lock (
source: {kind: uv}) or from pinned versions, andapi_versionis pinned for the server release you tested (5.2, 5.4, 6.2). - The
multitask_strategyis chosen on purpose and tested with two quick messages (6.7). - Authentication and per-user authorisation exist, and a two-user test passes after every upgrade (6.11).
- Webhook URLs are restricted, loopback blocking is on, the receiver validates a token, treats
successas "check the thread" and is idempotent (6.9). - Crons are converted to UTC (or a tested
timezone), and each has an owner and a deletion date (6.8). - Thread TTLs and deletion procedures match your retention promises (6.4).
- Hosting, licence terms (including Elastic-2.0 for the server packages) and cost have been reviewed by someone who owns them (Part 7).
Operations
- You know what you would do if LangSmith were down: tracing is off the request path (background upload), so the service continues, but check your own configuration.
- Advisories for
langchain,langgraphand the CLI are watched, and upgrades go through the lockfile and the test suite (8.3). - The CLI is never run with
--verbosein shared logs (8.3).
Common misconceptions#
| Misconception | Reality |
|---|---|
| "LangChain and LangGraph need LangSmith." | Both are MIT libraries that run without it. Tracing is opt-in through environment variables, and unit tests need no account (1.2, Part 4). |
"LANGSMITH_TRACING=True (or 1) turns tracing on." |
The SDK compares with the exact lowercase string true. True and 1 do nothing, silently (2.2). |
"LANGCHAIN_TRACING_V2 stopped working." |
langsmith 0.14.17 still honours it, and it takes precedence over LANGSMITH_TRACING, so a stale line can switch tracing off or on behind your back (2.2). |
| "I can set the variable in code after my imports." | The value is read once and cached on the first check. Set it before the first traced call (2.2). |
"hide_inputs=True hides the customer's data." |
It hides inputs only. A function that echoes its input leaks it through the output; use an anonymizer or hide both (2.11). |
"TracePolicy redacts a node's data from the trace." |
It changes only that node's own run; the root graph run still holds the data, and the library says it is not for redacting secrets (2.11). |
"evaluate(..., upload_results=False) keeps everything offline." |
Results stay local, but LangChain runs inside the target were still handed to the tracer in 0.14.17. Block egress and test it (3.5). |
"A @pytest.mark.langsmith test works offline like any test." |
Not unless LANGSMITH_TEST_TRACKING=false: otherwise the plugin calls LangSmith first and the test fails without a connection (3.7). |
"GenericFakeChatModel can drive create_agent as it is." |
create_agent calls bind_tools, which the plain fake does not implement; subclass it and return self (4.2). |
| "Passing unit tests means the agent works." | They prove the wiring. Whether a real model picks the right tool is an integration and eval question (4.7). |
"langgraph validate checks my graph." |
It checks the config file, statically. A missing graph variable passes; the server finds it at start-up (5.2). |
"langgraph dev is fully offline." |
It needs a LangSmith key, and traces, CLI analytics and Studio analytics are three different flows with different switches (5.7). |
| "LangGraph Server and Agent Server are different products." | The same runtime under older and current names (1.1). |
| "Assistants, double texting and cron are LangGraph features." | They are Agent Server features, not in the open-source library (6.3, 6.7). |
| "Updating an assistant changes only what I send." | The update creates a new version from scratch: send the whole payload (6.3). |
"A webhook with status: success means the run is finished." |
A run paused at interrupt() reports success too; read the thread (6.9). |
| "Cron schedules use my local time." | The docs say UTC; convert yourself, and watch daylight saving (6.8). |
| "Self-hosting the server is free because it is on PyPI." | Two separate facts. The packages' licence (Elastic-2.0) forbids offering them as a managed service and circumventing the licence key. Separately, the docs require a licence key for standalone production servers, and Kubernetes for production (Part 7). |
| "The cost of LangSmith is the plan price." | Retention upgrades, deployments, crons and trace volume add to it, and model tokens usually dominate (7.3). |
Key takeaways#
- Three layers, three names to keep straight. MIT libraries (
langchain,langgraph,langsmith), the LangSmith platform (a service), and the Agent Server runtime (Elastic-2.0 packages; formerly LangGraph Server and LangSmith Deployment). Only the libraries run with no account. - Tracing is one variable, with traps.
LANGSMITH_TRACING=true, exactly lowercase, set before the first traced call. The legacyLANGCHAIN_TRACING_V2still works in 0.14.17 and overrides the new name. Agent-based workspaces replace project names on Cloud (LANGSMITH_AGENT_IDandLANGSMITH_AGENT_ENVIRONMENT), and not on self-hosted. - Tag and name from day one.
tags,metadata,run_nameandthread_idinconfigreach every child run;@traceablecovers your own code at decoration, call and run time; flush in short-lived processes. - Look at the payload before you send it. A recorder client shows exactly what is uploaded: full inputs and outputs, a runtime block and extras such as a revision id.
- Mask in layers and test the masking. Anonymizer for patterns, hiding for whole parts (remembering the echo), conditional tracing for paths that must not be recorded, a self-hosted platform for data that must not leave.
TracePolicytrims a node's view and does not redact the root run. - Evaluators are plain functions. Write and call them before any experiment; trajectory modes (
strict,unordered,subset,superset) state different requirements; judges need calibration. upload_results=Falseis not an offline switch in the SDK version tested, and marked pytest tests needLANGSMITH_TEST_TRACKING=falseto run offline. Block the network and measure before you promise anyone "nothing leaves".- Unit-test everything that is control flow. Build graphs in a function taking the model and the checkpointer, compile per test, fake the model with the
bind_toolsfix, useupdate_state(as_node=...)for partial runs, assert on structure, and rehearse a restart with a shared saver. - Integration tests are marked, skipped without keys, structural and cheap; record and replay needs filtered headers and stale-cassette hygiene; evals measure what fakes cannot.
langgraph.jsonis the deployment contract. Validate it statically in CI, import the graph for real in a test, install from the lock, pinapi_version, and export the graph without its own checkpointer.- Agent Server adds assistants (versioned configurations), threads, runs, double texting and cron to the library's graphs, with PostgreSQL for data and Redis for signalling. These server features are not in the open-source library.
- Know the sharp edges of the server API. Assistant updates replace;
interruptandrollbackdouble-texting strategies differ in what they keep; cron is UTC; a webhooksuccesscan mean "waiting for a human"; loopback webhooks are blocked by default. - Security on the server is authentication, authorisation, webhook restrictions, encryption and updates. Test that user B cannot read user A's thread after every upgrade, and treat checkpoint stores as trusted-only.
- Hosting is a decision with a licence and a bill. Cloud, hybrid, self-hosted with a control plane and standalone differ in plan, licence key, Kubernetes demands and egress. Prices are a dated snapshot; model tokens usually cost more than the platform.
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
| LangSmith | LangChain's platform for tracing, evaluation, prompt iteration and deployment, framework-agnostic and a service rather than a library |
| Run (LangSmith) | One unit of traced work (a model call, a tool call, a node), the equivalent of an OpenTelemetry span |
| Trace | The tree of runs for one operation, tied together by a trace id (at most 25,000 runs) |
| Thread (LangSmith) | A multi-turn conversation: traces grouped by a shared thread_id in metadata |
| Trajectory | A flat ordered list of the messages of a thread or run, used to evaluate the path an agent took |
| Feedback | A score on a run: a key, a numeric score or categorical value, and an optional comment |
@traceable |
The decorator that turns your own function into a run, nesting inside other traced runs |
tracing_context |
A context manager that switches tracing, tags, metadata, client or agent address for a block, overriding the environment |
| Agent-based workspace | A LangSmith Cloud model in which traces belong to an agent id and one of four environments instead of a project |
| Agent address | The pair (agent id, environment) built with ls.agent_address, sent as lrn:agents/<id>/environments/<environment> |
| Recorder client | A langsmith.Client with a custom HTTP session that stores requests instead of sending them; used here to inspect and test traces offline |
| Anonymizer | A function given to Client(anonymizer=...) that rewrites matching strings in run inputs and outputs before upload |
TracePolicy |
A per-node setting (process_inputs, process_outputs) that changes what that node's own run records; omit_payload drops it |
| Dataset, example | A versioned collection of inputs (and optional reference outputs) used for evaluation; each item is an example |
| Reference outputs | The expected result stored on an example and never passed to your application |
| Experiment | The results of running one version of an application over a dataset: outputs, scores and traces |
| Evaluator | A function (or judge) that scores a run; it asks for any of run, example, inputs, outputs, reference_outputs |
| Offline and online evaluation | Scoring dataset examples before release (with references) versus scoring production runs (without) |
| LLM-as-judge | An evaluator in which a model grades an output against a rubric; needs calibration against human labels |
| Trajectory match mode | strict, unordered, subset or superset: how an agent's tool calls are compared with a reference |
| Fake chat model | A scripted model (GenericFakeChatModel, FakeListChatModel) that replays prepared replies so tests need no key |
| LangSmith Studio | A web IDE that connects to an Agent Server API to visualise, run, debug, fork and evaluate graphs |
langgraph.json |
The project file that names graphs, dependencies, environment, authentication, store, webhooks and image options for the server |
langgraph dev / up |
The local server without Docker (state pickled to disk, port 2024) versus with Docker, PostgreSQL and Redis (port 8123) |
| LangSmith Agent Server | The runtime (formerly LangGraph Server and LangSmith Deployment) that serves graphs as an API with persistence and a task queue |
| Assistant | A versioned configuration of a deployed graph (prompts, model, tools); each graph gets a default assistant; Agent Server only |
| Run (Agent Server) | One invocation of an assistant, stateless or on a thread, as a wait, a stream or a background job |
| Double texting | A new message arriving while a run is active; handled by the multitask_strategy: enqueue, reject, interrupt or rollback |
| Cron job (Agent Server) | A scheduled run of an assistant, with the same input each time, interpreted in UTC according to the docs |
| Run webhook | A callback the server makes when a run completes, whose success status also covers a run paused at an interrupt |
RemoteGraph |
A wrapper that lets a deployed assistant be used as if it were a local compiled graph |
| Agent Protocol | An open specification (Runs, Threads, Store) from LangChain, of which the Agent Server API is a superset, and the name of the wire formats for agent streaming events |
| LSU | The unit in which Agent Server resources are metered; 1 LSU is priced at $1.00 on the pricing page (as of 14 November 2026) |
| Standalone server | An Agent Server you run yourself with your own PostgreSQL, Redis and a licence key, without a control plane |
Exercises#
Exercises 1 to 9 run with no key and no account. Each has an answer to compare with after you try it.
- Predict, then run. Extend
s03_env_switches.pywith five more cases:LANGSMITH_TRACING=TRUE,LANGSMITH_TRACING_V2=true,LANGCHAIN_TRACING_V2=(empty),LANGSMITH_TRACING=" true"(a leading space) andLANGSMITH_TRACING=truetogether withLANGSMITH_TRACING_V2=false. Write down your predictions first. - A thread-id test. Add a test to
test_tracing_config.pythat gives the agent anInMemorySaver, invokes it withconfigurable={"thread_id": "conv-7"}and asserts that every run in the recorded tree hasthread_id == "conv-7"in its metadata. Then change the test to find the first run that does not, and say why that could break thread views. - Mask a card number. Add an anonymizer rule for 16-digit card numbers (with optional spaces) to
test_tracing_config.pyand a test with a tool call that carries4242 4242 4242 4242. Include the control test. - Write two evaluators and test them. Write
no_email(outputs) -> bool(False if the answer contains an address) andcites_order(inputs, outputs) -> dict(score 1 if the answer contains the order id from the question). Test them as plain functions with four hand-made runs. - Trajectories. Using
s20_local_evaluators.py, remove the extraget_customercall fromextra_stepand re-run. Predict the four modes first. Then swap the order of two tool calls in a trajectory with two different calls and predict again. - Cron. Write the UTC cron expressions for 08:00 Europe/London on 15 January and on 15 July 2026, and for 18:30 Asia/Tokyo. Use
utc_cron. Which of the three needs maintenance twice a year? - Webhook decisions. Extend
s41_webhook_handler.pyto handlestatus == "interrupted"andstatus == "timeout"differently fromerror. Add a test run with a payload for each. What should a handler do with arollback? - A two-graph config. Write a
langgraph.jsonwith two graphs (supportandbilling) in one deployment, validate it withlanggraph validate, and give two reasons this is cheaper than two deployments. Then break it three ways (a badpython_version, a badimage_distro, a typo in a key) and read the messages. - Hide everything. In
s16_trace_policy.py, replace the recorder withRecorder(hide_outputs=True)and run it. What do the four lines show now, and what is still visible? - Double texting, designed. For each of three products (a support chat, a payment-approval flow, a coding assistant that streams edits), choose a
multitask_strategy, and write the sentence you would put in the product spec for the case where the user sends a second message while the first is running.
Answers
- Real output:
LANGSMITH_TRACING=TRUEisFalse(case matters);LANGSMITH_TRACING_V2=trueisTrue(the SDK readsTRACING_V2under both prefixes, so this unofficial spelling works too: do not rely on it);LANGCHAIN_TRACING_V2=(empty) isFalsebecause empty values are ignored;" true"with a leading space isFalse(it must equaltrueexactly); andLANGSMITH_TRACING=truewithLANGSMITH_TRACING_V2=falseisFalsebecauseTRACING_V2wins. - With a checkpointer and
thread_idinconfigurable, LangGraph copies it into the metadata of the runs it creates (the sample in 2.4 shows it on the tool run).all(run["extra"]["metadata"].get("thread_id") == "conv-7" for run in runs)holds for every run in the tree (the author checked the root, node and model runs); if a custom@traceablehelper inside a node is in the tree and has nothread_id, the first failing run will be that helper, which is the bug the docs warn about: thread filtering and token counting skip runs without it. - Use
create_anonymizer([{"pattern": re.compile(r"\b(?:\d[ -]?){15}\d\b"), "replace": "<card>"}])(a pattern for sixteen digits with optional spaces or dashes), pass it asRecorder(anonymizer=...), and assert"4242" not in uploadedand"<card>" in uploaded. The control test, without the anonymizer, must find4242 4242 4242 4242in the upload. no_emailcan use a regular expression and returnre.search(...) is None;cites_orderreturns{"key": "cites_order", "score": int(order_id in outputs["answer"])}whereorder_idis extracted frominputs["question"]. Test with: a clean answer, an answer with an address, an answer that cites, an answer that does not. Note thatno_emailis a guardrail metric (it should be 1 on everything), whilecites_orderis a quality metric.- With the extra call removed the agent's trajectory equals the reference, so all four modes pass. With two different tool calls in swapped order,
strictfails (order differs), whileunordered,subsetandsupersetpass (the same set of calls). Choosestrictonly when the order is a requirement. - London:
0 8 * * *in January and0 7 * * *in July (British Summer Time), so it needs maintenance twice a year; Tokyo:30 9 * * *all year (Japan has no daylight saving). A schedule fixed in UTC for a daylight-saving city moves against local time twice a year: either update it, or, if your server version supports it, use thetimezoneargument and test it (6.8). - For
interrupted, look at the thread state and notify the human reviewer (a paused run is not a failure);timeoutis an alert and possibly a retry with a smaller task;erroris an alert with the error text;rollbackmeans the new run replaced this one (a double-textingrollback), so a handler should usually ignore it and wait for the replacement run's webhook. - Two graphs in one
langgraph.json("graphs": {"support": "...", "billing": "..."}) give one deployment with two default assistants, which is cheaper because charges apply per deployment, not per agent, and you pay for one database and one set of compute. The three breakages produce the messages shown in 5.2: an unsupported Python (below 3.11), an unsupportedimage_distro, and an unknown-key warning. - All outputs are empty, including the root
LangGraphrun's, because the client-level hiding covers every run. The inputs are still visible: theshoutnode's input still shows the drafted reply and the ticket. To hide both sides useRecorder(hide_inputs=True, hide_outputs=True), or an anonymizer to keep structure. - A support chat:
enqueue(orinterruptif the graph repairs a dangling tool call): "A message sent while we are replying is answered after the current reply." A payment-approval flow:reject: "While a payment is awaiting approval, new messages on that thread are refused with a message explaining why." A streaming coding assistant:interrupt: "Sending a new message stops the current edit stream and continues from what has been done so far", with the graph tested for the half-finished tool call (6.7).rollbacksuits "the user corrected the question": "The new message replaces the previous one."
Check yourself#
- Name the three layers of this lesson, their licences, and which of them needs an account.The libraries (MIT, no account), the LangSmith platform (a commercial service, needs an account and key), and the Agent Server runtime (packages under Elastic-2.0 on PyPI, local use needs a free key, production needs a licence) (1.1).
- Which exact value switches tracing on, which common values do not, and what happens if you set the variable after the first traced call?The exact lowercase string
true(inLANGSMITH_TRACING);True,TRUE,1and a value with a leading space do not. The value is read once and cached, so setting it after the first check changes nothing in that process (2.2). - A leftover
LANGCHAIN_TRACING_V2=falsein.envandLANGSMITH_TRACING=truein the shell: is tracing on? Why? - What do agent-based workspaces replace, which two variables do they use, and on which kind of LangSmith do they not exist?Free-form project names (
LANGSMITH_PROJECT); they useLANGSMITH_AGENT_IDandLANGSMITH_AGENT_ENVIRONMENT(local,development,staging,production); they do not exist on self-hosted LangSmith (2.3). - At which three levels can
@traceableruns get tags and metadata, and what do child runs inherit?At decoration (@traceable(tags=..., metadata=...)), per call (langsmith_extra) and while running (get_current_run_tree()); child runs inherit the parent's tags and metadata that were set before they started (2.6). - Why can a short-lived process lose its last traces, and what actually fixes it?Tracing uploads from a background thread, so the process can exit first. Fixes:
wait_for_all_tracers()(LangChain) andClient().flush()(SDK), including at the end of a serverless handler.LANGCHAIN_CALLBACKS_BACKGROUND=falseis in the docs, but nothing in the installed Python packages reads it, so it fixes nothing there (measured) (2.9). - Give two ways in which
hide_inputs=Truecan still leave sensitive data in a trace.The output may echo the input, and metadata, tool arguments and child runs of other clients are separate paths; also, a model's reply can restate personal data it was given (2.11). - What does
TracePolicychange and what does it leave alone?It changes what one node's own run records (process_inputs,process_outputs,omit_payload) and leaves the root graph run and child runs alone; the library says it is not for redacting secrets (2.11). - What is an evaluator, in code terms, and what are the four return shapes?A function that takes any subset of
run,example,inputs,outputs,reference_outputsand returns a dict withkeyandscoreorvalue, a bool/int/float (metric named after the function), a string (category), or a list of dicts (several metrics) (3.3). - What do the four trajectory match modes mean, and which would you pick for "the agent must at least call these tools"?
strict: same calls in the same order;unordered: same calls in any order;subset: only calls that appear in the reference;superset: every reference call, possibly more. "At least these tools" issuperset(3.3). - What did the offline measurement of
evaluate(..., upload_results=False)show, and what did stop the upload attempts?Scores were local, but LangChain runs inside the target still attempted a multipart upload;tracing_context(enabled=False)andLANGSMITH_TRACING=falsedid not stop it,LANGSMITH_TRACING_SAMPLING_RATE=0did (3.5). - Why does a test marked
@pytest.mark.langsmithfail without a network, and how do you stop that?The plugin contacts LangSmith to create the dataset and experiment before running your assertions (aGET /datasetsin the measurement). SetLANGSMITH_TEST_TRACKING=false(3.7). - Why does
create_agentfail with a plainGenericFakeChatModel, and what is the fix?create_agentcallsbind_tools, whichGenericFakeChatModeldoes not implement. Subclass it withdef bind_tools(self, tools, **kwargs): return self(4.2). - What does
graph.nodes["classify"].invoke(...)bypass, and what doesupdate_state(..., as_node=...)followed byinvoke(None, ..., interrupt_after=...)let you do?The first runs one node alone and bypasses the checkpointer and the other nodes. The second pretends a node already ran and executes only the following nodes up to the breakpoint (4.3). - What does
langgraph validatecatch and not catch?It catches an unsupportedpython_versionorimage_distro, an invalidpip_installerand (as a warning) an unknown key; it does not import your code or check that the graph file or variable exists, so a wrong path or variable name passes (5.2). - What are assistants, threads and runs, and which of the three are not available in the open-source library?Assistants (versioned graph configurations), threads (persistent conversations) and runs (invocations). Assistants and double texting are Agent Server concepts, not in the library; threads and checkpointers exist in the library in their own form (6.3).
- Name the four
multitask_strategyvalues and what each does to the running run.enqueue(wait, then run),reject(refuse the new input),interrupt(stop the running run but keep its progress and continue from it) androllback(stop it and revert its progress, including the original input) (6.7). - In which time zone are cron schedules read according to the docs, and what differs in
langgraph-sdk0.4.14?UTC; the 0.4.14 SDK'scrons.createhas atimezoneargument ("interpreted in UTC unless a timezone is specified"), which the docs page does not show, so test it on your server (6.8). - Why can a webhook with
status: successbe wrong to treat as done?A run paused atinterrupt()is reported assuccess; read the thread's state (a non-emptynext) to know whether it is done or waiting (6.9). - Which hosting options need an Enterprise plan, and what does a standalone server need beyond the image?Self-hosted with a control plane (Enterprise with Agent Server hosting), hybrid (listed under Enterprise on the pricing page; the deployment page names no plan), and self-hosted or BYOC LangSmith (Enterprise). A standalone server needs your own PostgreSQL and Redis, a licence key (
LANGGRAPH_CLOUD_LICENSE_KEY), egress to the licence-verification endpoint unless air-gapped, and Kubernetes with the Helm chart for production (7.1).
Further resources#
The official pages are more complete than this lesson, especially for the product features that change every month (agent-based workspaces, evaluators, deployment options, pricing). Read them, and read the changelogs. 08F.17 maps the whole documentation and gives a reading order. Pages under docs.langchain.com were checked on 14 November 2026.
Tracing
- LangSmith observability overview and concepts (runs, traces, threads, tags, metadata, feedback)
- Observability quickstart, trace with LangChain, trace with LangGraph
- Custom instrumentation (
@traceable,trace,RunTree) and metadata and tags - Log traces to an agent, the agent registry and migrating to agent-based workspaces
- Mask inputs and outputs, redact secrets, sample traces and data storage and privacy
- Usage and billing (retention, rate limits) and billing
Evaluation and testing
- Evaluation overview, concepts, quickstart and managing datasets
- Evaluate an LLM application, code evaluators, LLM-as-judge, evaluate a graph, intermediate steps and trajectory evals
- The pytest integration and openevals; the packages on PyPI:
openevalsandagentevals - LangChain's testing pages: overview, unit testing, integration testing, evals, and testing LangGraph
- In this course: Module 10A for evaluation design, 08A.14 for agent reliability and a from-scratch eval harness, 03.10 for mocking and testing LLM code
Studio, the CLI and the server
- LangSmith Studio, Studio quickstart, using Studio and the OSS Studio walkthrough
- Local development and testing (
devversusup), the CLI reference and application structure (langgraph.json) - Deployment hub, Agent Server architecture, its changelog, platform setup, release versions and self-hosted
- Assistants, threads, runs, stateless runs, background runs, double texting, cancelling runs, cron jobs and webhooks
- Authentication, the MCP endpoint, the A2A endpoint, the API reference and the OpenAPI document
- The Agent Protocol repository, the LangSmith Helm chart, and PyPI pages for
langsmith,langgraph-cli,langgraph-sdkandlanggraph-api
Cost and security
- LangChain pricing (re-check before quoting any number)
- The OSS security policy, and the security advisories pages of the
langchainandlanggraphrepositories - In this course: 08F.4 for the ecosystem and upgrade routine, 08F.8 to 08F.14 for the graph features this lesson tests and deploys, 08F.15 for patterns and migration, Module 11A for observability and Module 11C for deployment in general, and Module 12 for the security model
← 11A.4: Production Traces into Eval Datasets | Module 11A overview | Module 11B: Cost, Usage and Token Management →