---
title: "LangGraph (tracing)"
description: "Trace LangGraph stateful agent workflows with Respan: callback spans, gateway routing, and full observability."
---

[LangGraph](https://langchain-ai.github.io/langgraph/) is a framework for building stateful, multi-step agent workflows as graphs. Nodes represent operations such as LLM calls, tools, and routing decisions, while edges define the flow between them. Respan gives you full observability over every graph run, node, tool call, and LLM generation, plus gateway routing through the OpenAI-compatible Respan endpoint.

<Accordion title="Set up Respan">
Create an account at [platform.respan.ai](https://platform.respan.ai) and grab an [API key](https://platform.respan.ai/platform/gateway/api-keys).
</Accordion>

Paste this into your coding agent:

```text
Help me set up Respan tracing with the LangGraph integration.
Follow https://www.respan.ai/docs/integrations/langgraph.md
```

## Setup

<Steps>
<Step title="Install packages">

<Tabs>
<Tab title={"Python"}>

```bash
pip install respan-ai respan-instrumentation-langchain langgraph langchain-openai python-dotenv
```

</Tab>
<Tab title={"TypeScript"}>

```bash
npm install @respan/respan @respan/instrumentation-langchain @langchain/langgraph zod
```

</Tab>
</Tabs>

</Step>

<Step title="Set environment variables">

```bash
export RESPAN_API_KEY="YOUR_RESPAN_API_KEY"
export RESPAN_BASE_URL="https://api.respan.ai/api"
```

`RESPAN_API_KEY` is used to export traces to Respan. Set `OPENAI_API_KEY` too when graph nodes call provider-backed models.

</Step>

<Step title="Initialize and run">

LangGraph runs through LangChain callback managers, so use `respan-instrumentation-langchain` and pass `LangChainInstrumentor()` to `Respan(instrumentations=[...])`.

<Note>
**Python**: the instrumentor patches the LangChain and LangGraph callback managers on init, so the compiled graph, every node, and their nested LLM and tool calls are traced **automatically**. No per-call setup.

**TypeScript**: the instrumentor does not patch globally. Attach `langgraph.addCallback(...)` at the compiled graph's top-level `app.invoke()` (or `app.stream()`), not inside a node; LangGraph propagates it to every node. Attaching it only inside a single node yields just that node's spans.
</Note>

<Tabs>
<Tab title={"Python"}>

```python
from typing import TypedDict

from langgraph.graph import StateGraph, START, END
from respan import Respan
from respan_instrumentation_langchain import LangChainInstrumentor

# Activates global LangChain/LangGraph instrumentation. Graph and node runs are traced automatically.
respan = Respan(instrumentations=[LangChainInstrumentor()])

class State(TypedDict):
    topic: str
    joke: str

def generate_joke(state: State) -> dict:
    return {"joke": f"A short joke about {state['topic']}"}

graph = StateGraph(State)
graph.add_node("generate", generate_joke)
graph.add_edge(START, "generate")
graph.add_edge("generate", END)

app = graph.compile()
result = app.invoke({"topic": "AI tracing"})
print(result)
```

</Tab>
<Tab title={"TypeScript"}>

```typescript
import { END, START, StateGraph, StateSchema } from "@langchain/langgraph";
import { Respan } from "@respan/respan";
import { LangChainInstrumentor } from "@respan/instrumentation-langchain";
import { z } from "zod";

const langgraph = new LangChainInstrumentor();
const respan = new Respan({
  apiKey: process.env.RESPAN_API_KEY,
  baseURL: process.env.RESPAN_BASE_URL,
  instrumentations: [langgraph],
});
await respan.initialize();

const State = new StateSchema({
  topic: z.string(),
  joke: z.string().default(""),
});

const graph = new StateGraph(State)
  .addNode("generate", (state: typeof State.State) => {
    return { joke: `A short joke about ${state.topic}` };
  })
  .addEdge(START, "generate")
  .addEdge("generate", END)
  .compile();

const result = await graph.invoke(
  { topic: "AI tracing" },
  langgraph.addCallback({
    runName: "joke_graph",
    tags: ["langgraph", "quickstart"],
    metadata: { framework: "langgraph" },
  })
);
console.log(result);
```

</Tab>
</Tabs>

</Step>

<Step title="View your trace">

Open the [Traces page](https://platform.respan.ai/platform/traces) to see the graph execution with node spans, LLM calls, and state transitions.

</Step>
</Steps>

## Configuration

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `api_key` | `str \| None` | `None` | Falls back to `RESPAN_API_KEY` env var. |
| `base_url` | `str \| None` | `None` | Falls back to `RESPAN_BASE_URL` env var. |
| `instrumentations` | `list` | `[]` | Plugin instrumentations to activate, e.g. `LangChainInstrumentor()`. |
| `include_content` | `bool` | `True` | Includes graph inputs, node inputs, and outputs on spans. |
| `include_metadata` | `bool` | `True` | Includes LangGraph tags, metadata, and serialized runnable details. |
| `customer_identifier` | `str \| None` | `None` | Default customer identifier for all spans. |
| `metadata` | `dict \| None` | `None` | Default metadata attached to all spans. |
| `environment` | `str \| None` | `None` | Environment tag, e.g. `"production"`. |

## Attributes

### In Respan()

Set defaults at initialization. These apply to all spans.

<Tabs>
<Tab title={"Python"}>

```python
from respan import Respan
from respan_instrumentation_langchain import LangChainInstrumentor

respan = Respan(
    instrumentations=[LangChainInstrumentor()],
    customer_identifier="user_123",
    metadata={"service": "graph-api", "version": "1.0.0"},
)
```

</Tab>
<Tab title={"TypeScript"}>

```typescript
import { Respan } from "@respan/respan";
import { LangChainInstrumentor } from "@respan/instrumentation-langchain";

const respan = new Respan({
  instrumentations: [new LangChainInstrumentor()],
});
```

</Tab>
</Tabs>

### With propagate_attributes

Override per-request using a context scope.

<Tabs>
<Tab title={"Python"}>

```python
from respan import propagate_attributes
from respan_instrumentation_langchain import add_respan_callback

def handle_request(user_id: str, topic: str):
    with propagate_attributes(
        customer_identifier=user_id,
        session_identifier="conv_abc_123",
        metadata={"plan": "pro"},
    ):
        result = app.invoke(
            {"topic": topic},
            config=add_respan_callback({"run_name": "user_graph"}),
        )
        print(result)
```

</Tab>
<Tab title={"TypeScript"}>

```typescript
async function handleRequest(userId: string, topic: string) {
  await respan.propagateAttributes(
    {
      customer_identifier: userId,
      session_identifier: "conv_abc_123",
      metadata: { plan: "pro" },
    },
    async () => {
      const result = await graph.invoke(
        { topic },
        langgraph.addCallback({ runName: "user_graph" })
      );
      console.log(result);
    }
  );
}
```

</Tab>
</Tabs>

| Attribute | Type | Description |
|-----------|------|-------------|
| `customer_identifier` | `str` | Identifies the end user in Respan analytics. |
| `session_identifier` | `str` | Groups related messages into a conversation. |
| `metadata` | `dict` | Custom key-value pairs. Merged with default metadata. |

### Sessions

In TypeScript, when you don't set `session_identifier`, the `thread_id` in the run's config becomes the session id, so every turn of one conversation lands in one [session](/docs/documentation/features/custom-attributes#sessions). This needs `@respan/instrumentation-langchain` 1.2.0 or later.

```typescript
const result = await graph.invoke(
  { topic: "AI tracing" },
  langgraph.addCallback({ configurable: { thread_id: "chat_42" } })
);
```

## Decorators (optional)

Decorators are not required. Graph and node runs are traced automatically by the instrumentor in Python, and when you attach the Respan callback config to the graph invocation in TypeScript. Use `@workflow` and `@task` (Python) or `withWorkflow` and `withTask` (TypeScript) to group graph runs inside larger application workflows.

<Tabs>
<Tab title={"Python"}>

```python
from respan import workflow, task
from respan_instrumentation_langchain import add_respan_callback

@task(name="run_joke_graph")
def run_joke_graph(topic: str):
    return app.invoke(
        {"topic": topic},
        config=add_respan_callback({"run_name": "decorated_graph"}),
    )

@workflow(name="joke_pipeline")
def pipeline(topic: str):
    print(run_joke_graph(topic))

pipeline("AI tracing")
```

</Tab>
<Tab title={"TypeScript"}>

```typescript
await respan.withWorkflow({ name: "joke_pipeline" }, async () => {
  const result = await respan.withTask({ name: "run_joke_graph" }, async () => {
    return graph.invoke(
      { topic: "AI tracing" },
      langgraph.addCallback({ runName: "decorated_graph" })
    );
  });
  console.log(result);
});
```

</Tab>
</Tabs>

## Examples

### Streaming updates

Stream graph node updates while keeping the same trace.

```python
for update in app.stream(
    {"topic": "AI tracing"},
    config=add_respan_callback({"run_name": "streaming_graph"}),
    stream_mode="updates",
):
    print(update)
```

### Tool nodes

Tool calls inside graph nodes are captured as tool spans.

```python
from langchain_core.tools import tool
from langgraph.prebuilt import ToolNode

@tool
def search_docs(query: str) -> str:
    """Search docs."""
    return f"Results for {query}"

tools = ToolNode([search_docs])
```
