Tracing and monitoring with LangSmith

Topic 1 of 4 in Observability & evaluation23 min readAdvancedFree course

Overview

A LangGraph application can execute successfully while behaving inefficiently. An agent might generate a correct answer after eight unnecessary model calls, repeatedly retrieve identical documents, or spend most of its execution time waiting for an external service.

Looking only at the final response reveals none of these problems.

In the previous lesson, you implemented node caching, loop guards, retries, and fault-tolerant workflows. You now need evidence that those mechanisms are working as intended.

LangSmith is an observability, evaluation, and agent development platform that provides visibility into the execution of AI applications. Its tracing integration with LangGraph makes it possible to investigate what happened inside an agent invocation rather than treating the application as a black box.

Observability helps answer questions such as:

  • Which execution path did the graph follow?
  • Which nodes and tools were invoked?
  • What information was sent to each model?
  • Why did a particular operation fail?
  • Which component consumed the most time?
  • How many tokens did the workflow consume?
  • Did a new release increase operational costs?

The observability mental model

Traditional logging records individual events. Tracing connects related operations into a hierarchy, while monitoring aggregates measurements across many executions.

Capability Purpose Example
Logging Record individual events Database connection failed
Tracing Reconstruct one execution Agent called retrieval twice
Monitoring Analyze behavior over time P95 latency increased
Evaluation Measure application quality Answer groundedness declined
Checkpointing Preserve execution state Resume an interrupted graph

These capabilities complement one another. A checkpoint preserves graph state, whereas a trace describes execution activity. Neither replaces the other.

Traces and runs

A run, also called a span, represents an instrumented operation with its own identity, timing, inputs, outputs, and execution status.

A trace groups related runs into a tree. The root run typically represents the graph invocation, while child runs represent its constituent operations.

A conversation thread can contain multiple traces, such as one trace for each user turn or graph invocation.

The following diagram illustrates a simplified trace hierarchy.

Overview diagram: Graph invocation to Classify node; Graph invocation to Retrieve node; Graph invocation to Respond node; Classify node to Model call; Retrieve node to Database query; Respond node to Model call.

The tree represents execution containment, not necessarily chronological order. Parallel nodes can produce overlapping spans.

Internally, LangChain and LangGraph instrumentation generates lifecycle events as operations begin, complete, or fail. The tracing SDK associates these operations through identifiers and parent relationships, then submits telemetry to LangSmith.

Only instrumented operations are visible. LangSmith is not automatically a profiler of every Python statement or external network request.

Turn on tracing

Install the dependencies

Use Python 3.11 or later for the examples.

Terminal
pip install -U "langgraph>=1,<2" "langchain>=1,<2" langchain-openai "langsmith>=0.14.12"

You need an OpenAI API key, a LangSmith account, and a LangSmith API key with appropriate permissions.

Open LangSmith, select your workspace, and connect an existing agent. For this lesson, create an external agent named Customer Support with the identifier customer-support.

This registration represents your application in LangSmith; it does not deploy or execute your Python graph.

Configure environment variables

Set the following variables in your terminal or inject them through your application’s secret management system.

Terminal
export OPENAI_API_KEY="your-openai-api-key"
export LANGSMITH_API_KEY="your-langsmith-api-key"
export LANGSMITH_TRACING="true"
export LANGSMITH_AGENT_ID="customer-support"
export LANGSMITH_AGENT_ENVIRONMENT="local"

The configuration separates credentials, tracing activation, and the telemetry destination.

For accounts associated with multiple workspaces, configure LANGSMITH_WORKSPACE_ID as appropriate. If your workspace uses a non-default region, configure its corresponding LANGSMITH_ENDPOINT.

Project names and agent environments

Earlier LangSmith configurations commonly used LANGSMITH_PROJECT to organize traces. This remains relevant for integrations that require project-based addressing.

Current LangSmith agent addressing organizes telemetry using an agent identifier and an environment, such as local, development, staging, or production.

For a project-based integration, configure:

Terminal
unset LANGSMITH_AGENT_ID
unset LANGSMITH_AGENT_ENVIRONMENT
export LANGSMITH_PROJECT="your-environment-tracer-session-name"

Use the actual tracer_session_name supplied by LangSmith for the target environment, rather than inventing a project name.

For the remaining examples, use agent addressing and leave LANGSMITH_PROJECT unset.

Note: Do not combine project-based destination variables with agent-addressing variables. Conflicting destinations can prevent traces from being submitted. See the current agent addressing documentation.

Trace your first graph

The following complete example creates a small graph with two nodes. The first prepares a question, and the second invokes a language model.

Python
from typing import TypedDict
from langchain.chat_models import init_chat_model
from langchain.messages import HumanMessage, SystemMessage
from langgraph.graph import StateGraph, START, END
from langchain_core.tracers.langchain import wait_for_all_tracers

model = init_chat_model("openai:gpt-5.4-mini")

class State(TypedDict, total=False):
    question: str
    answer: str

def prepare(state: State) -> dict:
    return {"question": state["question"].strip()}

def generate(state: State) -> dict:
    response = model.invoke([
        SystemMessage(
            content="Explain technical concepts in two concise sentences."
        ),
        HumanMessage(content=state["question"]),
    ])

    return {"answer": response.text}

builder = StateGraph(State)
builder.add_node("prepare", prepare)
builder.add_node("generate", generate)

builder.add_edge(START, "prepare")
builder.add_edge("prepare", "generate")
builder.add_edge("generate", END)

graph = builder.compile()

try:
    result = graph.invoke(
        {"question": "What is a database index?"},
        config={"recursion_limit": 10},
    )

    print(result["answer"])
finally:
    wait_for_all_tracers()

Expected output resembles:

Text
A database index is a data structure that helps a database
locate records efficiently. It improves query performance
but requires additional storage and maintenance.

The exact wording will vary.

Notice that neither node contains explicit tracing code. LangGraph and LangChain provide the necessary integration automatically.

The wait_for_all_tracers() function helps pending LangChain tracing callbacks finish before the script exits. This matters especially in short-lived scripts and serverless environments.

The examples in this lesson use synthetic data and the course’s specified model. They are documentation-aligned runnable examples, but their live execution has not been verified against a credentialed LangSmith workspace. Displayed model responses, durations, and costs are illustrative.

Reading a trace

After executing the graph, open LangSmith, select the registered agent, navigate to its tracing interface, and select the Local environment.

Open the latest trace and expand its run tree.

A simplified representation might look like this:

Text
LangGraph                     1,245 ms
├── prepare                       1 ms
└── generate                  1,220 ms
    └── ChatOpenAI            1,180 ms

Additional internal operations may appear depending on the framework version and instrumentation.

Inspect the root run

The root run provides an overview of the invocation:

  • Original graph inputs and final outputs.
  • Execution start and end timestamps.
  • Overall duration and execution status.
  • Aggregated model usage and estimated costs, when available.
  • Tags, metadata, and run identifiers.

Start here when investigating a failed or unexpectedly expensive request.

Inspect individual child runs

Select the generate node, then expand its model invocation.

You can investigate the messages sent to the model, the generated response, available token usage, model configuration, timing, and recorded errors.

For tool-calling agents, inspect the model’s requested tool calls alongside the corresponding tool executions and returned results. This reveals whether an unexpected answer originated from model behavior, inaccurate tool data, or orchestration logic.

Understand the timing hierarchy

Suppose a node takes 1,200 milliseconds and contains a model call lasting 1,000 milliseconds.

The parent duration already includes its child’s execution. Adding both durations would incorrectly report 2,200 milliseconds.

Parallel execution requires similar care: two operations lasting 800 and 900 milliseconds may complete together in approximately 900 milliseconds rather than 1,700 milliseconds.

Use root duration for end-to-end graph execution latency and inspect child timings to identify contributing operations.

Monitoring individual nodes

Node-level monitoring is particularly important in agentic systems because routing, loops, retries, and parallel execution create variable workloads.

Consider a support graph with two parallel research operations.

The following diagram illustrates a workflow in which dependency latency can dominate the response time.

Monitoring individual nodes diagram: START to Classify request; Classify request to Search knowledge; Classify request to Fetch account; Search knowledge to Generate response; Fetch account to Generate response; Generate response to END.

If account retrieval becomes slow, optimizing the knowledge search may have little effect on overall latency.

Instrument work inside a node

LangGraph automatically traces node execution, but ordinary functions called inside nodes may not receive individual spans.

Use LangSmith’s traceable decorator to expose important internal operations.

This example simulates a slow database lookup inside a graph node.

Python
import time
from typing import TypedDict
from langsmith import traceable
from langgraph.graph import StateGraph, START, END
from langchain_core.tracers.langchain import wait_for_all_tracers

class State(TypedDict, total=False):
    product_id: str
    product: dict

@traceable(name="database_lookup", run_type="tool")
def database_lookup(product_id: str) -> dict:
    time.sleep(0.2)

    catalog = {
        "P100": {"name": "Mechanical Keyboard", "stock": 14}
    }

    return catalog.get(product_id, {"stock": 0})

def retrieve_product(state: State) -> dict:
    product = database_lookup(state["product_id"])
    return {"product": product}

builder = StateGraph(State)
builder.add_node("retrieve_product", retrieve_product)
builder.add_edge(START, "retrieve_product")
builder.add_edge("retrieve_product", END)

graph = builder.compile()

try:
    result = graph.invoke({"product_id": "P100"})
    print(result["product"])
finally:
    wait_for_all_tracers()

Expected output:

Text
{'name': 'Mechanical Keyboard', 'stock': 14}

The trace should contain a retrieve_product node with a nested database_lookup operation lasting approximately 200 milliseconds.

The delay simulates database latency; no real database is required.

Monitor failures, retries, and caching

Track node invocation counts, error rates, execution durations, and repeated calls.

A successful root trace does not necessarily mean every dependency succeeded. A retry may recover from an error, or a fallback may allow the graph to finish.

Likewise, a cached node may avoid executing its underlying function. Missing child operations can indicate successful caching rather than broken tracing.

Compare traces from equivalent cached and uncached requests to validate the optimization introduced in the previous lesson. Add explicit application-level cache-hit telemetry when you need reliable hit-rate measurements.

For recurring analysis, configure node-specific dashboard charts using stable run names and relevant metadata.

Tags, metadata and names

Without consistent naming, a production tracing environment becomes difficult to navigate.

LangChain’s runnable configuration supports three useful mechanisms for organizing traces.

Configuration Purpose Example
run_name Identify an operation support_workflow
tags Attach searchable labels ["support", "canary"]
metadata Record structured attributes {"release": "2.1.0"}
run_id Identify one execution A unique UUID

Tags and metadata generally propagate to nested runnable executions. A root run_name, however, does not rename every child operation.

Add structured tracing context

The following example attaches deployment information and creates a unique identifier that can also be recorded in application logs.

Python
from typing import TypedDict
from langsmith import uuid7
from langgraph.graph import StateGraph, START, END
from langchain.chat_models import init_chat_model
from langchain_core.tracers.langchain import wait_for_all_tracers

model = init_chat_model("openai:gpt-5.4-mini")

class State(TypedDict, total=False):
    question: str
    answer: str

def answer_question(state: State) -> dict:
    response = model.invoke(state["question"])
    return {"answer": response.text}

builder = StateGraph(State)
builder.add_node("answer_question", answer_question)
builder.add_edge(START, "answer_question")
builder.add_edge("answer_question", END)

graph = builder.compile()

run_id = uuid7()

config = {
    "run_id": run_id,
    "run_name": "support_workflow",
    "tags": ["customer-support", "canary"],
    "metadata": {
        "release": "2.1.0",
        "prompt_version": "v3",
        "tenant_tier": "standard",
    },
    "recursion_limit": 15,
}

try:
    result = graph.invoke(
        {"question": "How do database transactions work?"},
        config=config,
    )
    print("Trace ID:", run_id)
    print(result["answer"])
finally:
    wait_for_all_tracers()

The generated trace can be located using its run ID or filtered by the release, tags, and other recorded attributes.

Use consistent naming across deployments so that comparisons remain meaningful.

Avoid putting request IDs into run names: this makes aggregation difficult. Unique identifiers belong in run IDs or correlation metadata.

Tracing metadata is not a substitute for LangGraph runtime context. Pass application-specific user data through context_schema and invocation context; reserve tracing metadata for approved observability attributes.

Token, latency and cost tracking

Production monitoring should move beyond individual traces to measurable performance trends.

Token consumption monitoring

Supported model integrations expose token usage through the returned AIMessage.

The following example demonstrates local usage inspection independently of the LangSmith interface.

Python
from langchain.chat_models import init_chat_model
from langchain_core.tracers.langchain import wait_for_all_tracers

model = init_chat_model("openai:gpt-5.4-mini")

try:
    response = model.invoke(
        "Explain an HTTP status code in one sentence."
    )

    usage = response.usage_metadata

    if usage is not None:
        print("Input tokens:", usage["input_tokens"])
        print("Output tokens:", usage["output_tokens"])
        print("Total tokens:", usage["total_tokens"])
    else:
        print("Token usage was not reported.")
finally:
    wait_for_all_tracers()

Illustrative output:

Text
Input tokens: 18
Output tokens: 21
Total tokens: 39

Actual counts depend on the provider, request, model behavior, and reported usage fields.

LangSmith aggregates available usage information across model invocations. Some providers also expose cached-input and reasoning-token details.

An agent’s accumulated conversation history, retrieved documents, tool descriptions, and repeated calls can all increase token consumption. A short final answer is therefore not necessarily inexpensive.

Calculate estimated model cost

For a simple model pricing structure:

Cost = (input tokens × input rate + output tokens × output rate) / 1,000,000

Rates here represent prices per million tokens.

The following example uses hypothetical rates to demonstrate the calculation.

Python
from decimal import Decimal

input_tokens = 2400
output_tokens = 600

input_rate = Decimal("0.50")
output_rate = Decimal("2.00")

cost = (
    input_tokens * input_rate
    + output_tokens * output_rate
) / Decimal("1000000")

requests_per_day = 10000

print(f"Request cost: ${cost:.6f}")
print(f"Daily cost: ${cost * requests_per_day:.2f}")

Expected output:

Text
Request cost: $0.002400
Daily cost: $24.00

These are illustrative rates, not the actual pricing of GPT-5.4-mini.

Real billing may distinguish cached tokens, reasoning tokens, modalities, and provider-specific charges. LangSmith calculates supported costs using usage data and configured model pricing. Missing pricing or token information can produce incomplete estimates.

Additionally, database charges, external API fees, infrastructure, and LangSmith’s own charges are not necessarily included in automatically calculated model costs. Custom cost instrumentation can account for additional operations.

See the LangSmith cost tracking documentation for supported breakdowns.

Latency metrics

Averages alone can hide poor experiences. Monitor latency distributions instead.

Metric Meaning
P50 Median execution duration
P95 Duration at or below which 95% of executions finish
P99 Duration at or below which 99% of executions finish
TTFT Time to first generated token
Error rate Percentage of executions classified as failed
Cost per trace Recorded expenditure per traced execution

Time to first token is especially useful for streaming applications. It differs from the time required to finish generating the complete response.

Provider streaming measurements depend on available instrumentation. For actual user-perceived latency, measure your application gateway and streaming delivery path as well.

Create production dashboards

Open the agent environment’s tracing page and its associated dashboard. Current LangSmith interfaces also expose monitoring analytics and configurable workspace dashboards.

Monitor:

  • Trace volume and error rates.
  • P50 and P95 root latency.
  • Model and tool execution durations.
  • Input and output token consumption.
  • Total cost and average cost per trace.
  • Performance grouped by release or workflow.

For a canary deployment, compare matching workloads between the old and new release. Otherwise, changes in request complexity may be mistaken for performance regressions.

Define operational thresholds appropriate for your application, such as P95 latency below four seconds and an error rate below one percent.

Where supported, configure alerts for sustained threshold violations. Avoid triggering incidents from a single slow request.

See the dashboard documentation for available monitoring capabilities.

Query node telemetry programmatically

The LangSmith SDK also supports retrieving trace data for automated reporting.

This example queries completed answer_question runs from the last 24 hours and calculates their average duration.

Python
import asyncio
import os
from datetime import datetime, timedelta, timezone
from statistics import mean

from langsmith import Client, agent_address

async def report():
    client = Client()

    address = agent_address(
        os.environ["LANGSMITH_AGENT_ID"],
        os.environ["LANGSMITH_AGENT_ENVIRONMENT"],
    )

    session = await client.sessions.resolve(**address)
    since = datetime.now(timezone.utc) - timedelta(hours=24)

    durations = []

    async for run in client.runs.query(
        project_ids=[session.session_id],
        min_start_time=since,
        filter='eq(name, "answer_question")',
        selects=["ID", "NAME", "START_TIME", "END_TIME"],
    ):
        if run.start_time and run.end_time:
            durations.append(
                (run.end_time - run.start_time).total_seconds()
                * 1000
            )

    if durations:
        print("Completed node runs:", len(durations))
        print(f"Average latency: {mean(durations):.2f} ms")
    else:
        print("No completed matching runs found.")

if __name__ == "__main__":
    asyncio.run(report())

Run this after executing the previous support_workflow example. Your API credential needs permission to query traces.

The current client.runs.query() API supersedes older list_runs() usage. Agent-environment resolution also depends on deployment and SDK support; consult the trace query documentation for alternative configuration in BYOC environments.

Tracing code outside LangChain

Real applications frequently use ordinary Python, REST clients, SQL queries, custom retrieval algorithms, and third-party SDKs.

These operations require additional instrumentation when their internal behavior matters.

Use the traceable decorator

The following standalone pipeline demonstrates tracing without importing LangGraph or LangChain.

Python
import asyncio
import time

from langsmith import Client, traceable

client = Client()

@traceable(name="load_inventory", run_type="tool", client=client)
def load_inventory() -> list[dict]:
    time.sleep(0.1)

    return [
        {"product": "Keyboard", "stock": 8},
        {"product": "Monitor", "stock": 2},
    ]

@traceable(name="check_stock", client=client)
def check_stock(products: list[dict]) -> list[str]:
    return [
        item["product"]
        for item in products
        if item["stock"] < 5
    ]

@traceable(name="inventory_pipeline", client=client)
def inventory_pipeline() -> dict:
    products = load_inventory()
    low_stock = check_stock(products)

    return {"reorder": low_stock}

async def main():
    try:
        result = inventory_pipeline()
        print(result)
    finally:
        await client.flush()

if __name__ == "__main__":
    asyncio.run(main())

Expected output:

Text
{'reorder': ['Monitor']}

The resulting trace contains an inventory_pipeline root and two nested child operations.

LangSmith also provides the trace context manager for instrumenting specific code blocks and provider wrappers such as wrap_openai for direct OpenAI SDK calls.

Marking a function as run_type="llm" does not guarantee token accounting. Supported response formats or explicit usage instrumentation are still necessary.

For distributed applications, propagate trace context across service boundaries. Otherwise, remotely executed operations may appear as unrelated traces.

Privacy

Tracing creates an additional data destination for application information. Depending on instrumentation, traces may contain prompts, user messages, retrieved documents, tool arguments, outputs, metadata, and exception details.

Production observability must therefore enforce data minimization.

Hide sensitive inputs and outputs

For applications requiring content-free operational telemetry, configure:

Terminal
export LANGSMITH_HIDE_INPUTS="true"
export LANGSMITH_HIDE_OUTPUTS="true"

Metadata can also be hidden when required.

Terminal
export LANGSMITH_HIDE_METADATA="true"

These controls suppress the corresponding trace fields, but other information, including names and exception details, still requires review.

Disable tracing selectively

Some requests must not be traced at all.

The following example demonstrates request-scoped tracing control.

Python
from langsmith import tracing_context, traceable

@traceable(name="calculate_total")
def calculate_total(amount: float, tax: float) -> float:
    return round(amount * (1 + tax), 2)

with tracing_context(enabled=False):
    result = calculate_total(100.0, 0.18)

print(result)

Expected output:

Text
118.0

The calculation executes normally without submitting its decorated operation as a trace.

This is useful when a tenant’s privacy policy prohibits tracing or when a request contains restricted information.

Apply production safeguards

Use approved metadata fields, mask sensitive content before transmission, and avoid recording raw credentials or personal identifiers. Configure workspace permissions, retention periods, regional requirements, and trace sampling according to organizational policy.

For high-volume applications, LANGSMITH_TRACING_SAMPLING_RATE can reduce telemetry volume. A rate of 0.1 targets approximately ten percent of traces; account for sampling when interpreting aggregate counts and spend.

Tip: Trace sampling controls observability volume, not model execution cost. Privacy-sensitive requests must be excluded or sanitized deliberately rather than relying on random sampling.

Consult the sensitive data documentation for selective masking and client-level privacy configuration.

In the next lesson, Debugging state transitions in LangSmith Studio, you will move from observing completed execution traces to interactively investigating graph state, routing decisions, and unexpected transitions.

These capabilities form the observability foundation for this chapter’s multi-agent application project, where execution traces will support systematic debugging, evaluation, and regression testing.

Exercise

Instrument a Customer Support Graph

Build a customer support graph with a classification node, a knowledge lookup node, and a response generation node. Enable LangSmith tracing, attach release metadata and descriptive tags, and instrument the knowledge lookup using the traceable decorator. Execute two different requests and compare their node latency, token consumption, and estimated costs in LangSmith.

Python
# Install:
# pip install -U "langgraph>=1,<2" "langchain>=1,<2" langchain-openai "langsmith>=0.14.12"
#
# Configure OPENAI_API_KEY, LANGSMITH_API_KEY,
# LANGSMITH_TRACING, LANGSMITH_AGENT_ID and
# LANGSMITH_AGENT_ENVIRONMENT before running.

from typing import TypedDict
from langchain.chat_models import init_chat_model
from langchain.messages import HumanMessage, SystemMessage
from langgraph.graph import StateGraph, START, END
from langsmith import traceable, uuid7
from langchain_core.tracers.langchain import wait_for_all_tracers

model = init_chat_model("openai:gpt-5.4-mini")

class State(TypedDict, total=False):
    question: str
    category: str
    knowledge: str
    answer: str

KNOWLEDGE = {
    "billing": "Invoices are available in account settings.",
    "technical": "Restart the application and check connectivity.",
    "general": "Contact customer support for further assistance.",
}

def classify(state: State) -> dict:
    # TODO: Classify the question using the model.
    raise NotImplementedError

# TODO: Add a traceable decorator.
def lookup_knowledge(category: str) -> str:
    return KNOWLEDGE.get(category, KNOWLEDGE["general"])

def retrieve(state: State) -> dict:
    # TODO: Retrieve the relevant knowledge.
    raise NotImplementedError

def respond(state: State) -> dict:
    # TODO: Generate a grounded support response.
    raise NotImplementedError

builder = StateGraph(State)

# TODO: Register the nodes and connect the edges.

# TODO: Compile the graph.

# TODO: Invoke the graph twice with descriptive run names,
# tags, release metadata, unique run IDs and a recursion limit.

# TODO: Ensure pending LangChain traces are submitted.

Summary

  • LangSmith captures hierarchical execution traces that reveal the behavior of graphs, nodes, models, tools, and custom functions.
  • LangGraph and LangChain automatically produce tracing telemetry when the correct LangSmith environment is configured.
  • Stable run names, descriptive tags, and structured metadata make production traces searchable and comparable.
  • Individual node traces reveal slow dependencies, repeated model calls, failures, and inefficient execution paths.
  • Token consumption, percentile latency, and estimated cost are essential metrics for monitoring production agent performance.
  • The traceable decorator extends observability to ordinary Python functions and external integrations.
  • Production tracing requires deliberate privacy controls, access restrictions, retention policies, and appropriate sampling.