关于 openai-agents
用于通过 OpenAI Agents SDK 构建 JavaScript 和 TypeScript 应用的技能,指导开发者创建文本与语音 Agent、调用工具、编排多 Agent、验证输入输出并部署。
主要功能
- 01文本与实时语音 Agent
- 02带模式生成的工具调用
- 03多 Agent 移交与编排
- 04输入和输出防护
- 05基于 Zod 的结构化输出
- 06部署与调试模板
适用场景
- 01构建可调用工具的文本 Agent
- 02在专业 Agent 间路由请求
- 03创建实时语音体验
- 04为 Agent 操作添加验证或人工审批
MCP 相关
该技能记录了使用 MCP 服务时的 MCP tracing 问题,并建议初始化 tracing。它没有说明 MCP 服务管理或向客户端提供的能力。
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ jackspace/ claudeskillz --skill openai-agents安装后在 Claude Code 中输入/openai-agents确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
LICENSEREADME.mdSKILL.json详细介绍
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.tstemplates/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.tstemplates/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.tstemplates/realtime-agents/realtime-session-browser.tsxtemplates/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.tstemplates/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.tstemplates/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 tokens | 58% |
| 语音 Agent | 约 10k tokens | 约 4k tokens | 60% |
| 错误调试 | 约 8k tokens | 约 3k tokens | 63% |
| 平均值 | 约 10k | 约 4k | 约 60% |
避免的错误:已记录的 9 个问题 = 100% 错误预防率
模板索引
文本 Agent(8 个):
agent-basic.ts- 带工具的简单 Agentagent-handoffs.ts- 多 Agent 分诊agent-structured-output.ts- Zod 架构agent-streaming.ts- 实时事件agent-guardrails-input.ts- 输入验证agent-guardrails-output.ts- 输出过滤agent-human-approval.ts- HITL 模式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 - 调试
参考资料
agent-patterns.md- 编排策略common-errors.md- 9 个错误及解决方法realtime-transports.md- WebRTC 与 WebSocketcloudflare-integration.md- Workers 限制official-links.md- 文档链接
官方资源
- 文档:https://openai.github.io/openai-agents-js/
- GitHub:https://github.com/openai/openai-agents-js
- npm:https://www.npmjs.com/package/@openai/agents
- 问题反馈:https://github.com/openai/openai-agents-js/issues
版本:SDK v0.2.1
最后验证日期:2025-10-26
技能作者:Jeremy Dawes (Jezweb)
生产环境测试:是