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 和 tools 的 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@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-...