mcpField
O
openai-agents

openai-agents

github.com/ovachieverAgent 工作流5660 次安装48 周前更新
代码仓库

关于 openai-agents

这是一套使用 OpenAI Agents SDK 构建 JavaScript/TypeScript AI 应用的参考技能,面向开发者。内容涵盖文本与实时语音 Agent、多 Agent 编排、安全校验、部署模板和故障排查。

主要功能

  1. 01文本与实时语音 Agent 模式
  2. 02多 Agent 移交与编排
  3. 03安全护栏与结构化输出
  4. 04工具调用的人为审批
  5. 05框架模板与错误排查

适用场景

  1. 01构建多 Agent 工作流
  2. 02创建实时语音应用
  3. 03添加输入和输出校验
  4. 04使用 Next.js 或 Cloudflare Workers 部署 Agent

安装

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

$npx skills add https://github.com/ovachiever/droid-tings --skill openai-agents

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

包含的文件

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

LICENSE
README.md
.claude-plugin/
plugin.json
references/
agent-patterns.md
cloudflare-integration.md
common-errors.md
official-links.md
realtime-transports.md
scripts/
check-versions.sh
templates/
wrangler.jsonc
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 技能

用于构建 AI 应用的完整技能,基于 OpenAI Agents SDK(JavaScript/TypeScript),涵盖文本 Agent、实时语音 Agent、多 Agent 工作流和生产部署模式。


安装与设置

安装所需软件包:

npm install @openai/agents zod@3
npm install @openai/agents-realtime  # For voice agents

设置环境变量:

export OPENAI_API_KEY="your-api-key"

支持的运行时:

  • Node.js 22+
  • Deno
  • Bun
  • Cloudflare Workers(实验性)

核心概念

1. Agent

配备指令和工具的大模型:

import { Agent } from '@openai/agents';

const agent = new Agent({
  name: 'Assistant',
  instructions: 'You are helpful.',
  tools: [myTool],
  model: 'gpt-4o-mini',
});
2. 工具

Agent 可以调用的函数,并自动生成架构:

import { tool } from '@openai/agents';
import { z } from 'zod';

const weatherTool = tool({
  name: 'get_weather',
  description: 'Get weather for a city',
  parameters: z.object({
    city: z.string(),
  }),
  execute: async ({ city }) => {
    return `Weather in ${city}: sunny`;
  },
});
3. 交接

多 Agent 委派:

const specialist = new Agent({ /* ... */ });

const triageAgent = Agent.create({
  name: 'Triage',
  instructions: 'Route to specialists',
  handoffs: [specialist],
});
4. 护栏

用于安全保障的输入/输出验证:

const agent = new Agent({
  inputGuardrails: [homeworkDetector],
  outputGuardrails: [piiFilter],
});
5. 结构化输出

使用 Zod 实现类型安全的响应:

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

文本 Agent

基本用法
import { run } from '@openai/agents';

const result = await run(agent, 'What is 2+2?');
console.log(result.finalOutput);
console.log(result.usage.totalTokens);
流式传输
const stream = await run(agent, 'Tell me a story', {
  stream: true,
});

for await (const event of stream) {
  if (event.type === 'raw_model_stream_event') {
    const chunk = event.data?.choices?.[0]?.delta?.content || '';
    process.stdout.write(chunk);
  }
}

模板:

  • templates/text-agents/agent-basic.ts
  • templates/text-agents/agent-streaming.ts

多 Agent 交接

创建专用 Agent 并在它们之间路由:

const billingAgent = new Agent({
  name: 'Billing',
  handoffDescription: 'For billing and payment questions',
  tools: [processRefundTool],
});

const techAgent = new Agent({
  name: 'Technical',
  handoffDescription: 'For technical issues',
  tools: [createTicketTool],
});

const triageAgent = Agent.create({
  name: 'Triage',
  instructions: 'Route customers to the right specialist',
  handoffs: [billingAgent, techAgent],
});

模板:

  • templates/text-agents/agent-handoffs.ts

参考:

  • references/agent-patterns.md - 大模型与代码编排

护栏

输入护栏

处理前验证输入:

const homeworkGuardrail: InputGuardrail = {
  name: 'Homework Detection',
  execute: async ({ input, context }) => {
    const result = await run(guardrailAgent, input);
    return {
      tripwireTriggered: result.finalOutput.isHomework,
      outputInfo: result.finalOutput,
    };
  },
};

const agent = new Agent({
  inputGuardrails: [homeworkGuardrail],
});
输出护栏

过滤响应:

const piiGuardrail: OutputGuardrail = {
  name: 'PII Detection',
  execute: async ({ agentOutput }) => {
    const phoneRegex = /\b\d{3}[-. ]?\d{3}[-. ]?\d{4}\b/;
    return {
      tripwireTriggered: phoneRegex.test(agentOutput as string),
      outputInfo: { detected: 'phone_number' },
    };
  },
};

模板:

  • templates/text-agents/agent-guardrails-input.ts
  • templates/text-agents/agent-guardrails-output.ts

人机协同

对特定操作要求审批:

const refundTool = tool({
  name: 'process_refund',
  requiresApproval: true,  // ← Requires human approval
  execute: async ({ amount }) => {
    return `Refunded $${amount}`;
  },
});

// Handle approval requests
let result = await runner.run(input);

while (result.interruption) {
  if (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);
  }
}

模板:

  • templates/text-agents/agent-human-approval.ts

实时语音 Agent

创建语音 Agent
import { RealtimeAgent, tool } from '@openai/agents-realtime';

const voiceAgent = new RealtimeAgent({
  name: 'Voice Assistant',
  instructions: 'Keep responses concise for voice',
  tools: [weatherTool],
  voice: 'alloy', // alloy, echo, fable, onyx, nova, shimmer
  model: 'gpt-4o-realtime-preview',
});
浏览器会话(React)
import { RealtimeSession } from '@openai/agents-realtime';

const session = new RealtimeSession(voiceAgent, {
  apiKey: sessionApiKey, // From your backend!
  transport: 'webrtc', // or 'websocket'
});

session.on('connected', () => console.log('Connected'));
session.on('audio.transcription.completed', (e) => console.log('User:', e.transcript));
session.on('agent.audio.done', (e) => console.log('Agent:', e.transcript));

await session.connect();

重要:切勿将主 OPENAI_API_KEY 发送到浏览器!应在服务端生成临时会话令牌。

语音 Agent 交接

语音 Agent 支持交接,但有以下限制:

  • 交接期间无法更改语音
  • 交接期间无法更改模型
  • 自动传递对话历史
const specialist = new RealtimeAgent({
  voice: 'nova', // Must match parent
  /* ... */
});

const triageAgent = new RealtimeAgent({
  voice: 'nova',
  handoffs: [specialist],
});

模板:

  • 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(实验性)
import { Agent, run } from '@openai/agents';

export default {
  async fetch(request: Request, env: Env) {
    const { message } = await request.json();

    process.env.OPENAI_API_KEY = env.OPENAI_API_KEY;

    const agent = new Agent({
      name: 'Assistant',
      instructions: 'Be helpful and concise',
      model: 'gpt-4o-mini',
    });

    const result = await run(agent, message, {
      maxTurns: 5,
    });

    return new Response(JSON.stringify({
      response: result.finalOutput,
      tokens: result.usage.totalTokens,
    }), {
      headers: { 'Content-Type': 'application/json' },
    });
  },
};

限制:

  • 不支持实时语音 Agent
  • CPU 时间限制(最长 30s)
  • 内存限制(128MB)

模板:

  • templates/cloudflare-workers/worker-text-agent.ts
  • templates/cloudflare-workers/worker-agent-hono.ts

参考:

  • references/cloudflare-integration.md
Next.js App Router
// app/api/agent/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { Agent, run } from '@openai/agents';

export async function POST(request: NextRequest) {
  const { message } = await request.json();

  const agent = new Agent({
    name: 'Assistant',
    instructions: 'Be helpful',
  });

  const result = await run(agent, message);

  return NextResponse.json({
    response: result.finalOutput,
  });
}

模板:

  • templates/nextjs/api-agent-route.ts
  • templates/nextjs/api-realtime-route.ts

错误处理(预防 9+ 种错误)

1. Zod 架构类型错误

错误:工具参数存在类型错误。

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

// ❌ Can cause type errors
parameters: mySchema

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

来源: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-4o', // More reliable than gpt-4o-mini
  instructions: 'CRITICAL: Return JSON matching schema exactly',
  outputType: mySchema,
});

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

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


编排模式

基于大模型

Agent 自主决定路由:

const manager = Agent.create({
  instructions: 'Analyze request and route to appropriate agent',
  handoffs: [agent1, agent2, agent3],
});

优点:自适应,能处理复杂情况 缺点:可预测性较低,令牌消耗较高

基于代码

显式控制流:

const summary = await run(summarizerAgent, text);
const sentiment = await run(sentimentAgent, summary.finalOutput);

if (sentiment.finalOutput.score < 0.3) {
  await run(escalationAgent, text);
}

优点:可预测、成本较低
缺点:灵活性较差

并行

并发运行多个 Agent:

const [summary, keywords, entities] = await Promise.all([
  run(summarizerAgent, text),
  run(keywordAgent, text),
  run(entityAgent, text),
]);

模板:templates/text-agents/agent-parallel.ts

参考资料:references/agent-patterns.md


调试与追踪

启用详细日志记录:

process.env.DEBUG = '@openai/agents:*';

查看执行详情:

const result = await run(agent, input);

console.log('Tokens:', result.usage.totalTokens);
console.log('Turns:', result.history.length);
console.log('Current Agent:', result.currentAgent?.name);

模板:templates/shared/tracing-setup.ts


何时使用此技能

✅ 适用场景:

  • 构建多 Agent 工作流
  • 创建语音 AI 应用
  • 实现工具调用模式
  • 需要输入/输出验证(防护机制)
  • 需要人工审批关卡
  • 编排复杂 AI 任务
  • 部署到 Cloudflare Workers 或 Next.js

❌ 不适用场景:

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

生产环境检查清单

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

Token 效率

预计节省:约 60%

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

避免的错误:已记录的 9 个问题 = 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.2.1
最后验证日期:2025-10-26
技能作者:Jeremy Dawes (Jezweb)
生产环境测试:是

评论

支持 Markdown