跳转到内容

运行智能体

智能体本身不会做任何事——你需要使用 Runner 类或 run() 实用函数来运行它们。

简单运行
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.

当你不需要自定义 runner 时,也可以使用 run() 实用函数,它会运行一个单例的默认 Runner 实例。

或者,你也可以创建自己的 runner 实例:

简单运行
import { Agent, Runner } from '@openai/agents';
const agent = new Agent({
name: 'Assistant',
instructions: 'You are a helpful assistant',
});
// You can pass custom configuration to the runner
const runner = new Runner();
const result = await runner.run(
agent,
'Write a haiku about recursion in programming.',
);
console.log(result.finalOutput);
// Code within the code,
// Functions calling themselves,
// Infinite loop's dance.

运行你的智能体后,你会收到一个执行结果对象,其中包含最终输出以及整个运行历史。

当你在 Runner 中使用 run 方法时,你需要传入一个起始智能体和输入。输入可以是字符串(被视为一条用户消息),也可以是输入项列表,即 OpenAI Responses API 中的条目。

runner 随后会运行一个循环:

  1. 使用当前输入调用当前智能体的模型。
  2. 检查 LLM 的响应。
    • 最终输出 → 返回。
    • 交接 → 切换到新智能体,保留累积的对话历史,回到 1。
    • 工具调用 → 执行工具,将结果追加到对话中,回到 1。
  3. 一旦达到 maxTurns,抛出 MaxTurnsExceededError

在应用启动时创建一个 Runner 并在请求之间复用。该实例存储全局配置,如模型提供方与追踪选项。只有在需要完全不同的设置时才创建另一个 Runner。对于简单脚本,你也可以调用 run(),它在内部使用默认 runner。

run() 方法的输入包括一个用于启动运行的初始智能体、此次运行的输入和一组选项。

输入可以是字符串(被视为一条用户消息)、输入项列表,或在你构建人机协作智能体时使用的 RunState 对象。

其他选项包括:

OptionDefaultDescription
streamfalse若为 true,调用将返回 StreamedRunResult 并在事件从模型到达时进行触发。
context转发到每个工具 / 护栏 / 交接的上下文对象。详见上下文管理
maxTurns10安全上限——达到时抛出 MaxTurnsExceededError
signal用于取消的 AbortSignal

流式传输允许你在 LLM 运行时额外接收流式事件。一旦流启动,StreamedRunResult 将包含关于此次运行的完整信息,包括所有新产生的输出。你可以使用 for await 循环遍历流式事件。详见流式传输

如果你要创建自己的 Runner 实例,可以传入一个 RunConfig 对象来配置 runner。

FieldTypePurpose
modelstring | Model为运行中的所有智能体强制指定特定模型。
modelProviderModelProvider解析模型名称——默认为 OpenAI 提供方。
modelSettingsModelSettings覆盖按智能体设置的全局调参参数。
handoffInputFilterHandoffInputFilter在执行交接时变换输入项(若交接本身未定义该过滤器)。
inputGuardrailsInputGuardrail[]应用于初始用户输入的护栏。
outputGuardrailsOutputGuardrail[]应用于最终输出的护栏。
tracingDisabledboolean完全禁用 OpenAI 追踪。
traceIncludeSensitiveDataboolean在仍然发出 span 的同时,将 LLM/工具的输入与输出排除在追踪之外。
workflowNamestring显示于 Traces 控制台——用于分组相关的运行。
traceId / groupIdstring手动指定 trace 或 group ID,而不是由 SDK 生成。
traceMetadataRecord<string, any>附加到每个 span 的任意元数据。

每次调用 runner.run()(或 run() 实用函数)代表你的应用层对话中的一个轮次。你可以自行决定向最终用户展示多少 RunResult 内容——有时只展示 finalOutput,有时展示每个生成的条目。

延续会话历史示例
import { Agent, run } from '@openai/agents';
import type { AgentInputItem } from '@openai/agents';
let thread: AgentInputItem[] = [];
const agent = new Agent({
name: 'Assistant',
});
async function userSays(text: string) {
const result = await run(
agent,
thread.concat({ role: 'user', content: text }),
);
thread = result.history; // Carry over history + newly generated items
return result.finalOutput;
}
await userSays('What city is the Golden Gate Bridge in?');
// -> "San Francisco"
await userSays('What state is it in?');
// -> "California"

参见聊天示例以获取交互式版本。

SDK 会抛出一小组可捕获的错误:

以上都继承自基础的 AgentsError 类,它可能提供 state 属性以访问当前运行状态。

下面是处理 GuardrailExecutionError 的示例代码:

护栏执行错误
import {
Agent,
run,
GuardrailExecutionError,
InputGuardrail,
InputGuardrailTripwireTriggered,
} from '@openai/agents';
import { z } from 'zod';
const guardrailAgent = new Agent({
name: 'Guardrail check',
instructions: 'Check if the user is asking you to do their math homework.',
outputType: z.object({
isMathHomework: z.boolean(),
reasoning: z.string(),
}),
});
const unstableGuardrail: InputGuardrail = {
name: 'Math Homework Guardrail (unstable)',
execute: async () => {
throw new Error('Something is wrong!');
},
};
const fallbackGuardrail: InputGuardrail = {
name: 'Math Homework Guardrail (fallback)',
execute: async ({ input, context }) => {
const result = await run(guardrailAgent, input, { context });
return {
outputInfo: result.finalOutput,
tripwireTriggered: result.finalOutput?.isMathHomework ?? false,
};
},
};
const agent = new Agent({
name: 'Customer support agent',
instructions:
'You are a customer support agent. You help customers with their questions.',
inputGuardrails: [unstableGuardrail],
});
async function main() {
try {
const input = 'Hello, can you help me solve for x: 2x + 3 = 11?';
const result = await run(agent, input);
console.log(result.finalOutput);
} catch (e) {
if (e instanceof GuardrailExecutionError) {
console.error(`Guardrail execution failed: ${e}`);
// If you want to retry the execution with different settings,
// you can reuse the runner's latest state this way:
if (e.state) {
try {
agent.inputGuardrails = [fallbackGuardrail]; // fallback
const result = await run(agent, e.state);
console.log(result.finalOutput);
} catch (ee) {
if (ee instanceof InputGuardrailTripwireTriggered) {
console.log('Math homework guardrail tripped');
}
}
}
} else {
throw e;
}
}
}
main().catch(console.error);

运行上述示例时,你将看到如下输出:

Guardrail execution failed: Error: Input guardrail failed to complete: Error: Something is wrong!
Math homework guardrail tripped