> ## Documentation Index
> Fetch the complete documentation index at: https://cndoc-langchain.site/llms.txt
> Use this file to discover all available pages before exploring further.

# 追踪 OpenAI Agents SDK 应用程序

> 使用 LangSmith 追踪 OpenAI Agents SDK 的 Python 和 JavaScript 应用程序。

OpenAI Agents SDK 允许您构建由 OpenAI 模型驱动的智能体应用程序。

使用 LangSmith 追踪 OpenAI Agents SDK 的运行过程，包括智能体步骤、模型调用、工具调用和交接。

<Tabs>
  <Tab title="Python">
    ## 安装

    <Info>
      需要 Python SDK 版本 `langsmith>=0.3.15`。
    </Info>

    安装支持 OpenAI Agents 的 LangSmith：

    <CodeGroup>
      ```bash pip theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      pip install "langsmith[openai-agents]"
      ```

      ```bash uv theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      uv add "langsmith[openai-agents]"
      ```
    </CodeGroup>

    这将同时安装 LangSmith 库和 OpenAI Agents SDK。

    ## 环境配置

    ```bash Shell theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    export LANGSMITH_API_KEY=<your-api-key>
    export OPENAI_API_KEY=<your-openai-api-key>

    # 可选：为您的追踪设置一个项目
    export LANGSMITH_PROJECT=<your-project-name>

    # 对于链接到多个工作区的 LangSmith API 密钥，请设置 LANGSMITH_WORKSPACE_ID 环境变量以指定使用哪个工作区。
    export LANGSMITH_WORKSPACE_ID=<your-workspace-id>
    ```

    ## 快速开始

    通过使用 `OpenAIAgentsTracingProcessor` 类，将 LangSmith 追踪与 OpenAI Agents SDK 集成。

    ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    import asyncio

    from agents import Agent, Runner, set_trace_processors
    from langsmith.integrations.openai_agents_sdk import OpenAIAgentsTracingProcessor


    async def main():
        agent = Agent(
            name="Captain Obvious",
            instructions="You are Captain Obvious, the world's most literal technical support agent.",
        )

        question = "Why is my code failing when I try to divide by zero? I keep getting this error message."
        result = await Runner.run(agent, question)
        print(result.final_output)


    if __name__ == "__main__":
        set_trace_processors([OpenAIAgentsTracingProcessor()])
        asyncio.run(main())
    ```

    智能体的执行流程，包括跨度及其详细信息，都会被记录到 LangSmith。
  </Tab>

  <Tab title="JavaScript">
    ## 安装

    <Info>
      需要 JS SDK 版本 `langsmith>=0.5.25`。
    </Info>

    安装 LangSmith 和 OpenAI Agents SDK：

    <CodeGroup>
      ```bash npm theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      npm install langsmith @openai/agents zod
      ```

      ```bash yarn theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      yarn add langsmith @openai/agents zod
      ```

      ```bash pnpm theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      pnpm add langsmith @openai/agents zod
      ```
    </CodeGroup>

    ## 环境配置

    ```bash Shell theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    export LANGSMITH_API_KEY=<your-api-key>
    export OPENAI_API_KEY=<your-openai-api-key>

    # 可选：为您的追踪设置一个项目
    export LANGSMITH_PROJECT=<your-project-name>

    # 对于链接到多个工作区的 LangSmith API 密钥，请设置 LANGSMITH_WORKSPACE_ID 环境变量以指定使用哪个工作区。
    export LANGSMITH_WORKSPACE_ID=<your-workspace-id>
    ```

    <Note>
      安装 `OpenAIAgentsTracingProcessor` 是明确选择启用追踪。即使未设置 `LANGSMITH_TRACING`，该处理器也会发送追踪数据，并且智能体工具内的嵌套 `traceable` 调用会继承活动的追踪上下文。
    </Note>

    ## 快速开始

    在运行智能体之前，向 OpenAI Agents SDK 注册 `OpenAIAgentsTracingProcessor`。

    ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    import { Agent, run, setTraceProcessors, tool } from "@openai/agents";
    import { z } from "zod";

    import { OpenAIAgentsTracingProcessor } from "langsmith/wrappers/openai_agents";

    setTraceProcessors([new OpenAIAgentsTracingProcessor()]);

    const getWeather = tool({
      name: "get_weather",
      description: "Get the current weather for a city",
      parameters: z.object({
        city: z.string().describe("The city to get weather for"),
      }),
      execute: async ({ city }: { city: string }) => {
        return `The weather in ${city} is sunny.`;
      },
    });

    const agent = new Agent({
      name: "WeatherAgent",
      instructions: "You are a helpful assistant. Use the get_weather tool when asked about weather.",
      model: "gpt-5-nano",
      tools: [getWeather],
    });

    const result = await run(agent, "What's the weather in San Francisco?");
    console.log(result.finalOutput);
    ```

    生成的追踪包含根智能体运行、响应跨度和嵌套的工具调用跨度。

    ## 配置处理器

    向处理器传递选项以设置 LangSmith 客户端、项目、标签、元数据或根追踪名称。

    ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    import { Agent, run, setTraceProcessors } from "@openai/agents";

    import { Client } from "langsmith";
    import { OpenAIAgentsTracingProcessor } from "langsmith/wrappers/openai_agents";

    const client = new Client();
    const processor = new OpenAIAgentsTracingProcessor({
      client,
      projectName: "openai-agents-demo",
      name: "Support agent workflow",
      tags: ["openai-agents"],
      metadata: {
        environment: "development",
      },
    });

    setTraceProcessors([processor]);

    const agent = new Agent({
      name: "SupportAgent",
      instructions: "You are a concise support agent.",
      model: "gpt-5-nano",
    });

    const result = await run(agent, "Help me reset my password.");
    console.log(result.finalOutput);
    ```

    ## 在工具中嵌套 `traceable` 调用

    您可以在 OpenAI Agents SDK 工具处理器内部使用 `traceable`。LangSmith 会将这些运行嵌套在活动的工具跨度下。

    ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    import { Agent, run, setTraceProcessors, tool } from "@openai/agents";
    import { z } from "zod";

    import { traceable } from "langsmith/traceable";
    import { OpenAIAgentsTracingProcessor } from "langsmith/wrappers/openai_agents";

    setTraceProcessors([new OpenAIAgentsTracingProcessor()]);

    const lookupOrder = traceable(
      async (orderId: string) => {
        return { orderId, status: "shipped" };
      },
      { name: "lookup_order" }
    );

    const orderStatus = tool({
      name: "order_status",
      description: "Look up the status of an order",
      parameters: z.object({
        orderId: z.string().describe("The order ID to look up"),
      }),
      execute: async ({ orderId }: { orderId: string }) => {
        return JSON.stringify(await lookupOrder(orderId));
      },
    });

    const agent = new Agent({
      name: "OrdersAgent",
      instructions: "Use the order_status tool to answer order questions.",
      model: "gpt-5-nano",
      tools: [orderStatus],
    });

    await run(agent, "Where is order 123?");
    ```

    ## 在无服务器环境中刷新追踪

    在无服务器环境中进行追踪时，请在进程退出前刷新待处理的追踪。

    ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    import { Agent, run, setTraceProcessors } from "@openai/agents";

    import { Client } from "langsmith";
    import { OpenAIAgentsTracingProcessor } from "langsmith/wrappers/openai_agents";

    const client = new Client();
    const processor = new OpenAIAgentsTracingProcessor({ client });
    setTraceProcessors([processor]);

    try {
      const agent = new Agent({
        name: "SupportAgent",
        instructions: "You are a concise support agent.",
        model: "gpt-5-nano",
      });

      const result = await run(agent, "Help me reset my password.");
      console.log(result.finalOutput);
    } finally {
      await processor.forceFlush();
    }
    ```
  </Tab>
</Tabs>

***

<div className="source-links">
  <Callout icon="terminal-2">
    [将这些文档连接](/use-these-docs)到 Claude、VSCode 等，通过 MCP 获取实时答案。
  </Callout>

  <Callout icon="edit">
    [在 GitHub 上编辑此页面](https://github.com/langchain-ai/docs/edit/main/src/langsmith/trace-with-openai-agents-sdk.mdx) 或 [提交问题](https://github.com/langchain-ai/docs/issues/new/choose)。
  </Callout>
</div>
