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 让你以轻量、易用、抽象最少的方式构建具备智能体能力的 AI 应用。它是我们之前 面向智能体的实验项目 Swarm 的面向生产的升级版本,并且也可用于 Python。Agents SDK 仅包含一小组基础组件:
- 智能体(Agents):配备 instructions 和 tools 的 LLM
- 交接(Handoffs):允许智能体将特定任务委派给其他智能体
- 护栏(Guardrails):用于对传入智能体的输入进行校验
结合 TypeScript,这些基础组件足以表达工具与智能体之间的复杂关系,帮助你在没有陡峭学习曲线的情况下构建真实世界的应用。此外,SDK 内置 追踪(tracing),便于可视化与调试你的智能体流程,还可以对其进行评估,甚至为你的应用微调模型。
为何使用 Agents SDK
Section titled “为何使用 Agents SDK”该 SDK 的两大设计原则:
- 功能足够丰富,值得使用;但基础组件足够精简,便于快速上手。
- 开箱即用体验优秀,同时又可精确自定义具体行为。
SDK 的主要特性包括:
- Agent loop:内置智能体循环,负责调用工具、将结果返回给 LLM,并循环直至 LLM 完成。
- TypeScript 优先:使用内建语言特性来编排与串联智能体,而无需学习新的抽象。
- 交接(Handoffs):在多个智能体之间进行协调与委派的强大能力。
- 护栏(Guardrails):与智能体并行运行输入校验与检查,如检查失败可提前中止。
- 函数工具(Function tools):将任意 TypeScript 函数变为工具,自动生成模式(schema)并提供基于 Zod 的校验。
- 追踪(Tracing):内置追踪,用于可视化、调试和监控你的工作流,并可使用 OpenAI 的评估、微调与蒸馏工具。
- 实时智能体(Realtime Agents):构建强大的语音智能体,包含自动打断检测、上下文管理、护栏等。
npm install @openai/agents zod@3Hello 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-...