Skip to main content
当您从另一个服务调用已部署的代理服务器时,您可以传播追踪上下文,以便整个请求在 LangSmith 中显示为一个统一的追踪。这利用了 LangSmith 的分布式追踪功能,该功能通过 HTTP 头传播上下文。

工作原理

分布式追踪通过上下文传播头链接跨服务的运行:
  1. 客户端从当前运行中推断追踪上下文,并将其作为 HTTP 头发送。
  2. 服务器读取这些头,并将其作为 langsmith-tracelangsmith-project 可配置值添加到运行的配置和元数据中。您可以选择在使用代理时使用这些值来设置给定运行的追踪上下文。
使用的头包括:
  • langsmith-trace:包含追踪的点分顺序。
  • baggage:指定 LangSmith 项目以及其他可选标签和元数据。
要启用分布式追踪,客户端和服务器都需要选择加入。

配置服务器

要接受分布式追踪上下文,您的图必须从配置中读取追踪头并设置追踪上下文。这些头通过 configurable 字段传递,作为 langsmith-tracelangsmith-project
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 函数:
{
  "graphs": {
    "agent": "./src/agent.py:graph"
  }
}

从客户端连接

在初始化 RemoteGraph 时设置 distributed_tracing=True。这会自动在所有请求上传播追踪头。
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?")

相关内容