主题
当你从另一个服务调用已部署的 Agent Server 时,可以传播追踪上下文,以便整个请求在 LangSmith 中显示为单个统一的追踪。这利用了 LangSmith 的 分布式追踪 功能,该功能通过 HTTP 头传播上下文。
工作原理
分布式追踪使用上下文传播头来链接跨服务的运行:
- 客户端 从当前运行推断追踪上下文,并将其作为 HTTP 头发送。
- 服务器 读取这些头信息,并将它们作为可配置值
langsmith-trace和langsmith-project添加到运行的配置和元数据中。当你的代理被使用时,你可以选择使用这些值来设置给定运行的追踪上下文。
使用的头信息包括:
langsmith-trace:包含追踪的点分顺序。baggage:指定 LangSmith 项目以及其他可选的标签和元数据。
要启用分布式追踪,客户端和服务器都需要选择加入。
配置服务器
要接受分布式追踪上下文,你的图必须从配置中读取追踪头并设置追踪上下文。这些头信息通过 configurable 字段作为 langsmith-trace 和 langsmith-project 传递。
python
import contextlib
import langsmith as ls
from langgraph.graph import StateGraph, MessagesState
# 定义你的图
builder = StateGraph(MessagesState)
# ... 添加节点和边 ...
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")
# 如果你还想包含来自客户端的元数据和标签
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
SDK
初始化 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, # 启用追踪传播
)
def subgraph_node(query: str):
# 追踪上下文会自动传播
return remote_graph.invoke({
"messages": [{"role": "user", "content": query}]
})['messages'][-1]['content']
# RemoteGraph 在某个正在进行的工作的上下文中被调用。
# 这可能是一个父 LangGraph 代理、使用 `@ls.traceable` 追踪的代码,
# 或任何其他已插桩的代码。
graph = (
StateGraph(str)
.add_node(subgraph_node)
.add_edge("__start__", "subgraph_node")
.compile()
)
# 远程图的执行将作为此追踪的子级出现
result = graph.invoke("What's the weather in SF?")相关链接
- 分布式追踪:通用的分布式追踪概念和模式
- RemoteGraph:使用 RemoteGraph 与部署进行交互的完整指南