Debugging state transitions in LangSmith Studio

Topic 2 of 4 in Observability & evaluation28 min readAdvancedFree course

Overview

In the previous lesson, Tracing and monitoring with LangSmith, you learned how to observe agent execution through traces, inspect individual operations, and investigate token consumption, latency, and cost.

However, observing an execution is not the same as debugging it.

Imagine a customer support agent that retrieves an order, evaluates refund eligibility, and delegates the request to a specialist. The final response incorrectly states that the customer requires manual approval.

A trace might reveal that the manual review node executed successfully. But that does not explain why the graph selected that node in the first place.

You need answers to more specific questions:

  • What information did the eligibility node receive?
  • Which state fields did it modify?
  • Why did the conditional edge select manual review?
  • Can you correct the intermediate state and investigate the resulting execution?
  • Can you reproduce the problem without repeating expensive model calls?

This is where LangSmith Studio becomes valuable.

LangSmith Studio is an interactive development environment for agentic applications. It connects to an Agent Server and allows developers to visualize graph architecture, execute workflows, investigate intermediate state, configure breakpoints, and explore alternative execution paths.

Unlike conventional debugging, which primarily focuses on variables and individual lines of code, Studio focuses on the execution boundaries of agent workflows.

Understanding state transitions

A state transition occurs when a graph node produces an update that changes the shared graph state.

Conceptually, every transition involves four operations:

  1. A scheduled node receives the current state.
  2. The node executes its business logic.
  3. LangGraph applies the returned updates using the appropriate state reducers.
  4. The graph determines which nodes should execute next.

Consider this execution:

Text
Initial state:
{"amount_cents": 7500}

Eligibility node update:
{"eligible": false}

Resulting state:
{"amount_cents": 7500, "eligible": false}

Next node:
manual_review

The manual review node may be functioning perfectly. The actual defect could be the incorrect eligible value produced earlier.

The following diagram illustrates the relationship between node execution, state updates, and checkpointing.

Overview diagram: START to Execute node; Execute node to Apply state updates; Apply state updates to Checkpoint; Checkpoint to More work?; More work? to Execute node (Yes); More work? to END (No).

LangGraph saves checkpoints at super-step boundaries when checkpointing is enabled. A super-step may contain one sequential node or multiple nodes executing in parallel.

Consequently, checkpoints are not arbitrary Python instruction boundaries. Studio cannot rewind execution to an individual statement inside a node unless that statement corresponds to a separately modeled execution boundary.

LangSmith tracing versus Studio

Capability LangSmith tracing LangSmith Studio
Inspect historical executions Yes Yes
Examine model and tool operations Yes Yes
Analyze latency and token usage Primary use case Through trace integrations
Visualize graph architecture Execution-oriented Interactive graph view
Pause graph execution Not its primary function Yes
Modify historical graph state Not directly through traces Yes
Replay from checkpoints Requires execution infrastructure Interactive
Investigate alternative branches Compare recorded executions Fork and execute

These capabilities complement each other. Tracing identifies suspicious executions; Studio helps investigate their causes.

See the official LangSmith Studio documentation for the supported development features.

Start a local server

Studio communicates with your application through the LangSmith Agent Server API. For local development, LangGraph provides the langgraph dev command.

The local server runs your Python graph, exposes its execution endpoints, manages development checkpointing, and supports automatic reloading when source files change.

Docker is not required.

Step 1: Install the dependencies

Create a project directory using Python 3.11 or newer.

Terminal
mkdir studio-debugging
cd studio-debugging

python -m venv .venv
source .venv/bin/activate

python -m pip install -U pip
pip install "langgraph>=1,<2" "langchain>=1,<2" "langgraph-cli[inmem]"

On Windows PowerShell, activate the virtual environment with:

POWERSHELL
.venv\Scripts\Activate.ps1

The inmem extra installs the dependencies required by the lightweight development server.

Step 2: Create the project structure

Create the following files:

Text
studio-debugging/
├── .env
├── .gitignore
├── requirements.txt
├── langgraph.json
└── graph.py

In requirements.txt, specify the application dependencies:

Text
langgraph>=1,<2
langchain>=1,<2

Configure .env with your LangSmith credentials:

DOTENV
LANGSMITH_API_KEY=your_langsmith_api_key
LANGSMITH_TRACING=true
LANGSMITH_PROJECT=studio-debugging

Obtain your API key from LangSmith.

Protect credentials and development data by adding the following entries to .gitignore:

Text
.env
.venv/
.langgraph_api/
__pycache__/

This lesson deliberately uses deterministic business logic instead of an LLM. You can therefore investigate routing errors without introducing model variability, token costs, or an additional model-provider API key.

Step 3: Build a deliberately faulty graph

Our application processes refund requests. The intended business rule allows automatic approval for amounts up to $100.

However, the eligibility node incorrectly compares an amount expressed in cents against a threshold expressed in dollars.

The graph below represents the refund workflow.

Start a local server diagram: START to Fetch order; Fetch order to Assess eligibility; Assess eligibility to Dispatch request; Dispatch request to Eligible?; Eligible? to Auto approve (Yes); Eligible? to Manual review (No); Auto approve to END; Manual review to END.

Save this complete graph definition in graph.py.

Python
from typing import TypedDict, Literal
from langgraph.graph import StateGraph, START, END

class RefundInput(TypedDict):
    order_id: str

class RefundState(RefundInput, total=False):
    amount_cents: int
    eligible: bool
    reason: str
    destination: str
    result: str

ORDERS = {
    "ORD-101": 7500,
    "ORD-102": 15000,
    "ORD-103": 5000,
}

def fetch_order(state: RefundState):
    return {
        "amount_cents": ORDERS[state["order_id"]]
    }

def assess_eligibility(state: RefundState):
    # Intentional bug: comparing cents against dollars.
    eligible = state["amount_cents"] <= 100

    return {
        "eligible": eligible,
        "reason": (
            "Within refund limit"
            if eligible
            else "Exceeds refund limit"
        )
    }

def dispatch_request(state: RefundState):
    return {
        "destination": (
            "approve" if state["eligible"] else "review"
        )
    }

def route(
    state: RefundState
) -> Literal["approve", "review"]:
    return (
        "approve"
        if state["destination"] == "approve"
        else "review"
    )

def approve(state: RefundState):
    return {"result": "Refund automatically approved"}

def review(state: RefundState):
    return {"result": "Manual review required"}

def build_graph():
    builder = StateGraph(
        RefundState,
        input_schema=RefundInput
    )

    builder.add_node("fetch_order", fetch_order)
    builder.add_node(
        "assess_eligibility", assess_eligibility
    )
    builder.add_node(
        "dispatch_request", dispatch_request
    )
    builder.add_node("approve", approve)
    builder.add_node("review", review)

    builder.add_edge(START, "fetch_order")
    builder.add_edge(
        "fetch_order", "assess_eligibility"
    )
    builder.add_edge(
        "assess_eligibility", "dispatch_request"
    )

    builder.add_conditional_edges(
        "dispatch_request",
        route,
        {
            "approve": "approve",
            "review": "review"
        }
    )

    builder.add_edge("approve", END)
    builder.add_edge("review", END)

    return builder

graph = build_graph().compile()

if __name__ == "__main__":
    print(graph.invoke({"order_id": "ORD-101"}))

Run the graph independently:

Terminal
python graph.py

Expected output:

Text
{
    'order_id': 'ORD-101',
    'amount_cents': 7500,
    'eligible': False,
    'reason': 'Exceeds refund limit',
    'destination': 'review',
    'result': 'Manual review required'
}

The output is incorrect because 7,500 cents represents $75, which is within the $100 refund limit.

The separate input schema ensures that application callers normally supply an order identifier rather than internal eligibility decisions.

Step 4: Configure the Agent Server

Create langgraph.json:

JSON
{
  "dependencies": ["."],
  "graphs": {
    "refund_agent": "./graph.py:graph"
  },
  "env": "./.env"
}

The configuration has three important properties:

Property Purpose
dependencies Identifies the application dependencies
graphs Registers graph identifiers and their Python definitions
env Loads environment variables from the specified file

The value ./graph.py:graph instructs Agent Server to load the compiled object named graph from graph.py.

Notice that the exported graph does not explicitly configure a checkpointer. Agent Server supplies persistence infrastructure automatically. Standalone Python examples later in this lesson configure their own checkpointer.

Step 5: Launch the server

From the project directory, execute:

Terminal
langgraph dev

The terminal should display endpoints similar to these:

Text
API: http://127.0.0.1:2024
Docs: http://127.0.0.1:2024/docs
Studio Web UI:
https://smith.langchain.com/studio/?baseUrl=http://127.0.0.1:2024

Open the Studio URL printed by the server.

If the browser does not open automatically, navigate directly to:

Open LangSmith Studio for the local server

Keep the terminal running while using Studio.

Note: The examples use documented LangGraph 1.x APIs and expected outputs. Live execution against Studio was not verified for this lesson. Interface labels may vary between Studio releases.

Development server versus production-like server

LangGraph provides two useful local execution environments.

Feature langgraph dev langgraph up
Docker required No Yes
Primary purpose Development and debugging Production-like validation
Default port 2024 8123
Persistence Lightweight local storage PostgreSQL-backed
Automatic reload Enabled by default Available with watch option
Resource requirements Lower Higher

Use langgraph dev for everyday debugging and langgraph up when validating infrastructure-dependent behavior.

For browser connection problems, verify that the API documentation endpoint is reachable. Safari may require langgraph dev --tunnel and additional allowed-origin configuration. Consult the official Studio setup guide and local development documentation.

What you can do in Studio

Visualize graph architecture

Studio displays the nodes and edges of your registered application.

For complex agentic systems, this helps identify unexpected connections, conditional branches, supervisor routing, cycles, and termination paths.

The architecture describes possible execution paths. The thread history shows which paths were actually taken.

Do not confuse an edge appearing in the graph visualization with evidence that the corresponding transition executed.

Execute workflows interactively

Select the refund_agent graph and use Graph mode.

Studio supports two principal modes:

  • Graph mode: Detailed execution inspection, intermediate state, and debugging controls.
  • Chat mode: Conversational interaction for compatible message-based graphs using MessagesState or an equivalent supported messages schema.

Graph mode is appropriate for our refund workflow.

In the input section, switch to the raw JSON editor if necessary and enter:

JSON
{
  "order_id": "ORD-101"
}

Submit the input to execute the application.

Studio displays the execution history as the graph progresses. The expected path for the faulty implementation is:

Text
fetch_order
    → assess_eligibility
    → dispatch_request
    → review

Inspect node inputs and outputs

Expand individual nodes in the execution history.

Investigate both the information available before execution and the updates produced by the node.

For the refund example, the important transitions are:

Node State update Observation
fetch_order amount_cents = 7500 Correct
assess_eligibility eligible = False Incorrect
dispatch_request destination = review Consistent with incoming state
review Manual review result Correct execution of an incorrect decision

A downstream node can behave correctly while contributing to an incorrect final outcome.

Always investigate the earliest incorrect state transition rather than immediately rewriting the final node.

Configure breakpoints

Studio allows you to configure graph execution breakpoints.

Using the run controls:

  1. Select Interrupt.
  2. Choose dispatch_request.
  3. Configure execution to pause before that node.
  4. Submit a new run.
  5. Inspect the current state.
  6. Select Continue to resume execution.

At the breakpoint, order retrieval and eligibility assessment have completed, but dispatch has not.

You should observe:

JSON
{
  "order_id": "ORD-101",
  "amount_cents": 7500,
  "eligible": false,
  "reason": "Exceeds refund limit"
}

This makes it possible to investigate a decision before downstream execution occurs.

A Studio breakpoint is not identical to a business-level interrupt() call. Breakpoints support debugging, whereas dynamic interrupts implement application-controlled human interaction.

Inspect and manage threads

A thread represents persisted execution state across one or more runs.

The important identifiers are:

  • Thread ID: Identifies the persisted execution context.
  • Run ID: Identifies an individual execution request on Agent Server.
  • Checkpoint ID: Identifies a historical state checkpoint.

Select an existing thread to investigate previous executions, or create a new thread to isolate an experiment.

Reusing a thread can retain state from earlier runs. For independent debugging experiments, prefer fresh threads.

The detailed controls for execution, breakpoints, and thread management are documented in How to use Studio.

A debugging workflow

Effective debugging is a controlled investigation rather than a sequence of random state modifications.

Step 1: Establish the expected behavior

Before inspecting the execution, define the business invariant.

For our application:

Text
Refund amount <= 10,000 cents:
    Automatically approve.

Refund amount > 10,000 cents:
    Require manual review.

This gives you an objective standard against which to compare the observed state.

Without an expected invariant, it is difficult to distinguish an application defect from an unexpected but valid execution path.

Step 2: Reproduce the failure

Create a fresh Studio thread and submit ORD-101.

Record the following debugging information:

  • Graph identifier.
  • Thread and run identifiers.
  • Original input.
  • Expected outcome.
  • Actual outcome.
  • Relevant checkpoint identifiers.
  • Application version.

For an LLM-based system, also record model configuration, prompt version, tool responses, and relevant runtime context.

This makes the investigation reproducible by other engineers.

Step 3: Locate the first incorrect transition

Expand the execution history chronologically.

The order lookup correctly retrieves 7,500 cents. Eligibility assessment incorrectly changes eligible to False.

This is the earliest divergence from the expected behavior.

The root cause is therefore likely within the assessment logic, not the dispatcher or manual review node.

Step 4: Edit historical state and fork

In Studio, locate the completed assess_eligibility node.

Select Edit node state and change its output to:

JSON
{
  "eligible": true,
  "reason": "Within refund limit"
}

Confirm the edit using Fork. Allow the forked execution to continue.

The alternative execution should follow:

Text
dispatch_request
    → approve

Expected result:

Text
Refund automatically approved

Forking validates the hypothesis that incorrect eligibility state caused the routing problem.

The original execution remains available for comparison.

Step 5: Understand replay versus fork

LangGraph’s time-travel functionality supports two related debugging operations.

Behavior Replay Fork
Starting point Historical checkpoint Historical checkpoint
Modify state before execution No Yes
Re-execute downstream nodes Yes Yes
Preserve original history Yes Yes
Typical purpose Reproduce behavior Test alternative state

Studio exposes replay through Re-run from here, while editing historical node output creates a modified execution branch.

The replay starting point matters. To investigate a faulty assessment function, replay from the checkpoint before assessment. Replaying from a checkpoint after assessment retains its saved output.

Tip: Time travel does not reverse external side effects. Replayed nodes may repeat API calls, database writes, payments, emails, or other operations. Use sandbox services, dry-run modes, and idempotency keys during debugging.

Step 6: Correct the implementation

Editing historical state proves a hypothesis, but it does not repair the application.

Replace the faulty comparison in graph.py:

Python
eligible = state["amount_cents"] <= 100

With:

Python
eligible = state["amount_cents"] <= 10_000

The development server should reload the updated code.

Create fresh threads and verify:

Order Amount Expected result
ORD-101 $75 Automatic approval
ORD-102 $150 Manual review
ORD-103 $50 Automatic approval

Also test the boundary values of 9,999, 10,000, and 10,001 cents using additional fixtures.

A corrected historical execution is insufficient evidence that the source-code fix works for future requests.

Step 7: Correlate state with traces

After repairing the routing logic, inspect the corresponding LangSmith traces.

In a real multi-agent application, incorrect routing might produce unnecessary specialist calls, additional model invocations, or repeated tool execution.

Use traces to investigate whether the corrected path also eliminates unnecessary latency and cost.

Studio answers why the graph selected a path. Tracing helps quantify the operational consequences of that path.

Debugging state transitions without Studio

Production investigations and automated debugging utilities cannot always rely on a graphical interface.

LangGraph exposes Python APIs that support the same fundamental debugging operations.

Inspect checkpoint history

The following example imports our graph builder and attaches an explicit checkpointer for standalone execution.

Keep the intentional bug in graph.py while running the historical debugging demonstrations below.

Save this as inspect_history.py:

Python
from langgraph.checkpoint.memory import InMemorySaver
from graph import build_graph

graph = build_graph().compile(
    checkpointer=InMemorySaver()
)

config = {
    "configurable": {
        "thread_id": "refund-history"
    }
}

graph.invoke(
    {"order_id": "ORD-101"},
    config
)

latest = graph.get_state(config)

print("Final state:", latest.values)
print("Pending nodes:", latest.next)

history = list(graph.get_state_history(config))

for snapshot in reversed(history):
    print(
        "Step:", snapshot.metadata.get("step"),
        "| Next:", snapshot.next,
        "| State:", snapshot.values
    )

Run it:

Terminal
python inspect_history.py

The output includes transitions similar to:

Text
Next: ('fetch_order',)
State: {'order_id': 'ORD-101'}

Next: ('assess_eligibility',)
State: {'order_id': 'ORD-101', 'amount_cents': 7500}

Next: ('dispatch_request',)
State: {..., 'eligible': False, 'reason': 'Exceeds refund limit'}

Next: ('review',)
State: {..., 'destination': 'review'}

Next: ()
State: {..., 'result': 'Manual review required'}

The ellipses represent previously accumulated state fields. Actual output includes complete state dictionaries and initialization checkpoints.

get_state_history() normally returns checkpoints in reverse chronological order. Reversing the collected history makes it easier to follow execution forward.

Understand StateSnapshot

The object returned by get_state() is a StateSnapshot.

Attribute Meaning
values State values at the checkpoint
next Nodes scheduled to execute next
config Configuration identifying the checkpoint
metadata Execution metadata, including step information
created_at Checkpoint creation timestamp
parent_config Configuration identifying its parent checkpoint
tasks Task information, including available errors and interrupts

An empty next tuple normally indicates that no additional graph nodes are scheduled.

Inspect tasks and associated interrupt or error information before assuming that a workflow has completed successfully.

Replay and fork programmatically

This complete example reproduces the faulty execution, replays it, and creates an alternative branch with corrected eligibility state.

Save it as time_travel.py:

Python
from langgraph.checkpoint.memory import InMemorySaver
from graph import build_graph

graph = build_graph().compile(
    checkpointer=InMemorySaver()
)

config = {
    "configurable": {
        "thread_id": "refund-time-travel"
    },
    "recursion_limit": 30
}

original = graph.invoke(
    {"order_id": "ORD-101"},
    config
)

history = list(graph.get_state_history(config))

before_assessment = next(
    snapshot
    for snapshot in history
    if snapshot.next == ("assess_eligibility",)
)

before_dispatch = next(
    snapshot
    for snapshot in history
    if snapshot.next == ("dispatch_request",)
)

replayed = graph.invoke(
    None,
    before_assessment.config
)

fork_config = graph.update_state(
    before_dispatch.config,
    values={
        "eligible": True,
        "reason": "Within refund limit"
    },
    as_node="assess_eligibility"
)

corrected = graph.invoke(None, fork_config)

print("Original:", original["result"])
print("Replay:", replayed["result"])
print("Fork:", corrected["result"])

assert graph.get_state(
    before_dispatch.config
).values["eligible"] is False

Expected output:

Text
Original: Manual review required
Replay: Manual review required
Fork: Refund automatically approved

The as_node argument attributes the artificial update to assess_eligibility, affecting downstream scheduling.

update_state() creates a new checkpoint rather than mutating the original. Its updates also pass through state reducers.

For additive list reducers, an edit may append elements instead of replacing them. For message histories using add_messages, matching message IDs enable replacement, while explicit message removal requires RemoveMessage.

See the official time-travel guide and checkpoint documentation.

Debug live execution using streaming

Streaming provides immediate visibility into state updates without inspecting completed checkpoint history.

This example uses the v2 streaming format.

Python
from langgraph.checkpoint.memory import InMemorySaver
from graph import build_graph

graph = build_graph().compile(
    checkpointer=InMemorySaver()
)

config = {
    "configurable": {
        "thread_id": "refund-stream"
    },
    "recursion_limit": 30
}

for chunk in graph.stream(
    {"order_id": "ORD-101"},
    config,
    stream_mode=["updates", "values"],
    version="v2"
):
    if chunk["type"] == "updates":
        print("Node update:", chunk["data"])

    elif chunk["type"] == "values":
        print("Current state:", chunk["data"])

Expected node updates include:

Text
Node update: {'fetch_order': {'amount_cents': 7500}}

Node update: {'assess_eligibility': {
    'eligible': False,
    'reason': 'Exceeds refund limit'
}}

Node update: {'dispatch_request': {
    'destination': 'review'
}}

Node update: {'review': {
    'result': 'Manual review required'
}}

The updates mode exposes node-produced changes, while values exposes accumulated state. Other available modes support model messages, custom events, and more detailed debugging information.

Refer to the LangGraph streaming documentation for event formats.

Configure programmatic breakpoints

Static breakpoints allow developers to reproduce Studio-style pauses directly from Python.

The following example pauses execution before dispatch.

Python
from langgraph.checkpoint.memory import InMemorySaver
from graph import build_graph

graph = build_graph().compile(
    checkpointer=InMemorySaver(),
    interrupt_before=["dispatch_request"]
)

config = {
    "configurable": {
        "thread_id": "refund-breakpoint"
    }
}

graph.invoke({"order_id": "ORD-101"}, config)

snapshot = graph.get_state(config)

print("Paused state:", snapshot.values)
print("Next node:", snapshot.next)

assert snapshot.next == ("dispatch_request",)

result = graph.invoke(None, config)

print("Completed:", result["result"])

Expected output:

Text
Next node: ('dispatch_request',)
Completed: Manual review required

For this static breakpoint, invoke(None, config) resumes execution.

A dynamic interrupt created with interrupt(payload) instead requires Command(resume=value). On resumption, the interrupted node restarts from its beginning, so operations preceding the interrupt must be safe to repeat.

Common debugging mistakes

Mistake Correct approach
Investigating only final responses Inspect every important state transition
Reusing contaminated threads Start independent experiments with fresh thread IDs
Replaying a terminal checkpoint Select a checkpoint with pending execution
Assuming state edits bypass reducers Account for reducer behavior
Editing derived fields independently Maintain consistency between related fields
Replaying production side effects Use isolated services and idempotent operations
Treating checkpoint edits as permanent fixes Correct and validate source code
Assuming replay is deterministic Control model configuration and external dependencies

In parallel graphs, multiple nodes can execute during a single super-step. Conflicting writes to a state field without an appropriate reducer can cause concurrent update errors.

When diagnosing these failures, examine the participating tasks and their individual outputs rather than assuming that streamed event order represents sequential execution.

Production debugging best practices

For production-grade agentic applications, design workflows to be debuggable from the beginning.

Use descriptive node names such as validate_customer, retrieve_policy, and select_specialist. Avoid names that obscure responsibilities.

Keep node responsibilities narrow. Smaller nodes create clearer checkpoint boundaries and reduce the amount of work that must be repeated during replay.

Represent important routing decisions explicitly in state, including structured reason codes when appropriate. Record observable decision evidence rather than private model reasoning.

Use persistent checkpoint storage when debugging must survive process restarts. For standalone applications, SQLite can support local investigations, while PostgreSQL is suitable for production persistence. Agent Server manages its checkpoint infrastructure separately.

Choose durability settings deliberately. For investigations requiring checkpoints to be committed before subsequent execution, durability="sync" provides stronger guarantees at the cost of additional latency.

Remember that replaying graph checkpoints does not automatically restore previous runtime context, external databases, long-term stores, tool results outside state, or application versions.

Finally, restrict access to debugging environments. Checkpoints and traces may contain customer information, internal prompts, and sensitive business data. State editing is a privileged operation, not an ordinary end-user capability.

Connecting debugging to agent evaluation

Debugging explains why a specific execution failed. Evaluation determines whether the application behaves correctly across many executions.

A reproducible failure discovered in Studio is an excellent candidate for an evaluation dataset.

For example, the refund-routing incident can become a dataset record containing:

JSON
{
  "inputs": {
    "order_id": "ORD-101"
  },
  "expected_outputs": {
    "eligible": true,
    "destination": "approve",
    "result": "Refund automatically approved"
  }
}

For the chapter’s multi-agent hands-on project, preserve examples of incorrect supervisor decisions, failed specialist handoffs, invalid tool selections, and inconsistent state updates.

These examples provide concrete evidence for evaluating improvements to the application.

In the next lesson, Evaluating agents — datasets, LLM-as-a-judge and trajectories, you will extend this debugging workflow into systematic evaluation, measuring not only whether an agent produces an acceptable final answer, but also whether it follows an appropriate execution trajectory.

Exercise

Debug and Fork a Risk Assessment Graph

Build a risk assessment workflow that incorrectly routes a customer with a risk score of 20 to manual review. Inspect its checkpoint history to identify the incorrect classification. Fork execution by correcting the classification in a historical checkpoint, resume the graph, and verify that the original checkpoint remains unchanged.

Python
from typing import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.memory import InMemorySaver

class State(TypedDict, total=False):
    risk_score: int
    high_risk: bool
    result: str

def classify(state: State):
    # Intentional bug
    return {"high_risk": state["risk_score"] < 70}

def route(state: State):
    return "review" if state["high_risk"] else "approve"

def review(state: State):
    return {"result": "Manual review required"}

def approve(state: State):
    return {"result": "Approved"}

builder = StateGraph(State)
builder.add_node("classify", classify)
builder.add_node("review", review)
builder.add_node("approve", approve)

builder.add_edge(START, "classify")
builder.add_conditional_edges(
    "classify",
    route,
    {"review": "review", "approve": "approve"}
)
builder.add_edge("review", END)
builder.add_edge("approve", END)

graph = builder.compile(checkpointer=InMemorySaver())
config = {"configurable": {"thread_id": "risk-debug"}}

original = graph.invoke({"risk_score": 20}, config)
print("Original:", original)

# TODO: Retrieve checkpoint history.
# TODO: Find the checkpoint before review.
# TODO: Fork the checkpoint with high_risk=False.
# TODO: Resume execution using the fork configuration.
# TODO: Verify that the original checkpoint is unchanged.

Summary

  • LangSmith Studio provides an interactive environment for inspecting and debugging LangGraph applications at the graph and state levels.
  • The langgraph dev command launches a lightweight local Agent Server that connects to Studio without requiring Docker.
  • Checkpoints preserve graph state at super-step boundaries and enable historical inspection, replay, and alternative execution paths.
  • Studio breakpoints allow developers to pause execution before or after selected nodes and investigate intermediate state.
  • Replay re-executes downstream work from a historical checkpoint, whereas forking introduces modified state before continuing execution.
  • The get_state, get_state_history, and update_state APIs provide programmatic alternatives to visual debugging.
  • Editing a checkpoint helps validate a debugging hypothesis but does not replace correcting the underlying application code.