智能体
智能体是 OpenAI Agents SDK 的主要构建组件。智能体是经过以下配置的大语言模型(LLM):
- Instructions——告诉模型它是谁以及应如何响应的系统提示。
- 模型——要调用的 OpenAI 模型,以及任何可选的模型调优参数。
- 工具——LLM 可以调用以完成任务的函数或 API 列表。
import { Agent } from '@openai/agents';
const agent = new Agent({ name: 'Haiku Agent', instructions: 'Always respond in haiku form.', model: 'gpt-5.4', // optional – falls back to the default model});当您需要定义或自定义单个
Agent时,请使用此页面。如果您正在决定多个智能体应如何协作,请参阅智能体编排。
后续指南选择
Section titled “后续指南选择”将此页面作为定义智能体的中心,并根据接下来需要做出的决定,前往相应的指南。
| 如果您希望… | 接下来阅读 |
|---|---|
| 选择模型或配置已存储的提示 | 模型 |
| 为智能体添加功能 | 工具 |
| 为结构化数据选择验证库 | 模式验证 |
| 为智能体提供隔离的文件系统工作区 | 概念 |
| 在管理器与交接之间做出选择 | 智能体编排 |
| 配置交接行为 | 交接 |
| 运行轮次、流式传输事件或管理状态 | 运行智能体 |
| 在不使用实时服务的情况下测试智能体工作流 | 测试 |
| 检查最终输出、运行项或恢复执行 | 执行结果 |
本页其余部分将更详细地介绍智能体的各项功能。
Agent 构造函数接受单个配置对象。下面列出了最常用的属性。
| 属性 | 必需 | 说明 |
|---|---|---|
name | 是 | 简短且便于理解的标识符。 |
instructions | 是 | 系统提示(字符串或函数——请参阅动态 instructions)。 |
prompt | 否 | OpenAI Responses API 提示配置。接受静态提示对象或函数。请参阅提示。 |
handoffDescription | 否 | 此智能体作为交接工具提供时使用的简短说明。 |
handoffs | 否 | 将对话委派给专业智能体。请参阅组合模式和交接。 |
model | 否 | 模型名称或自定义 Model 实现。 |
modelSettings | 否 | 调优参数(temperature、top_p 等)。请参阅模型。如果所需属性不在顶层,可以将其放在 providerData 下。 |
tools | 否 | 模型可以调用的 Tool 实例数组。请参阅工具。 |
mcpServers | 否 | 为智能体提供工具的 MCP 服务器。请参阅 MCP 集成。 |
mcpConfig | 否 | 本地 MCP 工具的选项,例如严格模式、错误处理和带服务器前缀的工具名称。请参阅智能体级 MCP 配置。 |
inputGuardrails | 否 | 应用于此智能体链中首个用户输入的护栏。请参阅护栏。 |
outputGuardrails | 否 | 应用于此智能体最终输出的护栏。请参阅护栏。 |
outputType | 否 | 返回结构化输出而非纯文本。请参阅输出类型和执行结果。 |
toolUseBehavior | 否 | 控制 SDK 是将函数工具结果发回模型,还是将函数工具结果用作本次运行的最终输出。请参阅强制工具使用。 |
resetToolChoice | 否 | 在工具调用后将 toolChoice 重置为默认值(默认值:true),以防止工具使用循环。请参阅强制工具使用。 |
handoffOutputTypeWarningEnabled | 否 | 交接输出类型不同时发出警告(默认值:true)。请参阅执行结果。 |
import { Agent, tool } from '@openai/agents';import { z } from 'zod';
const getWeather = tool({ name: 'get_weather', description: 'Return the weather for a given city.', parameters: z.object({ city: z.string() }), async execute({ city }) { return `The weather in ${city} is sunny.`; },});
const agent = new Agent({ name: 'Weather bot', instructions: 'You are a helpful weather bot.', model: 'gpt-4.1', tools: [getWeather],});智能体的上下文类型使用泛型,即 Agent<TContext, TOutput>。上下文是由您创建并传递给 Runner.run() 的依赖注入对象。它会转发给每个工具、护栏和交接等组件,适合用于存储状态或提供共享服务(数据库连接、用户元数据、功能开关等)。
import { Agent } from '@openai/agents';
interface Purchase { id: string; uid: string; deliveryStatus: string;}interface UserContext { uid: string; isProUser: boolean;
// this function can be used within tools fetchPurchases(): Promise<Purchase[]>;}
const agent = new Agent<UserContext>({ name: 'Personal shopper', instructions: 'Recommend products the user will love.',});
// Laterimport { run } from '@openai/agents';
const result = await run(agent, 'Find me a new pair of running shoes', { context: { uid: 'abc', isProUser: true, fetchPurchases: async () => [] },});默认情况下,智能体返回纯文本(string)。如果希望模型返回结构化对象,可以指定 outputType 属性。SDK 接受:
- Zod 模式(
z.object({...}))。 - 支持转换为标准 JSON Schema 的 Standard Schema 值。
- 任何与 JSON Schema 兼容的对象。
import { Agent } from '@openai/agents';import { z } from 'zod';
const CalendarEvent = z.object({ name: z.string(), date: z.string(), participants: z.array(z.string()),});
const extractor = new Agent({ name: 'Calendar extractor', instructions: 'Extract calendar events from the supplied text.', outputType: CalendarEvent,});提供 outputType 后,SDK 会自动使用 structured outputs,而非纯文本。
Zod 和受支持的 Standard Schema 值会在本地验证解析后的输出,并保留其推断出的输出类型。原始 JSON Schema 用于描述模型约定,但解析后的结果仍为 unknown。有关 Standard Schema 示例和支持的验证边界,请参阅模式验证。
OpenAI 平台映射
Section titled “OpenAI 平台映射”部分智能体概念可以直接映射到 OpenAI 平台概念,其他概念则在运行智能体时配置,而非在定义智能体时配置。
| SDK 概念 | OpenAI 指南 | 适用场景 |
|---|---|---|
outputType | Structured Outputs | 智能体应返回带类型的 JSON 或经过模式验证的对象,而非文本。 |
tools / 托管工具 | 工具指南 | 模型应执行搜索、检索、代码执行,或调用您的函数或工具。 |
conversationId / previousResponseId | 对话状态 | 您希望 OpenAI 在不同轮次之间持久化或串联对话状态。 |
conversationId 和 previousResponseId 是运行时控制项,而不是 Agent 构造函数字段。需要使用这些 SDK 入口点时,请参阅运行智能体。
当智能体参与较大型工作流时,最常用的是以下两种 SDK 入口点:
- 管理器(agents as tools)——由一个中心智能体负责对话,并调用以工具形式公开的专业智能体。
- 交接——初始智能体识别用户请求后,将整个对话委派给专业智能体。
这两种方法可以互补。管理器让您可以在单一位置实施护栏或速率限制,而交接则让每个智能体专注于单项任务,无需继续控制对话。有关设计权衡以及各模式的适用场景,请参阅智能体编排。
管理器(agents as tools)
Section titled “管理器(agents as tools)”在此模式中,管理器绝不移交控制权——LLM 使用工具,而管理器汇总最终答案。更多信息请参阅工具。
import { Agent } from '@openai/agents';
const bookingAgent = new Agent({ name: 'Booking expert', instructions: 'Answer booking questions and modify reservations.',});
const refundAgent = new Agent({ name: 'Refund expert', instructions: 'Help customers process refunds and credits.',});
const customerFacingAgent = new Agent({ name: 'Customer-facing agent', instructions: 'Talk to the user directly. When they need booking or refund help, call the matching tool.', tools: [ bookingAgent.asTool({ toolName: 'booking_expert', toolDescription: 'Handles booking questions and requests.', }), refundAgent.asTool({ toolName: 'refund_expert', toolDescription: 'Handles refund questions and requests.', }), ],});使用交接时,分流智能体负责路由请求;但一旦发生交接,专业智能体便会接管对话,直至生成最终输出。这可以保持提示简短,并让您能够独立分析每个智能体。更多信息请参阅交接。
import { Agent } from '@openai/agents';
const bookingAgent = new Agent({ name: 'Booking Agent', instructions: 'Help users with booking requests.',});
const refundAgent = new Agent({ name: 'Refund Agent', instructions: 'Process refund requests politely and efficiently.',});
// Use Agent.create method to ensure the finalOutput type considers handoffsconst triageAgent = Agent.create({ name: 'Triage Agent', instructions: `Help the user with their questions. If the user asks about booking, hand off to the booking agent. If the user asks about refunds, hand off to the refund agent.`.trimStart(), handoffs: [bookingAgent, refundAgent],});如果交接目标可能返回不同的输出类型,请优先使用 Agent.create(...),而不是 new Agent(...)。这样,TypeScript 就能推断整个交接图中所有可能的 finalOutput 形状的联合类型,并避免由 handoffOutputTypeWarningEnabled 控制的运行时警告。有关端到端示例,请参阅执行结果。
高级配置与运行时控制
Section titled “高级配置与运行时控制”动态 instructions
Section titled “动态 instructions”instructions 可以是函数,而不是字符串。该函数接收当前 RunContext 和智能体实例,并且可以返回字符串或 Promise<string>。
import { Agent, RunContext } from '@openai/agents';
interface UserContext { name: string;}
function buildInstructions(runContext: RunContext<UserContext>) { return `The user's name is ${runContext.context.name}. Be extra friendly!`;}
const agent = new Agent<UserContext>({ name: 'Personalized helper', instructions: buildInstructions,});同步函数和 async 函数均受支持。
prompt 支持与 instructions 相同的回调形式,但返回的是提示配置对象,而不是字符串。当提示 ID、版本或变量取决于当前运行上下文时,此功能非常有用。
import { Agent, RunContext } from '@openai/agents';
interface PromptContext { customerTier: 'free' | 'pro';}
function buildPrompt(runContext: RunContext<PromptContext>) { return { promptId: 'pmpt_support_agent', version: '7', variables: { customer_tier: runContext.context.customerTier, }, };}
const agent = new Agent<PromptContext>({ name: 'Prompt-backed helper', prompt: buildPrompt,});只有使用 OpenAI Responses API 时才支持此功能。同步函数和 async 函数均受支持。
生命周期钩子
Section titled “生命周期钩子”对于高级用例,您可以通过监听事件来观察智能体的生命周期。
Agent 实例会为该特定智能体实例发出生命周期事件,而 Runner 会在整个运行过程中以单一事件流发出相同名称的事件。这对多智能体工作流非常有用,因为您可以在单一位置观察交接和工具调用。
共享的事件名称如下:
| 事件 | Agent 钩子参数 | Runner 钩子参数 |
|---|---|---|
agent_start | (context, agent, turnInput?) | (context, agent, turnInput?) |
agent_end | (context, output) | (context, agent, output) |
agent_handoff | (context, nextAgent) | (context, fromAgent, toAgent) |
agent_tool_start | (context, tool, { toolCall }) | (context, agent, tool, { toolCall }) |
agent_tool_end | (context, tool, result, { toolCall }) | (context, agent, tool, result, { toolCall }) |
import { Agent } from '@openai/agents';
const agent = new Agent({ name: 'Verbose agent', instructions: 'Explain things thoroughly.',});
agent.on('agent_start', (ctx, agent) => { console.log(`[${agent.name}] started`);});agent.on('agent_end', (ctx, output) => { console.log(`[agent] produced:`, output);});护栏允许您验证或转换用户输入和智能体输出。它们通过 inputGuardrails 和 outputGuardrails 数组进行配置。有关详细信息,请参阅护栏。
智能体克隆/复制
Section titled “智能体克隆/复制”需要现有智能体的轻微修改版本?请使用 clone() 方法,它会返回一个全新的 Agent 实例。
import { Agent } from '@openai/agents';
const pirateAgent = new Agent({ name: 'Pirate', instructions: 'Respond like a pirate – lots of “Arrr!”', model: 'gpt-5.4',});
const robotAgent = pirateAgent.clone({ name: 'Robot', instructions: 'Respond like a robot – be precise and factual.',});clone() 不会复制 tools、handoffs、mcpServers、inputGuardrails 或 outputGuardrails 等列表属性。当克隆配置省略其中某个属性时,原始智能体和克隆智能体会共享同一个数组,因此通过任一智能体修改该数组都会影响两者。若要让克隆智能体拥有自己的数组,请传入新数组,例如 tools: [...agent.tools, extraTool];该新数组中的条目仍是相同的工具或交接对象。将列表属性传为 undefined 也视为已提供该属性,并会从空列表开始,而不是继承原始数组。
强制工具使用
Section titled “强制工具使用”提供工具并不能保证 LLM 一定会调用工具。您可以通过 modelSettings.toolChoice 强制使用工具:
'auto'(默认值)——由 LLM 决定是否使用工具。'required'——LLM 必须调用工具(可以自行选择具体工具)。'none'——LLM 不得调用工具。- 指定工具名称,例如
'calculator'——LLM 必须调用该特定工具。
在 OpenAI Responses 中,当可用工具为 computerTool() 时,toolChoice: 'computer' 具有特殊含义:它会强制使用正式版(GA)内置计算机工具,而不是将 'computer' 视为普通函数名称。SDK 也接受与预览版兼容的计算机工具选择器,以支持较旧的集成,但新代码应优先使用 'computer'。如果没有可用的计算机工具,该字符串的行为与其他函数工具名称相同。
import { Agent, tool } from '@openai/agents';import { z } from 'zod';
const calculatorTool = tool({ name: 'Calculator', description: 'Use this tool to answer questions about math problems.', parameters: z.object({ question: z.string() }), execute: async (input) => { throw new Error('TODO: implement this'); },});
const agent = new Agent({ name: 'Strict tool user', instructions: 'Always answer using the calculator tool.', tools: [calculatorTool], modelSettings: { toolChoice: 'required' },});使用 toolNamespace()、带有 deferLoading: true 的函数工具,或带有 deferLoading: true 的托管 MCP 工具等延迟加载型 Responses 工具时,请将 modelSettings.toolChoice 保持为 'auto'。SDK 不允许按名称强制调用延迟加载工具或内置 tool_search 辅助工具,因为模型需要自行决定何时加载这些定义。有关完整的工具搜索配置,请参阅工具。
无限循环防护
Section titled “无限循环防护”工具调用后,SDK 会自动将 toolChoice 重置为 'auto'。这可以防止模型陷入反复尝试调用工具的无限循环。您可以通过 resetToolChoice 标志或配置 toolUseBehavior 来覆盖此行为:
'run_llm_again'(默认值)——使用工具结果再次运行 LLM。'stop_on_first_tool'——将第一个工具结果视为最终答案。{ stopAtToolNames: ['my_tool'] }——调用列表中的任一工具时停止。(context, toolResults) => ...——返回是否应结束运行的自定义函数。
import { Agent, tool } from '@openai/agents';import { z } from 'zod';
const calculatorTool = tool({ name: 'calculator', description: 'Add two numbers.', parameters: z.object({ left: z.number(), right: z.number() }), execute: async ({ left, right }) => left + right,});
const agent = new Agent({ name: 'Calculator agent', instructions: 'Use the calculator tool to answer arithmetic questions.', tools: [calculatorTool], toolUseBehavior: 'stop_on_first_tool',});注意:toolUseBehavior 仅适用于函数工具。托管工具始终会将结果返回给模型处理。