LangGraph 如何配合 LangChain 建立智能體並追蹤每個步驟
LangGraph agents with LangChain: build an agent and trace every one of its steps
文章示範如何用 LangGraph 和 LangChain 建立連接本地模型的智能體,並以 OpenTelemetry 追蹤每次執行中的節點、LLM 呼叫和 token 消耗。
Building LangGraph agents has become one of the most common ways to orchestrate LLMs in Python: you describe the steps of a reasoning process as a graph, with shared state, loops and tool calls. LangChain supplies the basic building blocks (models, prompts, tools, integrations), LangGraph the orchestration. Both projects are among the most-followed on GitHub in the AI agent ecosystem.
The trouble starts in production. An agent is not a function that returns an answer: it is a sequence of decisions, model calls and tool calls whose number varies from one run to the next. When an answer is wrong, slow or expensive, you need to know which step is responsible. Without traces, you are guessing.
In this article we build a small agent with LangGraph wired to a local model, then trace it with OpenTelemetry to see every node, every LLM call and every token consumed in a backend such as Dynatrace.
LangChain and LangGraph: who does what?
- LangChain standardises access to chat models (OpenAI, Anthropic, Mistral, Ollama, OpenAI-compatible servers…), tools, documents and vector stores. Integrations are published as separate packages, such as
langchain-openaiorlangchain-ollama. - LangGraph models an application as a state graph: nodes (functions) read and update a typed state, and edges, optionally conditional, decide what comes next. It also handles state persistence, interruption for human approval and streaming of the steps.
Ready-made functions create a ReAct-style agent (the model picks a tool, observes the result, starts again) in a single line. Their name and module have changed between versions: refer to the official LangChain and LangGraph documentation. The explicit graph, which we use here, remains the clearest way to understand what is going on.
In practice: a LangGraph agent on a local model
Step 1 — Install the packages
python3 -m venv .venv && source .venv/bin/activate
pip install langgraph langchain-openai
We use the OpenAI-compatible client so that we can target Ollama, vLLM or llama.cpp interchangeably. For Ollama, our guide Ollama locally describes the installation; its OpenAI-compatible API is served under /v1.
Step 2 — Describe the state and the nodes
The agent receives an incident symptom, draws up a diagnostic plan, then writes a short answer:
from typing import TypedDict
from langchain_openai import ChatOpenAI
from langgraph.graph import StateGraph, START, END
llm = ChatOpenAI(model="llama3.2",
base_url="http://localhost:11434/v1",
api_key="not-used")
class Etat(TypedDict):
symptome: str
plan: str
reponse: str
def planifier(etat: Etat) -> dict:
msg = llm.invoke(f"List 3 checks for: {etat['symptome']}")
return {"plan": msg.content}
def repondre(etat: Etat) -> dict:
msg = llm.invoke(f"Symptom: {etat['symptome']}\n"
f"Plan: {etat['plan']}\nSummarise in 5 lines.")
return {"reponse": msg.content}
Step 3 — Assemble and run the graph
graphe = StateGraph(Etat)
graphe.add_node("planifier", planifier)
graphe.add_node("repondre", repondre)
graphe.add_edge(START, "planifier")
graphe.add_edge("planifier", "repondre")
graphe.add_edge("repondre", END)
agent = graphe.compile()
for etape in agent.stream({"symptome": "p95 latency rising on the payment service"},
stream_mode="updates"):
print(etape)
The updates mode prints the state update produced by each node. It is a first form of observability, useful during development, but limited to the console.
Step 4 — Add tools
A real agent calls tools: a query to a monitoring API, reading a runbook, searching a document base. You bind the tools to the model and add a conditional edge that loops for as long as the model asks for a tool. That loop is precisely what makes the behaviour unpredictable, and therefore what you need to trace. Tools can also come from MCP servers, as explained in monitoring MCP agents with OpenTelemetry.
How do you trace LangGraph agents with OpenTelemetry?
There are two families of solutions. LangSmith, the platform from the company behind LangChain, is enabled through environment variables and offers a very detailed view; it is a commercial service, with a self-hosted option reserved for certain plans. The open alternative is OpenTelemetry, which sends traces to the backend of your choice.
The OpenLLMetry instrumentation for LangChain
The OpenLLMetry project publishes an OpenTelemetry instrumentation for LangChain, which also covers LangGraph since the latter relies on LangChain’s callback system. Each graph run becomes a trace, each node a child span, and each model call a span carrying the model, input and output tokens and the duration.
pip install opentelemetry-sdk opentelemetry-exporter-otlp \
opentelemetry-instrumentation-langchain
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.instrumentation.langchain import LangchainInstrumentor
provider = TracerProvider()
provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter()))
trace.set_tracer_provider(provider)
LangchainInstrumentor().instrument()
# ... then build and invoke the graph as above
The same project’s traceloop-sdk wraps this configuration into a single initialisation call. Check the package and class names in the OpenLLMetry repository; we compare this approach with Langfuse in Langfuse and OpenLLMetry.
Adding business context
Automatic spans tell you what the agent does, not who it does it for. Add attributes to the current span: conversation ID, team, request type. Avoid putting the full prompt text there if prompts contain personal data; some instrumentations offer an option to disable content capture.
Visualising the agent’s steps in Dynatrace
The OTLP exporter is configured through the standard variables (OTEL_EXPORTER_OTLP_ENDPOINT, OTEL_EXPORTER_OTLP_HEADERS, OTEL_SERVICE_NAME), pointing either to an OpenTelemetry Collector or directly to the Dynatrace OTLP endpoint with an API token allowed to ingest traces. In the distributed traces view, an agent run appears as a tree: the planifier node, an LLM call, the repondre node, another call. You immediately spot the slowest step, a tool loop running away or a call that uses too many tokens.
From these spans you can derive indicators: number of steps per run, tokens per run, tool error rate, end-to-end latency. If the model server is traced too, W3C propagation extends the trace all the way to inference, following the principles of our article end-to-end OpenTelemetry.
Best practices
- Set a limit on the number of graph iterations to avoid infinite loops and surprise bills.
- Name nodes explicitly: they are what will appear in the traces.
- Pin the versions of
langchain,langgraphand the instrumentations, which change quickly. - Trace from development onwards: comparing traces before and after a prompt change is very instructive.
- Mask or disable prompt content capture when it is sensitive.
Frequently asked questions
Do you need LangChain to use LangGraph?
LangGraph can orchestrate any Python code, but it integrates naturally with LangChain’s models and tools, and the two are usually installed together.
Is LangSmith required to trace an agent?
No. An OpenTelemetry instrumentation such as OpenLLMetry’s sends traces to any OTLP-compatible backend.
Can you use a local model with LangGraph?
Yes, through the Ollama integration or an OpenAI-compatible client pointed at Ollama, vLLM or llama.cpp.
Conclusion
LangGraph makes agents explicit; OpenTelemetry makes them observable. Together they turn opaque behaviour into a tree of measurable steps that you can follow and alert on in Dynatrace like any other service. To choose the rest of the stack, read our comparison of self-hosted open source AI stacks.
span.observer is an independent community blog, not affiliated with Dynatrace LLC or with the projects mentioned. Trademarks belong to their respective owners. Tools change quickly: check commands and options in their official documentation.
Originally published on span.observer. French version: https://span.observer/fr/langchain-langgraph-tracer-agents/.
來源:DEV Community · dev.to