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

实现分布式追踪

有时,你需要跨多个服务追踪一个请求。

LangSmith 开箱即用地支持分布式追踪,通过上下文传播请求头(langsmith-trace 和可选的 baggage 用于元数据/标签)将跨服务的 run 链接到同一追踪中。

客户端-服务器示例设置:

  • 追踪在客户端开始
  • 在服务器继续

WARNING

仅接受来自可信服务的分布式追踪请求头。langsmith-trace 和 baggage 请求头会被作为可信追踪上下文使用。请勿在直接接收不受信任第三方或公共互联网请求的服务上添加 TracingMiddleware(或将入站请求头作为追踪 parent 传入)。将分布式追踪限制在内部服务间调用,并在网关或代理处从不受信任的入站请求中移除这些请求头。信任来自外部调用方的 baggage 会让他们影响你的 run 记录方式。

Python 中的分布式追踪

python
# client.py
from langsmith.run_helpers import get_current_run_tree, traceable
import httpx

@traceable
async def my_client_function():
    headers = {}
    async with httpx.AsyncClient(base_url="...") as client:
        if run_tree := get_current_run_tree():
            # add langsmith-id to headers
            headers.update(run_tree.to_headers())
        return await client.post("/my-route", headers=headers)

然后,服务器(或其他服务)可以通过适当处理请求头来继续追踪。如果你使用 ASGI 应用 Starlette 或 FastAPI,可以使用 LangSmith 的 TracingMiddleware 连接分布式追踪。

INFO

TracingMiddleware 类在 langsmith==0.1.133 中添加。

使用 FastAPI 的示例:

python
from langsmith import traceable
from langsmith.middleware import TracingMiddleware
from fastapi import FastAPI, Request

app = FastAPI()  # Or Flask, Django, or any other framework
app.add_middleware(TracingMiddleware)

@traceable
async def some_function():
    ...

@app.post("/my-route")
async def fake_route(request: Request):
    return await some_function()

或在 Starlette 中:

python
from starlette.applications import Starlette
from starlette.middleware import Middleware
from langsmith.middleware import TracingMiddleware

routes = ...
middleware = [
    Middleware(TracingMiddleware),
]
app = Starlette(..., middleware=middleware)

如果你使用其他服务器框架,始终可以通过 langsmith_extra 传入请求头来“接收”分布式追踪:

python
# server.py
import langsmith as ls
from fastapi import FastAPI, Request

@ls.traceable
async def my_application():
    ...

app = FastAPI()  # Or Flask, Django, or any other framework

@app.post("/my-route")
async def fake_route(request: Request):
    # request.headers:  {"langsmith-trace": "..."}
    # as well as optional metadata/tags in `baggage`
    with ls.tracing_context(parent=request.headers):
        return await my_application()

上面的示例使用 tracing_context 上下文管理器。你也可以在用 @traceable 包装的方法的 langsmith_extra 参数中直接指定父 run 上下文。

python
# ... same as above

@app.post("/my-route")
async def fake_route(request: Request):
    # request.headers:  {"langsmith-trace": "..."}
    my_application(langsmith_extra={"parent": request.headers})

TypeScript 中的分布式追踪

NOTE

TypeScript 中的分布式追踪需要 langsmith>=0.1.31

首先,我们从客户端获取当前 run tree,并将其转换为 langsmith-trace 和 baggage 请求头值,然后传递给服务器:

typescript
// client.mts
import { getCurrentRunTree, traceable } from "langsmith/traceable";

const client = traceable(
    async () => {
        const runTree = getCurrentRunTree();
        return await fetch("...", {
            method: "POST",
            headers: runTree.toHeaders(),
        }).then((a) => a.text());
    },
    { name: "client" }
);

await client();

然后,服务器将请求头转换回 run tree,并用它继续追踪。

要将新创建的 run tree 传递给 traceable 函数,我们可以使用 withRunTree 辅助函数,它将确保 run tree 在 traceable 调用中传播。

typescript
// server.mts
import { RunTree } from "langsmith";
import { traceable, withRunTree } from "langsmith/traceable";
import express from "express";
import bodyParser from "body-parser";

    const server = traceable(
        (text: string) => `Hello from the server! Received "${text}"`,
        { name: "server" }
    );

    const app = express();
    app.use(bodyParser.text());

app.post("/", async (req, res) => {
    const runTree = RunTree.fromHeaders(req.headers);
    const result = await withRunTree(runTree, () => server(req.body));
    res.send(result);
});
typescript
// server.mts
import { RunTree } from "langsmith";
import { traceable, withRunTree } from "langsmith/traceable";
import { Hono } from "hono";

    const server = traceable(
        (text: string) => `Hello from the server! Received "${text}"`,
        { name: "server" }
    );

    const app = new Hono();

app.post("/", async (c) => {
    const body = await c.req.text();
    const runTree = RunTree.fromHeaders(c.req.raw.headers);
    const result = await withRunTree(runTree, () => server(body));
    return c.body(result);
});

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