AI个人学习
和实操指南
豆包Marscode1

OpenAI Agents SDK:搭建多智能体协作工作流的Python框架

综合介绍

OpenAI Agents SDK 是 OpenAI 推出的一款轻量级开发工具,专为构建多智能体工作流设计。它基于 Python,简单易上手,支持开发者通过配置智能体(Agents)、任务切换(Handoffs)、安全验证(Guardrails)和运行追踪(Tracing)来实现复杂的自动化任务。比如,你可以用它打造一个能写代码的助手,或处理多语言交互的智能系统。它的亮点在于兼容所有支持 OpenAI Chat Completions API 格式的模型提供商,灵活性很强。官方提供了详细文档和示例代码,适合各种水平的开发者快速入门。

OpenAI Agents SDK:搭建多智能体协作工作流的Python框架-1


 

功能列表

  • 智能体定制:为语言模型设置指令、工具和限制,创建专属智能助手。
  • 任务切换:支持智能体间无缝切换任务,比如从英语助手转到西班牙语助手。
  • 安全验证:内置输入和输出检查,确保结果安全可靠。
  • 运行追踪:自动记录智能体运行过程,方便调试和优化。
  • 工具扩展:允许添加自定义工具,例如查询天气或处理特定任务。
  • 模型兼容:支持多种模型提供商,只需符合 OpenAI API 格式即可。

 

使用帮助

安装流程

要使用 OpenAI Agents SDK,首先需要搭建 Python 环境。以下是具体步骤:

  1. 创建虚拟环境
    在终端输入以下命令,创建一个独立的 Python 环境,避免与其他项目冲突:
python -m venv env

然后激活环境:

  • Windows 系统:env\Scripts\activate
  • Mac/Linux 系统:source env/bin/activate
  1. 安装 SDK
    激活环境后,运行以下命令安装 SDK:
pip install openai-agents
  1. 配置 API 密钥
    在运行代码前,需要设置 OpenAI API 密钥。在终端输入:
export OPENAI_API_KEY='你的密钥'

或者在代码中通过环境变量加载。注意保护密钥安全。

完成以上步骤后,你就可以开始使用这个工具了。

如何使用

OpenAI Agents SDK 的核心是 Agent 和 Runner 类。Agent 用于定义智能体的行为,Runner 负责执行并返回结果。以下是主要功能的详细操作说明。

1. 创建基础智能助手

想快速上手?试试这个简单的例子,让智能体写一首关于编程的俳句:

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)

操作步骤

  • 创建一个智能体,设置名称和指令。
  • 用 Runner.run_sync 同步运行,输入任务要求。
  • 运行后会输出类似结果:“代码中有代码,函数调用自己,无限循环舞。”

2. 实现任务切换

任务切换是 SDK 的特色功能,可以让多个智能体协作。比如处理多语言请求:

from agents import Agent, Runner
import asyncio
spanish_agent = Agent(name="Spanish agent", instructions="You only speak Spanish.")
english_agent = Agent(name="English agent", instructions="You only speak English.")
triage_agent = Agent(
name="Triage agent",
instructions="Handoff to the appropriate agent based on the language of the request.",
handoffs=[spanish_agent, english_agent],
)
async def main():
result = await Runner.run(triage_agent, input="Hola, ¿cómo estás?")
print(result.final_output)
if __name__ == "__main__":
asyncio.run(main())

操作步骤

  • 定义多个智能体,每个有特定指令。
  • 创建主智能体(triage_agent),并指定可切换的智能体。
  • 用 Runner.run 异步运行,输入西班牙语问题。
  • 主智能体会根据语言切换到 spanish_agent,返回类似:“¡Hola! Estoy bien, gracias por preguntar. ¿Y tú, cómo estás?”

3. 添加自定义工具

你可以用 function_tool 定义工具,让智能体调用外部功能。比如查询天气:

from agents import Agent, Runner, function_tool
@function_tool
def get_weather(city: str) -> str:
return f"The weather in {city} is sunny."
agent = Agent(
name="Weather agent",
instructions="You are a helpful agent.",
tools=[get_weather],
)
async def main():
result = await Runner.run(agent, input="What's the weather in Tokyo?")
print(result.final_output)
if __name__ == "__main__":
asyncio.run(main())

操作步骤

  • 定义一个函数,用 @function_tool 装饰。
  • 将工具加入智能体的 tools 参数。
  • 运行后,智能体会调用工具,返回:“The weather in Tokyo is sunny.”

4. 使用运行追踪

SDK 内置追踪功能,每次运行都会记录智能体的操作细节。你可以通过 result 对象查看运行过程,或者集成外部工具(如 Logfire)分析。默认无需额外设置即可使用。

5. 设置安全验证

安全验证(Guardrails)可以检查输入和输出。例如,防止用户让智能体做数学作业:

from agents import Agent, Runner, input_guardrail
from pydantic import BaseModel
class MathCheck(BaseModel):
is_math_homework: bool
reasoning: str
guardrail_agent = Agent(
name="Guardrail check",
instructions="Check if the user is asking you to do their math homework.",
output_type=MathCheck,
)
@input_guardrail
async def math_guardrail(ctx, agent, input):
result = await Runner.run(guardrail_agent, input)
return GuardrailFunctionOutput(
output_info=result.final_output,
tripwire_triggered=result.final_output.is_math_homework,
)
agent = Agent(
name="Support agent",
instructions="Help customers with their questions.",
input_guardrails=[math_guardrail],
)
async def main():
try:
await Runner.run(agent, "Can you solve 2x + 3 = 11?")
except Exception as e:
print("Guardrail stopped the request")

操作步骤

  • 定义一个守卫智能体,检查输入。
  • 用 @input_guardrail 创建守卫函数。
  • 将守卫加入主智能体。如果输入涉及数学作业,运行会中断。

操作流程详解

  • 智能体循环:调用 Runner.run() 时,SDK 会执行以下步骤:
    1. 调用语言模型,生成响应。
    2. 检查是否有工具调用或任务切换。
    3. 执行工具调用并记录结果。
    4. 如果有任务切换,跳转到新智能体。
    5. 循环直到生成最终输出,或达到 max_turns 上限。
  • 输出类型:如果设置了 output_type,智能体会生成指定类型的结构化输出;否则,第一次无工具调用或切换的响应即为最终输出。

使用建议

  • 调试:用追踪功能查看每步细节,快速定位问题。
  • 优化:根据任务需要设置 max_turns,避免循环过多。
  • 扩展:参考官方 examples 文件夹,探索更多用法。

官方文档:https://openai.github.io/openai-agents-python/

CDN1
未经允许不得转载:首席AI分享圈 » OpenAI Agents SDK:搭建多智能体协作工作流的Python框架

首席AI分享圈

首席AI分享圈专注于人工智能学习,提供全面的AI学习内容、AI工具和实操指导。我们的目标是通过高质量的内容和实践经验分享,帮助用户掌握AI技术,一起挖掘AI的无限潜能。无论您是AI初学者还是资深专家,这里都是您获取知识、提升技能、实现创新的理想之地。

联系我们
zh_CN简体中文