如果您想尽快用 SDK 构建并运行一个智能体,可以从本页开始。下面的 TypeScript 和 Python 示例采用相同的思路:先定义一个智能体并运行它,再随着工作流的扩展逐步添加工具和专用智能体。
安装 SDK
创建项目,安装 SDK,并设置您的 API 密钥。
创建 API 密钥
# TypeScript
npm install @openai/agents zod
# Python
pip install openai-agents
export OPENAI_API_KEY=sk-...
创建并运行您的第一个智能体
先创建一个只负责一项任务的智能体,让它运行一轮。SDK 会调用模型,并返回一个包含最终输出和运行历史的结果对象。
创建并运行智能体
TypeScript
import { Agent, run } from "@openai/agents";
const agent = new Agent({
name: "History tutor",
instructions: "You answer history questions clearly and concisely.",
model: "gpt-6.2-astra",
});
const result = await run(agent, "When did the Roman Empire fall?");
console.log(result.finalOutput);您应该会在终端中看到一条简短的回答。跑通这个流程后,可以沿用现有结构,逐步添加功能,无需一开始就设计庞大的多智能体系统。
将状态传入下一轮
您也可以根据首次运行的结果,选择第二轮要使用的状态。
| 如果您希望 | 可以使用 |
|---|---|
| 在应用中保留完整历史记录 | result.history |
| 让 SDK 加载和保存历史记录 | 会话 |
| 让 OpenAI 管理继续对话所需的状态 | 由服务器管理的续接 ID |
| 恢复因等待审批或发生中断而暂停的运行 | result.stateinterruptions 配合使用 |
交接后,如果应由接手的专用智能体继续处理对话,请在下一轮复用 lastAgent
为智能体添加工具
为智能体扩展功能时,通常会先添加一个函数工具,或使用 OpenAI 托管的工具,例如网页搜索或文件搜索。
添加函数工具
TypeScript
import { Agent, run, tool } from "@openai/agents";
import { z } from "zod";
const historyFunFact = tool({
name: "history_fun_fact",
description: "Return a short history fact.",
parameters: z.object({}),
async execute() {
return "Sharks are older than trees.";
},
});
const agent = new Agent({
name: "History tutor",
instructions:
"Answer history questions clearly. Use history_fun_fact when it helps.",
tools: [historyFunFact],
});
const result = await run(
agent,
"Tell me something surprising about ancient life on Earth."
);
console.log(result.finalOutput);如果您需要使用托管工具、搜索可用工具或将智能体用作工具,请参阅通用指南使用工具。
添加专用智能体
接下来,常见的做法是将工作流拆分为不同任务,为每项任务指定专用智能体,再由路由智能体通过交接将任务分派给相应的智能体。
将任务分派给专用智能体
TypeScript
import { Agent, run } from "@openai/agents";
const historyTutor = new Agent({
name: "History tutor",
instructions: "Answer history questions clearly and concisely.",
});
const mathTutor = new Agent({
name: "Math tutor",
instructions: "Explain math step by step and include worked examples.",
});
const triageAgent = Agent.create({
name: "Homework triage",
instructions: "Route each homework question to the right specialist.",
handoffs: [historyTutor, mathTutor],
});
const result = await run(
triageAgent,
"Who was the first president of the United States?"
);
console.log(result.finalOutput);
console.log(result.lastAgent?.name);尽早查看追踪记录
在服务端按常规方式运行 SDK 时,SDK 会记录运行轨迹。首次运行成功后,请先打开追踪面板,检查模型调用、工具调用、任务交接和护栏的执行情况,再开始调整提示。
后续步骤
首次运行成功后,请根据您接下来想添加的功能,选择相应的指南。