openai-agents

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

OpenAI 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 agents
Set 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:
templates/
directory has production-ready examples for all patterns.

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
references/common-errors.md
for complete error catalog with workarounds.

错误:Agent无限循环。
解决方案:增加maxTurns或优化指令:
typescript
const result = await run(agent, input, {
  maxTurns: 20,
});

// 或优化指令
instructions: `使用工具后,提供最终答案。
请勿无限循环。`
全部9种错误:加载
references/common-errors.md
查看完整错误目录及解决方法。

When to Load References

何时加载参考资料

Load reference files when working on specific aspects of agent development:
在开发Agent的特定模块时加载参考文件:

Agent Patterns (
references/agent-patterns.md
)

Agent模式(
references/agent-patterns.md

Load 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

Load 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

Load 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
)

Cloudflare集成(
references/cloudflare-integration.md

Load 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

Load 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: true
).
For detailed examples, see templates in
templates/text-agents/
and
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:
templates/text-agents/
(8 templates)

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() }),
});
模板
templates/text-agents/
(8个模板)

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:
templates/realtime-agents/
(3 templates) | Details:
references/realtime-transports.md

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', // 或 'websocket'
});
语音移交限制:移交过程中无法更改语音/模型。
模板
templates/realtime-agents/
(3个模板)| 详情
references/realtime-transports.md

Framework 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:
templates/cloudflare-workers/
(2 templates)
Details: Load
references/cloudflare-integration.md
for complete Workers guide.
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,
    }));
  },
};
限制:不支持实时语音,CPU时间限制(最长30秒),内存限制(128MB)。
模板
templates/cloudflare-workers/
(2个模板)
详情:加载
references/cloudflare-integration.md
查看完整Workers指南。

Next.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:
templates/nextjs/
(2 templates)

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/nextjs/
(2个模板)

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-*.ts
,
agent-human-approval.ts

typescript
// 输入/输出防护机制
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-*.ts
,
agent-human-approval.ts

Orchestration 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
references/agent-patterns.md
for comprehensive orchestration strategies with examples.
Template:
templates/text-agents/agent-parallel.ts

基于LLM:Agent自主决定路由。适用于自适应工作流。
基于代码:显式控制流。适用于可预测、确定性工作流。
并行模式:同时运行多个Agent。适用于独立任务。
Agent作为工具:将Agent包装为工具供管理LLM使用。适用于专业任务委托。
详情:加载
references/agent-patterns.md
查看带示例的全面编排策略。
模板
templates/text-agents/agent-parallel.ts

Debugging & 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.ts

typescript
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.ts

Production Checklist

生产环境检查清单

  • Set
    OPENAI_API_KEY
    as environment secret
  • Implement error handling for all agent calls
  • Add guardrails for safety-critical applications
  • Set reasonable
    maxTurns
    to prevent runaway costs
  • Use
    gpt-4o-mini
    where possible for cost efficiency
  • 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
    openai-api
    skill instead)
  • 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%
TaskWithout SkillWith SkillSavings
Multi-agent setup~12k tokens~5k tokens58%
Voice agent~10k tokens~4k tokens60%
Error debugging~8k tokens~3k tokens63%
Average~10k~4k~60%
Errors Prevented: 9 documented issues = 100% error prevention

预估节省:~60%
任务未使用技能包使用技能包节省比例
多Agent设置~12k tokens~5k tokens58%
语音Agent~10k tokens~4k tokens60%
错误调试~8k tokens~3k tokens63%
平均~10k~4k~60%
避免的错误:9个已记录问题 = 100%错误预防

Templates Index

模板索引

Text Agents (8):
  1. agent-basic.ts
    - Simple agent with tools
  2. agent-handoffs.ts
    - Multi-agent triage
  3. agent-structured-output.ts
    - Zod schemas
  4. agent-streaming.ts
    - Real-time events
  5. agent-guardrails-input.ts
    - Input validation
  6. agent-guardrails-output.ts
    - Output filtering
  7. agent-human-approval.ts
    - HITL pattern
  8. agent-parallel.ts
    - Concurrent execution
Realtime Agents (3): 9.
realtime-agent-basic.ts
- Voice setup 10.
realtime-session-browser.tsx
- React client 11.
realtime-handoffs.ts
- Voice delegation
Framework Integration (4): 12.
worker-text-agent.ts
- Cloudflare Workers 13.
worker-agent-hono.ts
- Hono framework 14.
api-agent-route.ts
- Next.js API 15.
api-realtime-route.ts
- Next.js voice
Utilities (2): 16.
error-handling.ts
- Comprehensive errors 17.
tracing-setup.ts
- Debugging

文本Agent(8个):
  1. agent-basic.ts
    - 带工具的简单Agent
  2. agent-handoffs.ts
    - 多Agent分诊
  3. agent-structured-output.ts
    - Zod Schema
  4. agent-streaming.ts
    - 实时事件
  5. agent-guardrails-input.ts
    - 输入验证
  6. agent-guardrails-output.ts
    - 输出过滤
  7. agent-human-approval.ts
    - 人工介入流程模式
  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
- 调试

References

参考资料

  1. agent-patterns.md
    - Orchestration strategies (LLM vs code, parallel, agents-as-tools)
  2. common-errors.md
    - All 9 errors with workarounds and sources
  3. realtime-transports.md
    - WebRTC vs WebSocket comparison, latency, debugging
  4. cloudflare-integration.md
    - Workers setup, limitations, performance, costs
  5. official-links.md
    - Documentation, GitHub, npm, community resources

  1. agent-patterns.md
    - 编排策略(LLM vs代码、并行、Agent作为工具)
  2. common-errors.md
    - 全部9种错误及解决方法与来源
  3. realtime-transports.md
    - WebRTC与WebSocket对比、延迟、调试
  4. cloudflare-integration.md
    - Workers设置、限制、性能、成本
  5. official-links.md
    - 文档、GitHub、npm、社区资源

Official Resources

官方资源


Version: SDK v0.3.3 Last Verified: 2025-11-21 Skill Author: Claude Skills Maintainers Production Tested: Yes

版本:SDK v0.3.3 最后验证时间:2025-11-21 技能包作者:Claude Skills Maintainers 生产环境测试:已完成