OpenAI Agents SDK TypeScript
import { Agent, run } from '@openai/agents';
const agent = new Agent({ name: 'Assistant', instructions: 'You are a helpful assistant.',});
const result = await run( agent, 'Write a haiku about recursion in programming.',);
console.log(result.finalOutput);
import { RealtimeAgent, RealtimeSession } from '@openai/agents/realtime';
const agent = new RealtimeAgent({ name: 'Assistant', instructions: 'You are a helpful assistant.',});
// Automatically connects your microphone and audio output in the browser via WebRTC.const session = new RealtimeSession(agent);await session.connect({ apiKey: '<client-api-key>',});
适用于 TypeScript 的 OpenAI Agents SDK 让你以轻量、易用、几乎不引入抽象的方式构建智能体应用。它是我们先前 针对智能体的试验项目 Swarm 的生产级升级版本,并且也可用于 Python。Agents SDK 只有一小组基本组件:
- 智能体(Agents):配备 instructions 和工具的 LLM
- 交接(Handoffs):允许智能体将特定任务委托给其他智能体
- 护栏(Guardrails):用于验证传入智能体的输入
结合 TypeScript,这些基本组件足以表达工具与智能体之间的复杂关系,让你无需陡峭学习曲线即可构建 真实世界的应用。此外,SDK 内置了追踪(tracing),可用于可视化与调试你的智能体流程,并进一步评估它们,甚至为你的应用微调模型。
使用 Agents SDK 的理由
Section titled “使用 Agents SDK 的理由”该 SDK 遵循两条核心设计原则:
- 功能足够多,值得使用;但原语足够少,便于快速学习。
- 开箱即用效果很好,同时你可以精确自定义具体行为。
SDK 的主要特性如下:
- 智能体循环(Agent loop):内置循环,负责调用工具、将结果发送给 LLM,并循环直至 LLM 完成。
- TypeScript 优先(TypeScript-first):利用语言内置特性来编排与串联 智能体,而无需学习新的抽象。
- 交接(Handoffs):强大的能力,用于在多个智能体之间协调与委托。
- 护栏(Guardrails):与智能体并行运行输入验证与检查,如检查失败可提前中断。
- 函数工具(Function tools):将任意 TypeScript 函数变为工具,自动生成 schema,并使用 Zod 进行验证。
- 追踪(Tracing):内置追踪,便于可视化、调试和监控你的工作流,并可使用 OpenAI 的评估、微调与 蒸馏工具。
- 实时智能体(Realtime Agents):构建强大的语音智能体,包括自动打断 检测、上下文管理、护栏等。
npm install @openai/agents zod@3
Hello World 示例
Section titled “Hello World 示例”import { Agent, run } from '@openai/agents';
const agent = new Agent({ name: 'Assistant', instructions: 'You are a helpful assistant',});
const result = await run( agent, 'Write a haiku about recursion in programming.',);console.log(result.finalOutput);
// Code within the code,// Functions calling themselves,// Infinite loop's dance.
(如果要运行,请确保已设置 OPENAI_API_KEY
环境变量)
export OPENAI_API_KEY=sk-...