跳转到内容

智能体

智能体是 OpenAI Agents SDK 的主要构建模块。Agent 是一个经过如下配置的大语言模型(LLM):

  • Instructions——告诉模型它是谁以及应如何响应的系统提示。
  • Model——要调用的 OpenAI 模型,以及任何可选的模型调优参数。
  • Tools——LLM 可调用以完成任务的函数或 API 列表。
Basic Agent definition
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 时,请使用本页。如果您正在决定多个智能体应如何协作,请阅读智能体编排

将本页作为智能体定义的中心页。根据您下一步需要做出的决策,跳转到相邻的对应指南。

如果您想要……接下来阅读
选择模型或配置存储的提示模型
为智能体添加能力工具
在管理者和交接之间做选择智能体编排
配置交接行为交接
运行轮次、流式传输事件或管理状态运行智能体
检查最终输出、运行项或恢复执行执行结果

本页其余部分将更详细地介绍 Agent 的每项功能。


Agent 构造函数接受一个配置对象。最常用的属性如下所示。

属性必需说明
name简短、便于人类阅读的标识符。
instructions系统提示(字符串函数——参见动态 instructions)。
promptOpenAI Responses API 的提示配置。可接受静态提示对象或函数。参见Prompt
handoffDescription当该智能体作为交接工具提供时使用的简短描述。
handoffs将对话委派给专门智能体。参见组合模式交接指南
model模型名称自定义的 Model 实现。
modelSettings调优参数(temperature、top_p 等)。参见模型。如果您需要的属性不在顶层,可以将其放在 providerData 下。
tools模型可调用的 Tool 实例数组。参见工具
mcpServers智能体可使用的 MCP 支持工具。参见MCP 集成
inputGuardrails应用于该智能体链中首次用户输入的护栏。参见护栏
outputGuardrails应用于该智能体最终输出的护栏。参见护栏
outputType返回结构化输出而非纯文本。参见输出类型执行结果
toolUseBehavior控制函数工具结果是回传给模型继续处理,还是直接结束运行。参见强制工具使用
resetToolChoice工具调用后将 toolChoice 重置为默认值(默认:true),以防止工具调用循环。参见强制工具使用
handoffOutputTypeWarningEnabled当交接输出类型不一致时发出警告(默认:true)。参见执行结果
Agent with tools
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() 的依赖注入对象。它会被传递给每个工具、护栏、交接等,适合用于存储状态或提供共享服务(数据库连接、用户元数据、功能开关等)。

Agent with context
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.',
});
// Later
import { run } from '@openai/agents';
const result = await run(agent, 'Find me a new pair of running shoes', {
context: { uid: 'abc', isProUser: true, fetchPurchases: async () => [] },
});

默认情况下,Agent 返回纯文本string)。如果您希望模型返回结构化对象,可以指定 outputType 属性。SDK 接受:

  1. Zod schema(z.object({...}))。
  2. 任何兼容 JSON schema 的对象。
Structured output with Zod
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,而不是纯文本。


有些智能体概念可直接映射到 OpenAI 平台概念,另一些则是在运行智能体时配置,而不是在定义智能体时配置。

SDK 概念OpenAI 指南适用时机
outputTypeStructured Outputs智能体应返回带类型的 JSON 或经 Zod 验证的对象,而不是文本。
tools / 托管工具Tools guide模型应执行搜索、检索、运行代码,或调用您的函数/工具。
conversationId / previousResponseIdConversation state您希望 OpenAI 在多轮之间持久化或串联对话状态。

conversationIdpreviousResponseId 是运行时控制项,不是 Agent 构造函数字段。当您需要这些 SDK 入口时,请使用运行智能体


当智能体参与更大的工作流时,最常出现的两个 SDK 入口是:

  1. 管理者(Agents as tools)——一个中心智能体负责整个对话,并调用以工具形式暴露的专门智能体。
  2. 交接——初始智能体在识别出用户请求后,将整个对话委派给某个专门智能体。

这两种方式是互补的。管理者为您提供一个统一位置来实施护栏或速率限制,而交接则让每个智能体专注于单一任务,而无需持续控制整个对话。关于设计权衡以及何时选择每种模式,请参见智能体编排

在这种模式下,管理者永远不会移交控制权——LLM 使用工具,而管理者对最终答案进行总结。更多内容请参见工具指南

Agents as tools
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.',
}),
],
});

使用交接时,分流智能体会路由请求,但一旦发生交接,专门智能体就会接管对话,直到生成最终输出。这能让提示更简短,也便于您独立分析每个智能体。更多信息请参见交接指南

Agent with handoffs
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 handoffs
const 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 控制的运行时警告。完整示例请参见执行结果指南


instructions 可以是函数,而不仅仅是字符串。该函数会接收当前的 RunContext 和 Agent 实例,并可返回字符串Promise<string>

Agent with dynamic instructions
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、版本或变量依赖于当前运行上下文时,这非常有用。

Agent with dynamic prompt
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 函数。


对于高级用例,您可以通过监听事件来观察 Agent 生命周期。

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 })
Agent with lifecycle hooks
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);
});

护栏允许您验证或转换用户输入和智能体输出。它们通过 inputGuardrailsoutputGuardrails 数组进行配置。详情请参见护栏指南


需要现有智能体的一个稍作修改的版本?使用 clone() 方法,它会返回一个全新的 Agent 实例。

Cloning Agents
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.',
});

提供工具并不保证 LLM 会调用它。您可以通过 modelSettings.toolChoice 强制工具使用:

  1. 'auto'(默认)——由 LLM 决定是否使用工具。
  2. 'required'——LLM 必须调用某个工具(可自行选择调用哪一个)。
  3. 'none'——LLM 不得调用工具。
  4. 指定某个工具名称,例如 'calculator'——LLM 必须调用该特定工具。

当可用工具是在 OpenAI Responses 中的 computerTool() 时,toolChoice: 'computer' 有特殊含义:它会强制使用 GA 内置的计算机工具,而不是将 'computer' 视为普通函数名。对于旧版集成,SDK 也接受兼容预览版的计算机选择器,但新代码应优先使用 'computer'。如果没有可用的计算机工具,该字符串会像其他函数工具名称一样处理。

Forcing tool use
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' },
});

当您使用延迟加载的 Responses 工具(例如 toolNamespace())、设置了 deferLoading: true 的函数工具,或设置了 deferLoading: true 的托管 MCP 工具时,请将 modelSettings.toolChoice 保持为 'auto'。SDK 会拒绝通过名称强制调用延迟工具或内置的 tool_search 辅助工具,因为模型需要自行决定何时加载这些定义。完整的 tool-search 设置请参见工具指南

工具调用后,SDK 会自动将 toolChoice 重置回 'auto'。这可防止模型陷入反复尝试调用工具的无限循环。您可以通过 resetToolChoice 标志或配置 toolUseBehavior 来覆盖此行为:

  • 'run_llm_again'(默认)——使用工具结果再次运行 LLM。
  • 'stop_on_first_tool'——将第一个工具结果视为最终答案。
  • { stopAtToolNames: ['my_tool'] }——当调用了列出的任意工具时停止。
  • (context, toolResults) => ...——返回运行是否应结束的自定义函数。
const agent = new Agent({
...,
toolUseBehavior: 'stop_on_first_tool',
});

注意:toolUseBehavior 仅适用于函数工具。托管工具始终会返回给模型进行处理。


  • 模型:模型选择、存储提示和提供方配置。
  • 工具:函数工具、托管工具、MCP 和 agent.asTool()
  • 智能体编排:在管理者、交接和代码驱动的编排之间做选择。
  • 交接:配置专门智能体委派。
  • 运行智能体:执行轮次、流式传输和对话状态。
  • 执行结果finalOutput、运行项和恢复状态。
  • 在侧边栏中 @openai/agents 下浏览完整的 TypeDoc 参考。