mcpField
O
openai-agents

openai-agents

github.com/jezwebAgent 工作流1.1k359 次安装3 周前更新
代码仓库

关于 openai-agents

这项技能介绍如何用 OpenAI Agents SDK 构建文本和实时语音 Agent,涵盖多 Agent 协作、类型化工具、校验及人工审批模式。

主要功能

  1. 01文本与实时语音 Agent
  2. 02多 Agent 交接
  3. 03类型化工具与结构化输出
  4. 04输入和输出护栏
  5. 05工具调用人工审批

适用场景

  1. 01构建带工具的文本 Agent
  2. 02将请求转交给专用 Agent
  3. 03校验 Agent 的结构化响应
  4. 04工具执行前要求审批

MCP 相关

README 提到使用 MCP 服务时的 Agent 跟踪初始化设置。

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/jezweb/claude-skills --skill openai-agents

安装后在 Claude Code 中输入/openai-agents确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

README.md
.claude-plugin/
plugin.json
references/
agent-patterns.md
cloudflare-integration.md
common-errors.md
official-links.md
realtime-transports.md
rules/
openai-agents.md
scripts/
check-versions.sh
templates/cloudflare-workers/
worker-agent-hono.ts
worker-text-agent.ts
templates/nextjs/
api-agent-route.ts
api-realtime-route.ts
templates/realtime-agents/
realtime-agent-basic.ts
realtime-handoffs.ts
realtime-session-browser.tsx
templates/shared/
error-handling.ts
package.json
tracing-setup.ts
templates/text-agents/
agent-basic.ts
agent-guardrails-input.ts
agent-guardrails-output.ts
agent-handoffs.ts
agent-human-approval.ts
agent-parallel.ts
agent-streaming.ts
agent-structured-output.ts

详细介绍

OpenAI Agents SDK

使用文本 Agent、语音 Agent(实时)、多 Agent 工作流、工具、护栏和人在环路模式构建 AI 应用。


快速开始

npm install @openai/agents zod@4  # v0.4.0+ requires Zod 4 (breaking change)
npm install @openai/agents-realtime  # Voice agents
export OPENAI_API_KEY="your-key"

重大变更(v0.4.0):不再支持 Zod 3。请升级到 zod@4。

运行时:Node.js 22+、Deno、Bun、Cloudflare Workers(实验性)


核心概念

Agent:包含指令和工具的大模型

import { Agent } from '@openai/agents';
const agent = new Agent({ name: 'Assistant', tools: [myTool], model: 'gpt-5-mini' });

工具:带有 Zod 架构的函数

import { tool } from '@openai/agents';
import { z } from 'zod';
const weatherTool = tool({
  name: 'get_weather',
  parameters: z.object({ city: z.string() }),
  execute: async ({ city }) => `Weather in ${city}: sunny`,
});

交接:多 Agent 委派

const triageAgent = Agent.create({ handoffs: [specialist1, specialist2] });

护栏:输入/输出验证

const agent = new Agent({ inputGuardrails: [detector], outputGuardrails: [filter] });

结构化输出:类型安全的响应

const agent = new Agent({ outputType: z.object({ sentiment: z.enum(['positive', 'negative']) }) });

文本 Agent

基础用法:const result = await run(agent, 'What is 2+2?')

流式传输:

const stream = await run(agent, 'Tell me a story', { stream: true });
for await (const event of stream) {
  if (event.type === 'raw_model_stream_event') process.stdout.write(event.data?.choices?.[0]?.delta?.content || '');
}

多 Agent 交接

const billingAgent = new Agent({ name: 'Billing', handoffDescription: 'For billing questions', tools: [refundTool] });
const techAgent = new Agent({ name: 'Technical', handoffDescription: 'For tech issues', tools: [ticketTool] });
const triageAgent = Agent.create({ name: 'Triage', handoffs: [billingAgent, techAgent] });

Agent 作为工具时的上下文隔离:使用 agent.asTool() 时,子 Agent 不会共享父级对话历史(这是为了简化调试而采用的有意设计)。

解决方法:通过工具参数传递上下文:

const helperTool = tool({
  name: 'use_helper',
  parameters: z.object({
    query: z.string(),
    context: z.string().optional(),
  }),
  execute: async ({ query, context }) => {
    return await run(subAgent, `${context}\n\n${query}`);
  },
});

来源:Issue #806


护栏

输入:处理前进行验证

const guardrail: InputGuardrail = {
  execute: async ({ input }) => ({ tripwireTriggered: detectHomework(input) })
};
const agent = new Agent({ inputGuardrails: [guardrail] });

输出:过滤响应(PII 检测、内容安全)


人在环路

const refundTool = tool({ name: 'process_refund', requiresApproval: true, execute: async ({ amount }) => `Refunded $${amount}` });

let result = await runner.run(input);
while (result.interruption?.type === 'tool_approval') {
  result = await promptUser(result.interruption) ? result.state.approve(result.interruption) : result.state.reject(result.interruption);
}

流式 HITL:使用 stream: true 和 requiresApproval 时,必须显式检查中断:

const stream = await run(agent, input, { stream: true });
let result = await stream.finalResult();
while (result.interruption?.type === 'tool_approval') {
  const approved = await promptUser(result.interruption);
  result = approved
    ? await result.state.approve(result.interruption)
    : await result.state.reject(result.interruption);
}

示例:human-in-the-loop-stream.ts


实时语音 Agent

创建:

import { RealtimeAgent } from '@openai/agents-realtime';
const voiceAgent = new RealtimeAgent({
  voice: 'alloy', // alloy, echo, fable, onyx, nova, shimmer
  model: 'gpt-5-realtime',
  tools: [weatherTool],
});

浏览器会话:

import { RealtimeSession } from '@openai/agents-realtime';
const session = new RealtimeSession(voiceAgent, { apiKey: sessionApiKey, transport: 'webrtc' });
await session.connect();

重要:绝不要将 OPENAI_API_KEY 发送到浏览器!请在服务端生成临时会话令牌。

语音交接:各 Agent 的语音/模型必须匹配(交接期间无法更改)

限制:

  • 不支持视频流:尽管有摄像头示例,但原生不支持实时视频流。模型可能不会根据视频事件主动发言。(Issue #694)

模板:

  • templates/realtime-agents/realtime-agent-basic.ts
  • templates/realtime-agents/realtime-session-browser.tsx
  • templates/realtime-agents/realtime-handoffs.ts

参考资料:

  • references/realtime-transports.md - WebRTC 与 WebSocket

框架集成

Cloudflare Workers(实验性):

export default {
  async fetch(request: Request, env: Env) {
    // Disable tracing or use startTracingExportLoop()
    process.env.OTEL_SDK_DISABLED = 'true';

    process.env.OPENAI_API_KEY = env.OPENAI_API_KEY;
    const agent = new Agent({ name: 'Assistant', model: 'gpt-5-mini' });
    const result = await run(agent, (await request.json()).message);
    return Response.json({ response: result.finalOutput, tokens: result.usage.totalTokens });
  }
};

限制:

  • 不支持语音 Agent
  • CPU 时间限制为 30s,内存为 128MB
  • 跟踪需要手动设置 - 设置 OTEL_SDK_DISABLED=true 或调用 startTracingExportLoop()(Issue #16)

Next.js:app/api/agent/route.ts → 使用 run(agent, message) 的 POST 处理程序

模板:cloudflare-workers/、nextjs/


错误处理(避免 11+ 种错误)

1. Zod 架构类型错误

错误:工具参数出现类型错误。

解决方法:在行内定义架构。

// ❌ Can cause type errors
parameters: mySchema

// ✅ Works reliably
parameters: z.object({ field: z.string() })

注意:从 v0.4.1 起,工具调用参数中的无效 JSON 可以得到妥善处理(此前会导致 SyntaxError 崩溃)。(PR #887)

来源:GitHub #188

2. MCP 跟踪错误

错误:MCP 服务出现“No existing trace found”。

解决方法:

import { initializeTracing } from '@openai/agents/tracing';
await initializeTracing();

来源:GitHub #580

3. MaxTurnsExceededError

错误:Agent 无限循环。

解决方案:增加 maxTurns 或改进指令:

const result = await run(agent, input, {
  maxTurns: 20, // Increase limit
});

// Or improve instructions
instructions: `After using tools, provide a final answer.
Do not loop endlessly.`
4. ToolCallError

错误:工具执行失败。

解决方案:使用指数退避重试:

for (let attempt = 1; attempt <= 3; attempt++) {
  try {
    return await run(agent, input);
  } catch (error) {
    if (error instanceof ToolCallError && attempt < 3) {
      await sleep(1000 * Math.pow(2, attempt - 1));
      continue;
    }
    throw error;
  }
}
5. 架构不匹配

错误:输出与 outputType 不匹配。

解决方案:使用能力更强的模型或添加验证指令:

const agent = new Agent({
  model: 'gpt-5', // More reliable than gpt-5-mini
  instructions: 'CRITICAL: Return JSON matching schema exactly',
  outputType: mySchema,
});
6. 推理强度默认值已更改(v0.4.0)

错误:升级到 v0.4.0 后,推理行为异常。

原因:v0.4.0 中,gpt-5.1/5.2 的默认推理强度从 "low" 更改为 "none"。

预防方法:如果需要推理,请显式设置推理强度。

// v0.4.0+ - default is now "none"
const agent = new Agent({
  model: 'gpt-5.1',
  reasoning: { effort: 'low' }, // Explicitly set if needed: 'low', 'medium', 'high'
});

来源:发布版本 v0.4.0 | PR #876

7. 推理内容泄漏到 JSON 输出中

错误:结构化输出中意外出现 response_reasoning 字段。

原因:使用推理模型时,模型端点存在问题(并非 SDK 错误)。

解决方法:从输出中过滤掉 response_reasoning。

const result = await run(agent, input);
const { response_reasoning, ...cleanOutput } = result.finalOutput;
return cleanOutput;

来源:Issue #844 状态:模型端问题,正在与 OpenAI 团队协调

所有错误:参见 references/common-errors.md

模板:templates/shared/error-handling.ts


编排模式

基于 LLM:Agent 自主决定路由(适应性强,但消耗更多 token) 基于代码:使用条件语句显式控制流程(可预测,成本较低) 并行:Promise.all([run(agent1, text), run(agent2, text)])(并发执行)


调试

process.env.DEBUG = '@openai/agents:*';  // Verbose logging
const result = await run(agent, input);
console.log(result.usage.totalTokens, result.history.length, result.currentAgent?.name);

❌ 不适用场景:

  • 简单的 OpenAI API 调用(请改用 openai-api 技能)
  • 仅使用非 OpenAI 模型
  • 大规模生产语音应用(可考虑 LiveKit Agents)

生产环境检查清单

  • 将 OPENAI_API_KEY 设置为环境密钥
  • 为所有 Agent 调用实现错误处理
  • 为安全关键型应用添加防护措施
  • 启用跟踪以便调试
  • 设置合理的 maxTurns,以避免成本失控
  • 尽可能使用 gpt-5-mini,提高成本效益
  • 实现速率限制
  • 记录 token 用量以监控成本
  • 彻底测试交接流程
  • 切勿向浏览器暴露 API 密钥(请使用会话令牌)

Token 效率

预计节省:约 60%

任务不使用技能使用技能节省比例
多 Agent 设置约 12k tokens约 5k tokens58%
语音 Agent约 10k tokens约 4k tokens60%
错误调试约 8k tokens约 3k tokens63%
平均约 10k约 4k约 60%

已预防的错误:已记录的 11 个问题 = 100% 错误预防


模板索引

文本 Agent(8 个):

  1. agent-basic.ts - 带工具的简单 Agent
  2. agent-handoffs.ts - 多 Agent 分诊
  3. agent-structured-output.ts - Zod 模式
  4. agent-streaming.ts - 实时事件
  5. agent-guardrails-input.ts - 输入验证
  6. agent-guardrails-output.ts - 输出过滤
  7. agent-human-approval.ts - HITL 模式
  8. agent-parallel.ts - 并发执行

实时 Agent(3 个): 9. realtime-agent-basic.ts - 语音设置 10. realtime-session-browser.tsx - React 客户端 11. realtime-handoffs.ts - 语音委派

框架集成(4 个): 12. worker-text-agent.ts - Cloudflare Workers 13. worker-agent-hono.ts - Hono 框架 14. api-agent-route.ts - Next.js API 15. api-realtime-route.ts - Next.js 语音

实用工具(2 个): 16. error-handling.ts - 全面的错误处理 17. tracing-setup.ts - 调试


参考资料

  1. agent-patterns.md - 编排策略
  2. common-errors.md - 9 个错误及解决方法
  3. realtime-transports.md - WebRTC 与 WebSocket
  4. cloudflare-integration.md - Workers 限制
  5. official-links.md - 文档链接

官方资源


版本:SDK v0.4.1 最后验证时间:2026-01-21 技能作者:Jeremy Dawes(Jezweb) 是否经过生产测试:是 更改内容:新增 v0.4.0 破坏性更改(Zod 4、推理默认设置)、无效 JSON 处理(v0.4.1)、推理输出泄漏、流式 HITL 模式、Agent 作为工具时的上下文隔离、视频限制、Cloudflare 跟踪设置

评论

支持 Markdown