English
主导航

旧版 API

快速入门

使用 Agents SDK 在 TypeScript 或 Python 中构建你的第一个 Agent。

当你希望以最短路径构建一个基于 SDK 的可用 Agent 时,请参考本页。以下示例在 TypeScript 和 Python 中使用了相同的高级概念:定义一个 Agent,运行它,然后随着工作流的发展逐步添加工具和专业 Agent。

安装 SDK

创建一个项目,安装 SDK,并设置你的 API 密钥。

创建 API 密钥

1
2
3
4
5
6
7
# TypeScript
npm install @openai/agents zod

# Python
pip install openai-agents

export OPENAI_API_KEY=sk-...

创建并运行你的第一个 Agent

从一个专注的单个 Agent 和单次轮次开始。SDK 会处理模型调用,并返回一个包含最终输出和运行历史的结果对象。

创建并运行 Agent
1
2
3
4
5
6
7
8
9
10
11
import { Agent, run } from "@openai/agents";

const agent = new Agent({
  name: "History tutor",
  instructions:
    "You answer history questions clearly and concisely.",
  model: "gpt-5.5",
});

const result = await run(agent, "When did the Roman Empire fall?");
console.log(result.finalOutput);

你应该会在终端中看到一个简明的答案。一旦这个循环能正常运行,请保持相同的结构并逐步增加功能,而不是一开始就设计庞大的多 Agent 架构。

将状态带入下一轮次

第一次运行的结果也是你决定第二轮应使用什么状态的依据。

如果你想起始项
在应用程序中保留完整历史result.history
让 SDK 为你加载和保存历史记录A session
让 OpenAI 管理延续状态A server-managed continuation ID
恢复因等待批准或中断而暂停的运行result.state,连同 interruptions

在交接之后,复用 lastAgent 以便在该专业 Agent 应保持控制权时用于下一轮次。

为 Agent 提供工具

你添加的第一个功能通常是函数工具或托管的 OpenAI 工具(例如网页搜索或文件搜索)。

添加函数工具
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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);

当你需要托管工具、工具搜索或“Agent 作为工具 (agents-as-tools)”时,请使用共享的 使用工具 指南。

添加专业 Agent

常见的下一步是将工作流拆分给多个专业 Agent,并让路由器通过交接 (handoffs) 将任务委派给它们。

路由到专业 Agent
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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 路径包含追踪功能。在首次运行成功后,立即打开 跟踪面板 以检查模型调用、工具调用、交接和护栏,然后再开始调整提示词。

后续步骤

首次运行成功后,请继续阅读与你下一步想要添加的功能相匹配的指南。