📢gitzw.com上线了,功能陆续更新中,如有问题或反馈请在下方反馈/建议中给我们留言。
30分钟内部署openai-agents-python多智能体工作流

30分钟内部署openai-agents-python多智能体工作流

📌 本文速覽

openai-agents-python是一个轻量级且强大的多智能体工作流框架,支持OpenAI Responses和Chat Completions API,以及100多个其他LLM。通过本教程,您将学习如何快速部署和使用openai-agents-python,实现多智能体工作流的自动化和优化。

🎯 进阶📖 9 章⏱ ≈37 分鐘讀完🔄 更新於 2026-07-07📅 資料截至 2026-07
源專案:github.com/openai/openai-agents-python★ 27,699

1. openai-agents-python简介和安装

我们要部署openai-agents-python多智能体工作流,首先需要了解openai-agents-python是什么,并且学会如何安装和使用它。通过本章,你将能够安装openai-agents-python,并运行第一个Sandbox Agent

要开始,我们需要确保Python环境已经设置好,并且Python版本是3.10或更高。然后,我们可以使用以下命令创建一个虚拟环境:

python -m venv .venv
source .venv/bin/activate  # On Windows: .venv\Scripts\activate

接着,我们可以安装openai-agents-python包:

pip install openai-agents

如果你需要语音支持,可以安装带有voice组的包:

pip install 'openai-agents[voice]'

如果你需要Redis会话支持,可以安装带有redis组的包:

pip install 'openai-agents[redis]'

现在,我们可以运行第一个Sandbox Agent了。Sandbox Agent是一个可以在隔离的工作空间中运行的智能体,我们可以使用以下代码创建一个Sandbox Agent:

from agents import Runner
from agents.run import RunConfig
from agents.sandbox import Manifest, SandboxAgent, SandboxRunConfig
from agents.sandbox.entries import GitRepo
from agents.sandbox.sandboxes import UnixLocalSandboxClient

agent = SandboxAgent(
    name="Workspace Assistant",
    instructions="Inspect the sandbox workspace before answering.",
    default_manifest=Manifest(entries={"repo": GitRepo(repo="openai/openai-agents-python", ref="main")}),
)

result = Runner.run_sync(
    agent,
    "Inspect the repo README and summarize what this project does.",
    # Run this agent on the local filesystem
    run_config=RunConfig(sandbox=SandboxRunConfig(client=UnixLocalSandboxClient())),
)
print(result.final_output)

这段代码创建了一个Sandbox Agent,名为"Workspace Assistant",并且可以在本地文件系统中运行。我们需要设置OPENAI_API_KEY环境变量,以便Sandbox Agent可以访问OpenAI API

如果你遇到任何问题,可以检查一下环境变量是否设置正确,或者查看openai-agents-python的文档以获取更多信息。

本章小结

  • 我们了解了openai-agents-python是什么,并且学会了如何安装它。
  • 我们创建了一个虚拟环境,并安装了openai-agents-python包。
  • 我们运行了第一个Sandbox Agent,并且了解了如何设置OPENAI_API_KEY环境变量。
  • 我们知道了如何使用Sandbox Agent在隔离的工作空间中运行智能体。

2. 定义和自定义Agent

我们要定义和自定义Agent,这是openai-agents-python的核心部分。首先,你需要确保已经安装了openai-agents包,并且有一个Python环境(Python 3.10或更高版本)。

前置条件

  • 已经安装openai-agents包
  • 有一个Python环境(Python 3.10或更高版本)
  • 设置了OPENAI_API_KEY环境变量

定义Agent

我们可以直接定义一个Agent:

from agents import Agent

agent = Agent(name="Assistant", instructions="You are a helpful assistant")

这定义了一个名为"Assistant"的Agent,具有"You are a helpful assistant"的指令。

自定义Agent

我们可以自定义Agent的指令和工具。例如:

from agents import Agent

agent = Agent(
    name="Assistant",
    instructions="You are a helpful assistant",
    tools=["tool1", "tool2"]
)

这定义了一个名为"Assistant"的Agent,具有"You are a helpful assistant"的指令和两个工具"tool1"和"tool2"。

运行Agent

我们可以使用Runner运行Agent:

from agents import Runner

result = Runner.run_sync(agent, "Write a haiku about recursion in programming.")
print(result.final_output)

这运行了Agent,并打印出最终的输出。

常见报错与排查办法

  • 如果遇到"OPENAI_API_KEY not set"的错误,需要设置OPENAI_API_KEY环境变量。
  • 如果遇到"Agent not defined"的错误,需要定义Agent。

小结

  • 定义Agent需要指定name和instructions
  • 自定义Agent可以添加tools和其他配置
  • 运行Agent需要使用Runner
  • 需要设置OPENAI_API_KEY环境变量
  • 需要定义Agent才能运行它

3. 使用Sandbox Agent进行工作流自动化

本章要解决的问题是如何使用Sandbox Agent进行工作流自动化,读完本章,你就能使用Sandbox Agent来自动化你的工作流程。

首先,我们需要确保已经安装了openai-agents-python库,如果没有安装,可以使用以下命令安装:

pip install openai-agents

或者使用uv工具安装:

uv init
uv add openai-agents

接下来,我们需要导入必要的模块

from agents import Runner
from agents.run import RunConfig
from agents.sandbox import Manifest, SandboxAgent, SandboxRunConfig
from agents.sandbox.entries import GitRepo
from agents.sandbox.sandboxes import UnixLocalSandboxClient

然后,我们可以创建一个Sandbox Agent:

agent = SandboxAgent(
    name="Workspace Assistant",
    instructions="Inspect the sandbox workspace before answering.",
    default_manifest=Manifest(entries={"repo": GitRepo(repo="openai/openai-agents-python", ref="main")}),
)

这个Sandbox Agent的名字是"Workspace Assistant",instructions是"Inspect the sandbox workspace before answering.",default_manifest是定义了一个Git仓库的manifest。

接着,我们可以运行这个Sandbox Agent:

result = Runner.run_sync(
    agent,
    "Inspect the repo README and summarize what this project does.",
    # Run this agent on the local filesystem
    run_config=RunConfig(sandbox=SandboxRunConfig(client=UnixLocalSandboxClient())),
)
print(result.final_output)

这个命令会运行Sandbox Agent,并输出最终的结果。

如果你遇到错误,可以检查一下是否设置了OPENAI_API_KEY环境变量。

记住一点,Sandbox Agent需要一个文件系统工作空间和沙箱生命周期,所以如果你的工作流程不需要这些,可以使用普通的Agent。

本章小结

  • 安装openai-agents-python库
  • 导入必要的模块
  • 创建一个Sandbox Agent
  • 运行Sandbox Agent
  • 检查OPENAI_API_KEY环境变量
  • 了解Sandbox Agent的特点和使用场景

4. 实现Agent之间的协作和手offs

实现Agent之间的协作和手offs是openai-agents-python的一个关键功能。我们先来看一下如何定义两个Agent之间的协作。

首先,我们需要定义两个Agent:

from agents import Agent

agent1 = Agent(name="Agent 1", instructions="You are a helpful assistant")
agent2 = Agent(name="Agent 2", instructions="You are a knowledgeable expert")

接下来,我们需要定义两个Agent之间的协作关系。我们可以使用handoffs参数来实现这一点:

from agents import Runner

result = Runner.run_sync(agent1, "Ask Agent 2 about the meaning of life", handoffs=[agent2])
print(result.final_output)

在这个例子中,agent1会将问题"Ask Agent 2 about the meaning of life"转发给agent2,然后agent2会对这个问题进行回答。

如果你遇到错误,可能是因为agent2没有正确配置。确保agent2instructions参数正确设置,并且agent2能够理解问题的内容。

我们也可以使用tools参数来实现Agent之间的协作。例如,我们可以定义一个工具来调用agent2的功能:

from agents import Tool

tool = Tool(name="Ask Agent 2", agent=agent2, instructions="Ask Agent 2 about {question}")

result = Runner.run_sync(agent1, "Ask Agent 2 about the meaning of life", tools=[tool])
print(result.final_output)

在这个例子中,agent1会使用tool来调用agent2的功能,然后agent2会对问题进行回答。

本章小结

  • 我们学习了如何定义两个Agent之间的协作关系使用handoffs参数
  • 我们学习了如何使用tools参数来实现Agent之间的协作
  • 我们需要确保Agent的instructions参数正确设置,并且能够理解问题的内容
  • 我们可以使用Runner.run_sync函数来运行Agent并获取结果

5. 配置和使用Tools、Guardrails和Sessions

配置和使用Tools、Guardrails和Sessions是openai-agents-python工作流中的关键步骤。我们先从配置Tools开始,Tools让agents能够执行特定的任务。

首先,你需要确保已经安装了openai-agents-python包。如果还没有安装,可以使用以下命令安装:

pip install openai-agents

接着,我们来定义一个简单的Agent,并配置一个Tool让它能够执行一个特定的任务。我们将使用以下代码:

from agents import Agent, Runner
from agents.tools import Tool

# 定义一个简单的Agent
agent = Agent(name="Assistant", instructions="You are a helpful assistant")

# 定义一个Tool
tool = Tool(name="Summarize", function=lambda text: text[:10])

# 配置Agent使用Tool
agent.tools = [tool]

# 运行Agent
result = Runner.run_sync(agent, "Write a long text and summarize it.")
print(result.final_output)

预期结果是Agent会输出一段被缩短的文本。

接下来,我们来配置Guardrails。Guardrails是可配置的安全检查,用于输入和输出验证。我们可以使用以下代码:

from agents import Agent, Runner
from agents.guardrails import Guardrail

# 定义一个简单的Agent
agent = Agent(name="Assistant", instructions="You are a helpful assistant")

# 定义一个Guardrail
guardrail = Guardrail(name="Length Check", function=lambda text: len(text) < 100)

# 配置Agent使用Guardrail
agent.guardrails = [guardrail]

# 运行Agent
result = Runner.run_sync(agent, "Write a long text.")
print(result.final_output)

预期结果是Agent会输出一段被截断的文本,因为Guardrail检查了输出文本的长度。

最后,我们来配置Sessions。Sessions是自动对话历史管理,用于跟踪Agent的运行历史。我们可以使用以下代码:

from agents import Agent, Runner
from agents.sessions import Session

# 定义一个简单的Agent
agent = Agent(name="Assistant", instructions="You are a helpful assistant")

# 定义一个Session
session = Session(agent=agent)

# 配置Agent使用Session
agent.session = session

# 运行Agent
result = Runner.run_sync(agent, "Write a text.")
print(result.final_output)

# 再次运行Agent
result = Runner.run_sync(agent, "Write another text.")
print(result.final_output)

预期结果是Agent会输出两段不同的文本,因为Session跟踪了Agent的运行历史。

本章小结

  • 配置Tools让Agent能够执行特定的任务
  • 配置Guardrails用于输入和输出验证
  • 配置Sessions用于跟踪Agent的运行历史
  • 使用这些配置可以让Agent更好地执行任务并跟踪运行历史。记住一点,配置这些组件需要根据具体的任务和需求来进行。

6. 运行和调试Agent

本章要解决的问题是如何运行和调试openai-agents-python中的Agent。通过本章,你将能够成功运行一个Agent,并对其进行调试。

在开始之前,确保你已经安装了openai-agents-python包,并且你的Python环境是3.10或更新的版本。如果你还没有安装,可以使用以下命令:

python -m venv .venv
source .venv/bin/activate  # On Windows: .venv\Scripts\activate
pip install openai-agents

或者,如果你熟悉uv,可以使用:

uv init
uv add openai-agents

现在,我们可以开始运行一个Agent了。首先,我们需要定义一个Agent。我们可以使用以下代码定义一个简单的Agent:

from agents import Agent, Runner

agent = Agent(name="Assistant", instructions="You are a helpful assistant")

这个Agent的名字是"Assistant",其指令是"You are a helpful assistant"。

接下来,我们可以使用Runner运行这个Agent。我们可以使用以下代码运行Agent:

result = Runner.run_sync(agent, "Write a haiku about recursion in programming.")
print(result.final_output)

这个代码运行了Agent,并传递了一个输入参数"Write a haiku about recursion in programming."。然后,它打印出了Agent的最终输出。

如果你遇到错误,可以检查一下你的OPENAI_API_KEY环境变量是否设置正确。同时,也可以检查一下你的Agent的定义是否正确。

我们也可以运行一个Sandbox Agent。Sandbox Agent是一个使用计算机环境来执行真实工作的Agent。我们可以使用以下代码定义一个Sandbox Agent:

from agents import Runner
from agents.run import RunConfig
from agents.sandbox import Manifest, SandboxAgent, SandboxRunConfig
from agents.sandbox.entries import GitRepo
from agents.sandbox.sandboxes import UnixLocalSandboxClient

agent = SandboxAgent(
    name="Workspace Assistant",
    instructions="Inspect the sandbox workspace before answering.",
    default_manifest=Manifest(entries={"repo": GitRepo(repo="openai/openai-agents-python", ref="main")}),
)

这个Sandbox Agent的名字是"Workspace Assistant",其指令是"Inspect the sandbox workspace before answering."。它使用了一个GitRepo来检出openai/openai-agents-python仓库的main分支。

然后,我们可以使用以下代码运行Sandbox Agent:

result = Runner.run_sync(
    agent,
    "Inspect the repo README and summarize what this project does.",
    # Run this agent on the local filesystem
    run_config=RunConfig(sandbox=SandboxRunConfig(client=UnixLocalSandboxClient())),
)
print(result.final_output)

这个代码运行了Sandbox Agent,并传递了一个输入参数"Inspect the repo README and summarize what this project does."。然后,它打印出了Sandbox Agent的最终输出。

本章小结

  • 我们学习了如何定义和运行一个Agent。
  • 我们了解了如何使用Runner运行一个Agent。
  • 我们学习了如何定义和运行一个Sandbox Agent。
  • 我们知道了如何检查和调试Agent的错误。

7. 优化和扩展openai-agents-python工作流

优化和扩展openai-agents-python工作流是一个关键步骤,能够帮助我们提高工作流的效率和可靠性。在这一章中,我们将学习如何优化和扩展openai-agents-python工作流,包括如何使用工具、守护rails和会话等功能。

首先,我们需要确保已经安装了openai-agents-python包,并且已经设置了Python环境。我们可以使用以下命令来安装openai-agents-python包:

pip install openai-agents

如果我们需要使用语音支持或Redis会话支持,我们可以使用以下命令来安装:

pip install 'openai-agents[voice]'
pip install 'openai-agents[redis]'

接下来,我们可以定义一个agent,并使用Runner来运行它。我们可以使用以下代码来定义一个agent:

from agents import Agent, Runner

agent = Agent(name="Assistant", instructions="You are a helpful assistant")

result = Runner.run_sync(agent, "Write a haiku about recursion in programming.")
print(result.final_output)

这段代码定义了一个名为"Assistant"的agent,并使用Runner来运行它。agent的instructions是"You are a helpful assistant",并且我们要求它写一首关于递归编程的俳句。

如果我们需要使用工具、守护rails和会话等功能,我们可以使用以下代码来定义一个agent:

from agents import Agent, Runner
from agents.tools import Tool
from agents.guardrails import Guardrail
from agents.sessions import Session

agent = Agent(name="Assistant", instructions="You are a helpful assistant")
tool = Tool(name=" calculator", func=lambda x: x**2)
guardrail = Guardrail(name="input validation", func=lambda x: x > 0)
session = Session(name="conversation history")

result = Runner.run_sync(agent, "Write a haiku about recursion in programming.", tools=[tool], guardrails=[guardrail], session=session)
print(result.final_output)

这段代码定义了一个名为"Assistant"的agent,并使用Runner来运行它。agent的instructions是"You are a helpful assistant",并且我们要求它写一首关于递归编程的俳句。我们还定义了一个工具、一个守护rail和一个会话,并将它们传递给Runner。

在优化和扩展openai-agents-python工作流时,我们需要注意以下几点:

  • 使用工具、守护rails和会话等功能来提高工作流的效率和可靠性。
  • 确保agent的instructions清晰明确,并且能够正确地执行任务。
  • 使用Runner来运行agent,并且能够正确地处理结果。

本章小结

  • 优化和扩展openai-agents-python工作流是一个关键步骤,能够帮助我们提高工作流的效率和可靠性。
  • 我们可以使用工具、守护rails和会话等功能来提高工作流的效率和可靠性。
  • 确保agent的instructions清晰明确,并且能够正确地执行任务。
  • 使用Runner来运行agent,并且能够正确地处理结果。

8. 实战:使用openai-agents-python解决实际问题

我们要解决实际问题了,直接上代码。首先,确保你已经安装了 openai-agents 包:

pip install openai-agents

如果你需要语音支持或 Redis 会话支持,分别使用以下命令:

pip install 'openai-agents[voice]'
pip install 'openai-agents[redis]'

现在,我们来创建一个简单的 Agent 来解决实际问题。假设我们要创建一个 Agent 来回答用户关于天气的提问。我们先定义一个 Agent 类:

from agents import Agent, Runner

agent = Agent(name="Weather Assistant", instructions="You are a weather assistant")

接着,我们使用 Runner 类来运行这个 Agent,并给它一个问题:

result = Runner.run_sync(agent, "What's the weather like today in Beijing?")
print(result.final_output)

这会输出一个答案,可能是这样的:

Today in Beijing, the weather is mostly sunny with a high of 22°C and a low of 12°C.

如果你遇到错误,检查一下你的 OPENAI_API_KEY 环境变量是否设置正确。

我们也可以使用 Sandbox Agent 来解决更复杂的问题。例如,创建一个 Sandbox Agent 来分析一个 Git 仓库的 README 文件:

from agents import Runner
from agents.run import RunConfig
from agents.sandbox import Manifest, SandboxAgent, SandboxRunConfig
from agents.sandbox.entries import GitRepo
from agents.sandbox.sandboxes import UnixLocalSandboxClient

agent = SandboxAgent(
    name="Workspace Assistant",
    instructions="Inspect the sandbox workspace before answering.",
    default_manifest=Manifest(entries={"repo": GitRepo(repo="openai/openai-agents-python", ref="main")}),
)

result = Runner.run_sync(
    agent,
    "Inspect the repo README and summarize what this project does.",
    run_config=RunConfig(sandbox=SandboxRunConfig(client=UnixLocalSandboxClient())),
)
print(result.final_output)

这会输出一个摘要,可能是这样的:

This project provides a Python SDK for building multi-agent workflows.

记住一点,Sandbox Agent 需要一个配置好的环境来运行,所以确保你已经设置好了 UnixLocalSandboxClient

本章小结

  • 我们创建了一个简单的 Agent 来回答用户关于天气的提问
  • 我们使用了 Sandbox Agent 来分析一个 Git 仓库的 README 文件
  • 我们需要设置 OPENAI_API_KEY 环境变量来使用 OpenAI API
  • 我们需要配置好环境来运行 Sandbox Agent

9. 高级主题:性能调优和源码解析

本章要解决的问题是如何优化和扩展openai-agents-python工作流,以及如何深入理解其源码。通过本章,读者可以学习到如何调优openai-agents-python的性能,如何解析其源码,并如何应用这些知识来解决实际问题。

要开始本章,需要确保已经安装了openai-agents-python,并且有基本的Python编程知识。同时,需要了解openai-agents-python的基本概念,包括Agent、Sandbox Agent、Tools、Guardrails和Sessions。

我们先来看看如何优化openai-agents-python的性能。首先,需要了解openai-agents-python的性能瓶颈在哪里。可以使用以下命令来分析性能:

pip install line_profiler

然后,可以使用以下代码来分析Agent的性能:

from agents import Agent, Runner
from line_profiler import LineProfiler

def run_agent():
    agent = Agent(name="Assistant", instructions="You are a helpful assistant")
    result = Runner.run_sync(agent, "Write a haiku about recursion in programming.")
    print(result.final_output)

profiler = LineProfiler()
profiler.add_function(run_agent)
profiler.run('run_agent()')
profiler.print_stats()

这将输出性能分析结果,帮助我们了解哪些部分需要优化。

接着,我们来看看如何解析openai-agents-python的源码。可以从以下命令开始:

git clone https://github.com/openai/openai-agents-python.git

然后,可以使用以下代码来解析Agent的源码:

from agents import Agent

print(Agent.__doc__)

这将输出Agent类的文档字符串,帮助我们了解其实现细节。

如果你遇到性能问题,可以尝试使用以下方法来优化:

  • 使用Sandbox Agent代替普通Agent,Sandbox Agent可以在隔离的环境中运行,减少性能损耗。
  • 使用Tools和Guardrails来优化Agent的行为,减少不必要的计算。
  • 使用Sessions来管理Agent的状态,减少重复计算。

如果你遇到源码解析问题,可以尝试使用以下方法来解决:

  • 查阅openai-agents-python的文档和源码,了解其实现细节。
  • 使用调试工具来跟踪代码的执行流程,了解其内部工作机制。
  • 使用测试用例来验证代码的正确性,确保其符合预期行为。

本章小结

  • 优化openai-agents-python的性能需要了解其性能瓶颈,并使用合适的工具和方法来优化。
  • 解析openai-agents-python的源码需要了解其实现细节,并使用合适的工具和方法来分析。
  • 使用Sandbox Agent、Tools、Guardrails和Sessions可以帮助优化Agent的行为和性能。
  • 使用调试工具和测试用例可以帮助验证代码的正确性和性能。

常見問題

问题:如何安装openai-agents-python?

安装openai-agents-python可以使用pip命令,首先需要设置Python环境(Python 3.10或更新版本),然后运行pip install openai-agents命令。如果需要语音支持,可以使用pip install 'openai-agents[voice]'命令,如果需要Redis会话支持,可以使用pip install 'openai-agents[redis]'命令。

问题:什么是Sandbox Agent?

Sandbox Agent是openai-agents-python中的一个概念,指的是在一个隔离的工作空间中运行的agent,具有manifest定义的文件和沙箱原生能力。Sandbox Agent可以用于需要在文件系统中执行任务的场景。

问题:如何运行第一个Sandbox Agent?

运行第一个Sandbox Agent需要导入必要的模块,创建一个SandboxAgent实例,配置运行参数,然后使用Runner.run_sync方法运行agent。具体代码示例如下:

from agents import Runner
from agents.run import RunConfig
from agents.sandbox import Manifest, SandboxAgent, SandboxRunConfig
from agents.sandbox.entries import GitRepo
from agents.sandbox.sandboxes import UnixLocalSandboxClient

agent = SandboxAgent(
    name="Workspace Assistant",
    instructions="Inspect the sandbox workspace before answering.",
    default_manifest=Manifest(entries={"repo": GitRepo(repo="openai/openai-agents-python", ref="main")}),
)

result = Runner.run_sync(
    agent,
    "Inspect the repo README and summarize what this project does.",
    # Run this agent on the local filesystem
    run_config=RunConfig(sandbox=SandboxRunConfig(client=UnixLocalSandboxClient())),
)
print(result.final_output)

问题:如何运行一个不需要沙箱的agent?

运行一个不需要沙箱的agent可以使用Agent类和Runner.run_sync方法。具体代码示例如下:

from agents import Agent, Runner

agent = Agent(name="Assistant", instructions="You are a helpful assistant")

result = Runner.run_sync(agent, "Write a haiku about recursion in programming.")
print(result.final_output)

问题:openai-agents-python支持哪些LLM模型?

openai-agents-python支持OpenAI Responses和Chat Completions API,以及100+其他LLM模型。

问题:如何配置agent的运行参数?

agent的运行参数可以通过RunConfig类配置,例如可以配置沙箱、工具、守护rail等参数。

问题:如何使用openai-agents-python进行多agent协作?

openai-agents-python提供了多agent协作的功能,可以通过Agent类和Runner.run_sync方法实现多agent之间的协作。具体代码示例请参考文档。

🔗 相關推薦

📦 相關專案