openai-agents
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseOpenAI Agents SDK Skill
OpenAI Agents SDK 技能包
Complete skill for building AI applications with OpenAI Agents SDK (JavaScript/TypeScript), covering text agents, realtime voice agents, multi-agent workflows, and production deployment patterns.
使用OpenAI Agents SDK(JavaScript/TypeScript)构建AI应用的完整技能包,涵盖文本Agent、实时语音Agent、多Agent工作流以及生产部署模式。
Quick Start
快速开始
Installation
安装
bash
bun add @openai/agents zod@3
bun add @openai/agents-realtime # For voice agentsSet environment variable:
bash
export OPENAI_API_KEY="your-api-key"bash
bun add @openai/agents zod@3
bun add @openai/agents-realtime # 用于语音Agent设置环境变量:
bash
export OPENAI_API_KEY="your-api-key"Basic Text Agent
基础文本Agent
typescript
import { Agent, run, tool } from '@openai/agents';
import { z } from 'zod';
const agent = new Agent({
name: 'Assistant',
instructions: 'You are helpful.',
tools: [tool({
name: 'get_weather',
parameters: z.object({ city: z.string() }),
execute: async ({ city }) => `Weather in ${city}: sunny`,
})],
model: 'gpt-4o-mini',
});
const result = await run(agent, 'What is the weather in SF?');typescript
import { Agent, run, tool } from '@openai/agents';
import { z } from 'zod';
const agent = new Agent({
name: 'Assistant',
instructions: 'You are helpful.',
tools: [tool({
name: 'get_weather',
parameters: z.object({ city: z.string() }),
execute: async ({ city }) => `Weather in ${city}: sunny`,
})],
model: 'gpt-4o-mini',
});
const result = await run(agent, 'What is the weather in SF?');Voice Agent & Multi-Agent
语音Agent与多Agent
typescript
// Voice agent
const voiceAgent = new RealtimeAgent({
voice: 'alloy',
model: 'gpt-4o-realtime-preview',
});
// Browser session
const session = new RealtimeSession(voiceAgent, {
apiKey: sessionApiKey, // From backend!
transport: 'webrtc',
});
// Multi-agent handoffs
const triageAgent = Agent.create({
handoffs: [billingAgent, techAgent],
});17 Templates: directory has production-ready examples for all patterns.
templates/typescript
// 语音Agent
const voiceAgent = new RealtimeAgent({
voice: 'alloy',
model: 'gpt-4o-realtime-preview',
});
// 浏览器会话
const session = new RealtimeSession(voiceAgent, {
apiKey: sessionApiKey, // 从后端获取!
transport: 'webrtc',
});
// 多Agent移交
const triageAgent = Agent.create({
handoffs: [billingAgent, techAgent],
});17个模板:目录包含所有模式的生产就绪示例。
templates/Top 3 Critical Errors
三大关键错误
1. Zod Schema Type Errors
1. Zod Schema类型错误
Error: Type errors with tool parameters even when structurally compatible.
Workaround: Define schemas inline.
typescript
// ❌ Can cause type errors
parameters: mySchema
// ✅ Works reliably
parameters: z.object({ field: z.string() })Source: GitHub #188
错误:即使结构兼容,工具参数仍出现类型错误。
解决方法:内联定义Schema。
typescript
// ❌ 可能导致类型错误
parameters: mySchema
// ✅ 可靠运行
parameters: z.object({ field: z.string() })来源:GitHub #188
2. MCP Tracing Errors
2. MCP追踪错误
Error: "No existing trace found" with MCP servers.
Workaround:
typescript
import { initializeTracing } from '@openai/agents/tracing';
await initializeTracing();Source: GitHub #580
错误:MCP服务器提示"No existing trace found"(未找到现有追踪)。
解决方法:
typescript
import { initializeTracing } from '@openai/agents/tracing';
await initializeTracing();来源:GitHub #580
3. MaxTurnsExceededError
3. MaxTurnsExceededError
Error: Agent loops infinitely.
Solution: Increase maxTurns or improve instructions:
typescript
const result = await run(agent, input, {
maxTurns: 20,
});
// Or improve instructions
instructions: `After using tools, provide a final answer.
Do not loop endlessly.`All 9 Errors: Load for complete error catalog with workarounds.
references/common-errors.md错误:Agent无限循环。
解决方案:增加maxTurns或优化指令:
typescript
const result = await run(agent, input, {
maxTurns: 20,
});
// 或优化指令
instructions: `使用工具后,提供最终答案。
请勿无限循环。`全部9种错误:加载查看完整错误目录及解决方法。
references/common-errors.mdWhen to Load References
何时加载参考资料
Load reference files when working on specific aspects of agent development:
在开发Agent的特定模块时加载参考文件:
Agent Patterns (references/agent-patterns.md
)
references/agent-patterns.mdAgent模式(references/agent-patterns.md
)
references/agent-patterns.mdLoad when:
- Designing multi-agent orchestration strategies
- Choosing between LLM-based vs code-based orchestration
- Implementing parallel agent execution
- Creating agents-as-tools patterns
- Need to understand when to use which orchestration pattern
在以下场景加载:
- 设计多Agent编排策略
- 在基于LLM与基于代码的编排之间做选择
- 实现并行Agent执行
- 创建Agent作为工具的模式
- 需要了解何时使用何种编排模式
Common Errors (references/common-errors.md
)
references/common-errors.md常见错误(references/common-errors.md
)
references/common-errors.mdLoad when:
- Debugging agent issues beyond the top 3 errors above
- Implementing comprehensive error handling
- Encountering: GuardrailExecutionError, ToolCallError, Schema Mismatch, Ollama integration, webSearchTool failures, Agent Builder export bugs
- Building production error recovery patterns
在以下场景加载:
- 调试超出上述三大错误的Agent问题
- 实现全面的错误处理
- 遇到:GuardrailExecutionError、ToolCallError、Schema不匹配、Ollama集成、webSearchTool故障、Agent Builder导出bug
- 构建生产级错误恢复模式
Realtime Transports (references/realtime-transports.md
)
references/realtime-transports.md实时传输(references/realtime-transports.md
)
references/realtime-transports.mdLoad when:
- Choosing between WebRTC vs WebSocket for voice agents
- Optimizing voice agent latency
- Debugging voice connection issues
- Understanding network/firewall requirements for voice
- Implementing custom audio sources/sinks
在以下场景加载:
- 为语音Agent选择WebRTC或WebSocket
- 优化语音Agent延迟
- 调试语音连接问题
- 了解语音功能的网络/防火墙要求
- 实现自定义音频源/接收器
Cloudflare Integration (references/cloudflare-integration.md
)
references/cloudflare-integration.mdCloudflare集成(references/cloudflare-integration.md
)
references/cloudflare-integration.mdLoad when:
- Deploying agents to Cloudflare Workers
- Understanding Workers limitations (CPU, memory, no voice)
- Implementing streaming in Workers
- Debugging Workers-specific issues
- Optimizing for Workers performance and costs
在以下场景加载:
- 将Agent部署到Cloudflare Workers
- 了解Workers限制(CPU、内存,不支持语音)
- 在Workers中实现流处理
- 调试Workers特定问题
- 优化Workers性能与成本
Official Links (references/official-links.md
)
references/official-links.md官方链接(references/official-links.md
)
references/official-links.mdLoad when:
- Need official documentation links
- Looking for examples or community resources
- Checking latest SDK versions
- Finding pricing information
- Need migration guides
在以下场景加载:
- 需要官方文档链接
- 寻找示例或社区资源
- 查看最新SDK版本
- 查找定价信息
- 需要迁移指南
Core Concepts Summary
核心概念总结
Agents: LLMs equipped with instructions and tools.
Tools: Functions with Zod schemas that agents can call automatically.
Handoffs: Multi-agent delegation where agents route tasks to specialists.
Guardrails: Input/output validation for safety (content filtering, PII detection).
Structured Outputs: Type-safe responses using Zod schemas.
Streaming: Real-time event streaming for progressive responses.
Human-in-the-Loop: Require approval for specific tool executions ().
requiresApproval: trueFor detailed examples, see templates in and .
templates/text-agents/templates/realtime-agents/Agents:配备指令与工具的大语言模型(LLM)。
Tools:带有Zod Schema的函数,Agent可自动调用。
Handoffs:多Agent委托,Agent将任务路由给专业Agent。
Guardrails:用于安全的输入/输出验证(内容过滤、PII检测)。
结构化输出:使用Zod Schema实现类型安全的响应。
流处理:实时事件流,用于渐进式响应。
人工介入流程(Human-in-the-Loop):特定工具执行需要批准()。
requiresApproval: true如需详细示例,请查看与中的模板。
templates/text-agents/templates/realtime-agents/Text Agents Quick Reference
文本Agent快速参考
typescript
// Basic
const result = await run(agent, 'Your question');
// Streaming
const stream = await run(agent, input, { stream: true });
// Structured output
const agent = new Agent({
outputType: z.object({ sentiment: z.enum([...]), confidence: z.number() }),
});Templates: (8 templates)
templates/text-agents/typescript
// 基础用法
const result = await run(agent, 'Your question');
// 流处理
const stream = await run(agent, input, { stream: true });
// 结构化输出
const agent = new Agent({
outputType: z.object({ sentiment: z.enum([...]), confidence: z.number() }),
});模板:(8个模板)
templates/text-agents/Realtime Voice Agents Quick Reference
实时语音Agent快速参考
typescript
const voiceAgent = new RealtimeAgent({
voice: 'alloy', // alloy, echo, fable, onyx, nova, shimmer
model: 'gpt-4o-realtime-preview',
});
const session = new RealtimeSession(voiceAgent, {
apiKey: sessionApiKey,
transport: 'webrtc', // or 'websocket'
});Voice handoff constraints: Cannot change voice/model during handoff.
Templates: (3 templates) | Details:
templates/realtime-agents/references/realtime-transports.mdtypescript
const voiceAgent = new RealtimeAgent({
voice: 'alloy', // alloy, echo, fable, onyx, nova, shimmer
model: 'gpt-4o-realtime-preview',
});
const session = new RealtimeSession(voiceAgent, {
apiKey: sessionApiKey,
transport: 'webrtc', // 或 'websocket'
});语音移交限制:移交过程中无法更改语音/模型。
模板:(3个模板)| 详情:
templates/realtime-agents/references/realtime-transports.mdFramework Integration Quick Reference
框架集成快速参考
Cloudflare Workers (Experimental)
Cloudflare Workers(实验性)
typescript
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,
}));
},
};Limitations: No realtime voice, CPU time limits (30s max), memory constraints (128MB).
Templates: (2 templates)
templates/cloudflare-workers/Details: Load for complete Workers guide.
references/cloudflare-integration.mdtypescript
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,
}));
},
};限制:不支持实时语音,CPU时间限制(最长30秒),内存限制(128MB)。
模板:(2个模板)
templates/cloudflare-workers/详情:加载查看完整Workers指南。
references/cloudflare-integration.mdNext.js App Router
Next.js App Router
typescript
// 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({ /* ... */ });
const result = await run(agent, message);
return NextResponse.json({ response: result.finalOutput });
}Templates: (2 templates)
templates/nextjs/typescript
// 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({ /* ... */ });
const result = await run(agent, message);
return NextResponse.json({ response: result.finalOutput });
}模板:(2个模板)
templates/nextjs/Guardrails & Human-in-the-Loop
防护机制与人工介入流程
typescript
// Input/output guardrails
const agent = new Agent({
inputGuardrails: [homeworkDetectorGuardrail],
outputGuardrails: [piiFilterGuardrail],
});
// Human approval
const tool = tool({
requiresApproval: true,
execute: async ({ amount }) => `Refunded $${amount}`,
});
// Handle approval loop
while (result.interruption?.type === 'tool_approval') {
result = (await promptUser(result.interruption))
? await result.state.approve(result.interruption)
: await result.state.reject(result.interruption);
}Templates: ,
templates/text-agents/agent-guardrails-*.tsagent-human-approval.tstypescript
// 输入/输出防护机制
const agent = new Agent({
inputGuardrails: [homeworkDetectorGuardrail],
outputGuardrails: [piiFilterGuardrail],
});
// 人工批准
const tool = tool({
requiresApproval: true,
execute: async ({ amount }) => `Refunded $${amount}`,
});
// 处理批准循环
while (result.interruption?.type === 'tool_approval') {
result = (await promptUser(result.interruption))
? await result.state.approve(result.interruption)
: await result.state.reject(result.interruption);
}模板:,
templates/text-agents/agent-guardrails-*.tsagent-human-approval.tsOrchestration Patterns Summary
编排模式总结
LLM-Based: Agent decides routing autonomously. Use for adaptive workflows.
Code-Based: Explicit control flow. Use for predictable, deterministic workflows.
Parallel: Run multiple agents concurrently. Use for independent tasks.
Agents as Tools: Wrap agents as tools for manager LLM. Use for specialist delegation.
Details: Load for comprehensive orchestration strategies with examples.
references/agent-patterns.mdTemplate:
templates/text-agents/agent-parallel.ts基于LLM:Agent自主决定路由。适用于自适应工作流。
基于代码:显式控制流。适用于可预测、确定性工作流。
并行模式:同时运行多个Agent。适用于独立任务。
Agent作为工具:将Agent包装为工具供管理LLM使用。适用于专业任务委托。
详情:加载查看带示例的全面编排策略。
references/agent-patterns.md模板:
templates/text-agents/agent-parallel.tsDebugging & Tracing
调试与追踪
typescript
process.env.DEBUG = '@openai/agents:*';
const result = await run(agent, input);
console.log('Tokens:', result.usage.totalTokens, 'Turns:', result.history.length);Template:
templates/shared/tracing-setup.tstypescript
process.env.DEBUG = '@openai/agents:*';
const result = await run(agent, input);
console.log('Tokens:', result.usage.totalTokens, 'Turns:', result.history.length);模板:
templates/shared/tracing-setup.tsProduction Checklist
生产环境检查清单
- Set as environment secret
OPENAI_API_KEY - Implement error handling for all agent calls
- Add guardrails for safety-critical applications
- Set reasonable to prevent runaway costs
maxTurns - Use where possible for cost efficiency
gpt-4o-mini - Implement rate limiting
- Log token usage for cost monitoring
- Test handoff flows thoroughly
- Never expose API keys to browsers (use session tokens)
- Enable tracing/observability for debugging
- 将设置为环境密钥
OPENAI_API_KEY - 为所有Agent调用实现错误处理
- 为安全关键型应用添加防护机制
- 设置合理的以避免失控成本
maxTurns - 尽可能使用以提高成本效率
gpt-4o-mini - 实现速率限制
- 记录Token使用情况以监控成本
- 彻底测试移交流程
- 切勿向浏览器暴露API密钥(使用会话令牌)
- 启用追踪/可观测性以方便调试
When to Use This Skill
何时使用此技能包
✅ Use when:
- Building multi-agent workflows
- Creating voice AI applications
- Implementing tool-calling patterns
- Requiring input/output validation (guardrails)
- Needing human approval gates
- Orchestrating complex AI tasks
- Deploying to Cloudflare Workers or Next.js
❌ Don't use when:
- Simple OpenAI API calls (use skill instead)
openai-api - Non-OpenAI models exclusively
- Production voice at massive scale (consider LiveKit Agents)
✅ 适用场景:
- 构建多Agent工作流
- 创建语音AI应用
- 实现工具调用模式
- 需要输入/输出验证(防护机制)
- 需要人工批准环节
- 编排复杂AI任务
- 部署到Cloudflare Workers或Next.js
❌ 不适用场景:
- 简单OpenAI API调用(改用技能包)
openai-api - 仅使用非OpenAI模型
- 大规模生产级语音应用(考虑LiveKit Agents)
Token Efficiency
Token效率
Estimated Savings: ~60%
| Task | Without Skill | With Skill | Savings |
|---|---|---|---|
| Multi-agent setup | ~12k tokens | ~5k tokens | 58% |
| Voice agent | ~10k tokens | ~4k tokens | 60% |
| Error debugging | ~8k tokens | ~3k tokens | 63% |
| Average | ~10k | ~4k | ~60% |
Errors Prevented: 9 documented issues = 100% error prevention
预估节省:~60%
| 任务 | 未使用技能包 | 使用技能包 | 节省比例 |
|---|---|---|---|
| 多Agent设置 | ~12k tokens | ~5k tokens | 58% |
| 语音Agent | ~10k tokens | ~4k tokens | 60% |
| 错误调试 | ~8k tokens | ~3k tokens | 63% |
| 平均 | ~10k | ~4k | ~60% |
避免的错误:9个已记录问题 = 100%错误预防
Templates Index
模板索引
Text Agents (8):
- - Simple agent with tools
agent-basic.ts - - Multi-agent triage
agent-handoffs.ts - - Zod schemas
agent-structured-output.ts - - Real-time events
agent-streaming.ts - - Input validation
agent-guardrails-input.ts - - Output filtering
agent-guardrails-output.ts - - HITL pattern
agent-human-approval.ts - - Concurrent execution
agent-parallel.ts
Realtime Agents (3):
9. - Voice setup
10. - React client
11. - Voice delegation
realtime-agent-basic.tsrealtime-session-browser.tsxrealtime-handoffs.tsFramework Integration (4):
12. - Cloudflare Workers
13. - Hono framework
14. - Next.js API
15. - Next.js voice
worker-text-agent.tsworker-agent-hono.tsapi-agent-route.tsapi-realtime-route.tsUtilities (2):
16. - Comprehensive errors
17. - Debugging
error-handling.tstracing-setup.ts文本Agent(8个):
- - 带工具的简单Agent
agent-basic.ts - - 多Agent分诊
agent-handoffs.ts - - Zod Schema
agent-structured-output.ts - - 实时事件
agent-streaming.ts - - 输入验证
agent-guardrails-input.ts - - 输出过滤
agent-guardrails-output.ts - - 人工介入流程模式
agent-human-approval.ts - - 并发执行
agent-parallel.ts
实时Agent(3个):
9. - 语音设置
10. - React客户端
11. - 语音委托
realtime-agent-basic.tsrealtime-session-browser.tsxrealtime-handoffs.ts框架集成(4个):
12. - Cloudflare Workers
13. - Hono框架
14. - Next.js API
15. - Next.js语音
worker-text-agent.tsworker-agent-hono.tsapi-agent-route.tsapi-realtime-route.ts工具类(2个):
16. - 全面错误处理
17. - 调试
error-handling.tstracing-setup.tsReferences
参考资料
- - Orchestration strategies (LLM vs code, parallel, agents-as-tools)
agent-patterns.md - - All 9 errors with workarounds and sources
common-errors.md - - WebRTC vs WebSocket comparison, latency, debugging
realtime-transports.md - - Workers setup, limitations, performance, costs
cloudflare-integration.md - - Documentation, GitHub, npm, community resources
official-links.md
- - 编排策略(LLM vs代码、并行、Agent作为工具)
agent-patterns.md - - 全部9种错误及解决方法与来源
common-errors.md - - WebRTC与WebSocket对比、延迟、调试
realtime-transports.md - - Workers设置、限制、性能、成本
cloudflare-integration.md - - 文档、GitHub、npm、社区资源
official-links.md
Official Resources
官方资源
- Docs: https://openai.github.io/openai-agents-js/
- GitHub: https://github.com/openai/openai-agents-js
- npm: https://www.npmjs.com/package/@openai/agents
- Issues: https://github.com/openai/openai-agents-js/issues
Version: SDK v0.3.3
Last Verified: 2025-11-21
Skill Author: Claude Skills Maintainers
Production Tested: Yes
- 文档: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.3.3
最后验证时间:2025-11-21
技能包作者:Claude Skills Maintainers
生产环境测试:已完成