OpenAI Agents SDK 集成与可观测性

2026-11-06 17:50 更新

工作流结构明确后,需要决定哪些外部能力放入智能体循环,以及如何查看运行时实际发生的操作。

选择由SDK承载的能力

需求 起点 原因
访问公开远程托管的MCP工具 SDK中的托管MCP工具 模型可通过托管能力调用远程MCP服务器
从自有运行时连接本地或私有MCP服务器 SDK管理的stdio或可流式HTTP连接 运行时负责连接、批准与网络边界
调试提示词、工具、交接或批准 内置追踪 正式开展评测前,追踪提供端到端记录

工具能力语义见使用工具。本页侧重SDK特有的MCP接入和可观测性流程。

MCP

远程服务器应经模型侧托管能力调用时,使用托管MCP工具:

来源示例 1(javascript):

// [中文] 示例1:MCP。
// [中文] 配置托管MCP服务器https://gitmcp.io/openai/codex;指令要求用MCP工具回答问题,本段尚未运行任务。
// [中文] Python来源显式设置require_approval:never,JavaScript没有提供同名配置;按各SDK和服务器的信任及批准要求核对,不假设默认策略相同。
import { Agent, hostedMcpTool } from "@openai/agents";

const agent = new Agent({
  name: "MCP assistant",
  instructions: "Use the MCP tools to answer questions.",
  tools: [
    hostedMcpTool({
      serverLabel: "gitmcp",
      serverUrl: "https://gitmcp.io/openai/codex",
    }),
  ],
});

来源示例 2(python):

## [中文] 示例2:MCP。
## [中文] 配置托管MCP服务器https://gitmcp.io/openai/codex;指令要求用MCP工具回答问题,本段尚未运行任务。
## [中文] Python来源显式设置require_approval:never,JavaScript没有提供同名配置;按各SDK和服务器的信任及批准要求核对,不假设默认策略相同。
from agents import Agent, HostedMCPTool

agent = Agent(
    name="MCP assistant",
    instructions="Use the MCP tools to answer questions.",
    tools=[
        HostedMCPTool(
            tool_config={
                "type": "mcp",
                "server_label": "gitmcp",
                "server_url": "https://gitmcp.io/openai/codex",
                "require_approval": "never",
            }
        )
    ],
)

应用应直接连接MCP服务器时,使用本地传输:

来源示例 3(javascript):

// [中文] 示例3:MCP。
// [中文] 启动本地文件系统MCP进程;指令要求先读文件再回答,用户输入要求读取并列出文件。
// [中文] JavaScript目录为fixtures/sample_files,Python为./sample_files,运行前需准备相应目录及Node/npx;退出时关闭服务器连接。
import { Agent, MCPServerStdio, run } from "@openai/agents";

const server = new MCPServerStdio({
  name: "Filesystem MCP Server",
  fullCommand:
    "npx -y @modelcontextprotocol/server-filesystem fixtures/sample_files",
});

await server.connect();

try {
  const agent = new Agent({
    name: "Filesystem assistant",
    instructions: "Read files with the MCP tools before answering.",
    mcpServers: [server],
  });

  const result = await run(agent, "Read the files and list them.");
  console.log(result.finalOutput);
} finally {
  await server.close();
}

来源示例 4(python):

## [中文] 示例4:MCP。
## [中文] 启动本地文件系统MCP进程;指令要求先读文件再回答,用户输入要求读取并列出文件。
## [中文] JavaScript目录为fixtures/sample_files,Python为./sample_files,运行前需准备相应目录及Node/npx;退出时关闭服务器连接。
import asyncio

from agents import Agent, Runner
from agents.mcp import MCPServerStdio


async def main() -> None:
    async with MCPServerStdio(
        name="Filesystem MCP Server",
        params={
            "command": "npx",
            "args": [
                "-y",
                "@modelcontextprotocol/server-filesystem",
                "./sample_files",
            ],
        },
    ) as server:
        agent = Agent(
            name="Filesystem assistant",
            instructions="Read files with the MCP tools before answering.",
            mcp_servers=[server],
        )
        result = await Runner.run(agent, "Read the files and list them.")
        print(result.final_output)


if __name__ == "__main__":
    asyncio.run(main())

实际选择原则:适合平台信任模型的公开远程服务器使用托管MCP;运行时需要自己控制连接、过滤或批准时,使用本地或私有MCP。

平台通用概念、信任模型与产品支持,以MCP服务器为基础参考。

追踪

Agents SDK内置追踪,正常服务端SDK路径默认启用。每次运行可生成模型调用、工具调用、交接、护栏及自定义跨度(span)的结构化记录,在追踪控制台查看。

默认追踪通常包含整个运行或工作流、每次模型调用、工具调用及输出、交接与护栏,以及为工作流额外包裹的自定义跨度。

需要减少追踪时,使用SDK级或单次运行控制,不必移除整个工作流的可观测性。以下把多次运行放在一条追踪中:

来源示例 5(javascript):

// [中文] 示例5:追踪。
// [中文] 在同一条“笑话工作流”追踪中运行两次:先要求“讲个笑话”,再把第一次最终输出作为第二次“评价这个笑话”的输入。
// [中文] 智能体指令是“讲有趣的笑话”;打印两个结果,这里不是把两次运行自动合并为一个对话会话。
import { Agent, run, withTrace } from "@openai/agents";

const agent = new Agent({
  name: "Joke generator",
  instructions: "Tell funny jokes.",
});

await withTrace("Joke workflow", async () => {
  const first = await run(agent, "Tell me a joke");
  const second = await run(agent, `Rate this joke: ${first.finalOutput}`);
  console.log(first.finalOutput);
  console.log(second.finalOutput);
});

来源示例 6(python):

## [中文] 示例6:追踪。
## [中文] 在同一条“笑话工作流”追踪中运行两次:先要求“讲个笑话”,再把第一次最终输出作为第二次“评价这个笑话”的输入。
## [中文] 智能体指令是“讲有趣的笑话”;打印两个结果,这里不是把两次运行自动合并为一个对话会话。
import asyncio

from agents import Agent, Runner, trace

agent = Agent(
    name="Joke generator",
    instructions="Tell funny jokes.",
)


async def main() -> None:
    with trace("Joke workflow"):
        first = await Runner.run(agent, "Tell me a joke")
        second = await Runner.run(
            agent,
            f"Rate this joke: {first.final_output}",
        )
        print(first.final_output)
        print(second.final_output)


if __name__ == "__main__":
    asyncio.run(main())

追踪主要用于调试单次工作流并理解过程;准备系统化评分后,再将更有价值的样例用于智能体工作流评测。

后续步骤

接好外部能力后,可阅读:

以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号