跳转至

快速入门

项目与虚拟环境的创建

你只需要执行一次。

mkdir my_project
cd my_project
python -m venv .venv

虚拟环境的激活

每次启动新的终端会话时都需要执行此操作。

在 macOS 或 Linux 上:

source .venv/bin/activate

在 Windows 上:

.venv\Scripts\activate

Agents SDK 的安装

pip install openai-agents # or `uv add openai-agents`, etc

OpenAI API 密钥的设置

如果你还没有密钥,请按照这些说明创建 OpenAI API 密钥。

这些命令会为当前终端会话设置密钥。

在 macOS 或 Linux 上:

export OPENAI_API_KEY=sk-...

在 Windows PowerShell 上:

$env:OPENAI_API_KEY = "sk-..."

在 Windows 命令提示符上:

set "OPENAI_API_KEY=sk-..."

首个智能体的创建

智能体由 instructions、名称以及特定模型等可选配置定义。

from agents import Agent

agent = Agent(
    name="History Tutor",
    instructions="You answer history questions clearly and concisely.",
)

首个智能体的运行

使用 Runner 执行智能体,并获取返回的 RunResult

import asyncio
from agents import Agent, Runner

agent = Agent(
    name="History Tutor",
    instructions="You answer history questions clearly and concisely.",
)

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

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

对于第二轮对话,你可以将 result.to_input_list() 传回 Runner.run(...),附加一个会话,或者使用 conversation_id / previous_response_id 复用 OpenAI 服务端管理的状态。运行智能体指南会比较这些方法。

可按以下经验法则选择:

如果你想要... 从...开始
完全手动控制和与提供商无关的历史记录 result.to_input_list()
由 SDK 为你加载和保存历史记录 session=...
由 OpenAI 管理的服务端延续 previous_response_idconversation_id

有关权衡取舍和确切行为,请参阅运行智能体

当任务主要存在于提示词、工具和对话状态中时,使用普通的 AgentRunner。如果智能体需要在隔离的工作区中检查或修改真实文件,请转到沙盒智能体快速入门

智能体工具的提供

你可以为智能体提供工具,用于查找信息或执行操作。

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():
    result = await Runner.run(
        agent,
        "Tell me something surprising about ancient life on Earth.",
    )
    print(result.final_output)


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

更多智能体的添加

在选择多智能体模式之前,请决定最终答案应由谁负责:

  • 任务转移:专家智能体会接管该轮对话中的相应部分。
  • Agents as tools:编排者保持控制,并将专家智能体作为工具调用。

本快速入门继续使用任务转移,因为这是最短的入门示例。有关管理者式模式,请参阅智能体编排工具:agents as tools

其他智能体也可以用同样的方式定义。handoff_description 会为路由智能体提供有关何时委派的额外上下文。

from agents import Agent

history_tutor_agent = Agent(
    name="History Tutor",
    handoff_description="Specialist agent for historical questions",
    instructions="You answer history questions clearly and concisely.",
)

math_tutor_agent = Agent(
    name="Math Tutor",
    handoff_description="Specialist agent for math questions",
    instructions="You explain math step by step and include worked examples.",
)

任务转移的定义

在智能体上,你可以定义一组可选的外部任务转移选项,供它在解决任务时选择。

triage_agent = Agent(
    name="Triage Agent",
    instructions="Route each homework question to the right specialist.",
    handoffs=[history_tutor_agent, math_tutor_agent],
)

智能体编排的运行

运行器会处理各个智能体的执行、所有任务转移以及所有工具调用。

import asyncio
from agents import Runner


async def main():
    result = await Runner.run(
        triage_agent,
        "Who was the first president of the United States?",
    )
    print(result.final_output)
    print(f"Answered by: {result.last_agent.name}")


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

参考代码示例

仓库包含相同核心模式的完整脚本:

追踪的查看

若要回顾智能体运行期间发生的情况,请前往 OpenAI Dashboard 中的追踪查看器,查看智能体运行的追踪。

后续步骤

了解如何构建更复杂的智能体式流程: