OpenAI Agents SDK 快速开始

2026-11-06 16:09 更新

本页提供基于SDK运行智能体的最短入门路径。JavaScript与Python示例采用相同概念:定义智能体、运行它,再随工作流扩展加入工具和专项智能体。

安装SDK

创建项目、安装SDK,并设置API密钥。先创建API密钥:

来源示例 1(bash):

## [中文] 示例1:安装SDK。
## [中文] 分别安装JavaScript或Python的Agents SDK,并在应用终端将sk-...替换成实际API密钥;无需同时安装两种语言。
## JavaScript
npm install @openai/agents zod

## Python
pip install openai-agents

export OPENAI_API_KEY=sk-...

创建并运行第一个智能体

先运行一个职责明确的智能体、完成一轮任务。SDK处理模型调用,返回包含最终输出及运行历史的结果对象。

来源示例 2(javascript):

// [中文] 示例2:创建并运行第一个智能体。
// [中文] 历史老师指令要求清楚、简洁地回答历史问题;用户输入是“罗马帝国何时灭亡”。
// [中文] 调用模型后打印最终输出;回答与调用费用取决于实际运行,本地稿没有预置成功结果。
import { Agent, run } from "@openai/agents";

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

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

来源示例 3(python):

## [中文] 示例3:创建并运行第一个智能体。
## [中文] 历史老师指令要求清楚、简洁地回答历史问题;用户输入是“罗马帝国何时灭亡”。
## [中文] 调用模型后打印最终输出;回答与调用费用取决于实际运行,本地稿没有预置成功结果。
import asyncio

from agents import Agent, Runner

agent = Agent(
    name="History tutor",
    instructions="You answer history questions clearly and concisely.",
    model="gpt-6-astra",
)


async def main() -> None:
    result = await Runner.run(agent, "When did the Roman Empire fall?")
    print(result.final_output)


if __name__ == "__main__":
    asyncio.run(main())

终端应显示简洁回答。该循环能运行后,保持相同结构逐步添加能力,不必从庞大的多智能体设计起步。

将状态带入下一轮

第一次运行的结果,也用于决定第二轮采用什么状态:

目标 起点
应用保存完整历史 TypeScript的result.history或Python的result.to_input_list()
SDK代为加载和保存历史 会话(session)
OpenAI管理继续运行的状态 服务端管理的继续标识符
恢复因批准或其他中断暂停的运行 TypeScript的result.state或Python的result.to_state(),配合interruptions

发生交接后,若专项智能体应继续掌控下一轮,复用TypeScript的lastAgent或Python的last_agent。

为智能体提供工具

最先添加的能力往往是函数工具,或网页搜索、文件搜索等OpenAI托管工具。以下添加函数工具:

来源示例 4(javascript):

// [中文] 示例4:为智能体提供工具。
// [中文] 历史事实工具固定返回“鲨鱼比树木更古老”;指令要求清楚回答、合适时用history_fun_fact。
// [中文] 输入是“讲一件地球远古生命中令人惊讶的事”;函数无外部查询,最后打印模型回答。
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);

来源示例 5(python):

## [中文] 示例5:为智能体提供工具。
## [中文] 历史事实工具固定返回“鲨鱼比树木更古老”;指令要求清楚回答、合适时用history_fun_fact。
## [中文] 输入是“讲一件地球远古生命中令人惊讶的事”;函数无外部查询,最后打印模型回答。
import asyncio

from agents import Agent, Runner, function_tool


@function_tool
def history_fun_fact() -> str:
    """Return a short history fact."""
    return "Sharks are older than trees."


agent = Agent(
    name="History tutor",
    instructions="Answer history questions clearly. Use history_fun_fact when it helps.",
    tools=[history_fun_fact],
)


async def main() -> None:
    result = await Runner.run(
        agent,
        "Tell me something surprising about ancient life on Earth.",
    )
    print(result.final_output)


if __name__ == "__main__":
    asyncio.run(main())

托管工具、工具搜索和作为工具的智能体见使用工具。

添加专项智能体

常见的下一步是拆分专项职责,并通过路由智能体的交接机制委派:

来源示例 6(javascript):

// [中文] 示例6:添加专项智能体。
// [中文] 历史老师清楚简洁地回答历史题,数学老师逐步讲解并给出例题,分流智能体把作业交给合适专家。
// [中文] 输入询问“美国第一任总统是谁”;打印最终回答和最后接管的智能体名称。
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);

来源示例 7(python):

## [中文] 示例7:添加专项智能体。
## [中文] 历史老师清楚简洁地回答历史题,数学老师逐步讲解并给出例题,分流智能体把作业交给合适专家。
## [中文] 输入询问“美国第一任总统是谁”;打印最终回答和最后接管的智能体名称。
import asyncio

from agents import Agent, Runner

history_tutor = Agent(
    name="History tutor",
    handoff_description="Specialist for history questions.",
    instructions="Answer history questions clearly and concisely.",
)

math_tutor = Agent(
    name="Math tutor",
    handoff_description="Specialist for math questions.",
    instructions="Explain math step by step and include worked examples.",
)

triage_agent = Agent(
    name="Homework triage",
    instructions="Route each homework question to the right specialist.",
    handoffs=[history_tutor, math_tutor],
)


async def main() -> None:
    result = await Runner.run(
        triage_agent,
        "Who was the first president of the United States?",
    )
    print(result.final_output)
    print(result.last_agent.name)


if __name__ == "__main__":
    asyncio.run(main())

尽早检查追踪

正常服务端SDK路径包含追踪。第一次成功运行后,就到追踪控制台检查模型调用、工具调用、交接和护栏,再开始调提示词。

后续步骤

按下一项能力选择指南:

以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号