Skip to content
LangSmith 文档版本 跟随上游 源快照 51a1131d 更新于 2026-10-18

使用 Agent Server 进行分布式追踪

当使用 RemoteGraph 或 SDK 从另一个服务调用你已部署的 Agent Server 时,统一追踪。

当你从另一个服务调用已部署的 Agent Server 时,可以传播追踪上下文,使整个请求在 LangSmith 中显示为一条统一的追踪。这利用了 LangSmith 的分布式追踪能力,该能力通过 HTTP 请求头传播上下文。

工作原理

分布式追踪使用上下文传播请求头跨服务关联运行:

  1. 客户端从当前运行推断追踪上下文,并将其作为 HTTP 请求头发送出去。
  2. 服务器读取这些请求头,并将它们作为 langsmith-trace 和 langsmith-project 可配置值添加到运行的 config 和 metadata 中。当你的智能体被使用时,你可以选择用它们来为给定的运行设置追踪上下文。

使用的请求头如下:

  • langsmith-trace:包含该追踪的点分顺序。
  • baggage:指定 LangSmith 项目以及其他可选的标签和 metadata。

要启用分布式追踪,客户端和服务器都需要选择启用。

配置服务器

要接受分布式追踪上下文,你的图必须从 config 中读取追踪请求头并设置追踪上下文。这些请求头通过 configurable 字段以 langsmith-trace 和 langsmith-project 的形式传入。

WARNING

分布式追踪请求头(langsmith-trace、baggage)会被当作可信的追踪上下文来使用。仅当你的部署由可信的内部服务调用时,才应将服务器配置为应用入站追踪上下文。如果你的 Agent Server 直接接收来自不可信第三方或公共互联网的请求,请不要将这些请求头传播到追踪上下文中:而应在网关或代理处将它们剥离。信任来自外部调用者的 baggage 会让他们影响你的运行被记录的方式。

python
import contextlib
import langsmith as ls
from langgraph.graph import StateGraph, MessagesState

# Define your graph
builder = StateGraph(MessagesState)
# ... add nodes and edges ...
my_graph = builder.compile()

@contextlib.contextmanager
async def graph(config):
    configurable = config.get("configurable", {})
    parent_trace = configurable.get("langsmith-trace")
    parent_project = configurable.get("langsmith-project")
    # If you want to also include metadata and tags from the client
    metadata = configurable.get("langsmith-metadata")
    tags = configurable.get("langsmith-tags")
    with ls.tracing_context(parent=parent_trace, project_name=parent_project, metadata=metadata, tags=tags):
        yield my_graph

在你的 langgraph.json 中导出这个 graph 函数:

json
{
  "graphs": {
    "agent": "./src/agent.py:graph"
  }
}

从客户端连接

初始化 RemoteGraph 时设置 distributed_tracing=True。这会在所有请求上自动传播追踪请求头。

python
from langgraph.graph import StateGraph
from langgraph.pregel.remote import RemoteGraph

remote_graph = RemoteGraph(
    "agent",
    url="<DEPLOYMENT_URL>",
    distributed_tracing=True,  # Enable trace propagation
)

def subgraph_node(query: str):
    # Trace context is automatically propagated
    return remote_graph.invoke({
        "messages": [{"role": "user", "content": query}]
    })['messages'][-1]['content']

# The RemoteGraph is called in the context of some on going work.
# This could be a parent LangGraph agent, code traced with `@ls.traceable`,
# or any other instrumented code.
graph = (
        StateGraph(str)
            .add_node(subgraph_node)
            .add_edge("__start__", "subgraph_node")
            .compile()
)
# The remote graph's execution will appear as a child of this trace
result = graph.invoke("What's the weather in SF?")

相关


BytesRouter 是社区翻译站点,所有译文仅供参考,一切以官方英文原文为准。