英文文档原文详见 OpenAI Agents SDKhttps://openai.github.io/openai-agents-python/

本文是OpenAI-agents-sdk-python使用翻译软件翻译后的中文文档/教程。分多个帖子发布,帖子的目录如下:

(1) OpenAI 代理 SDK, 介绍及快速入门

(2)OpenAI agents sdk, agents,运行agents,结果,流,工具,交接​​​​​​​


目录

OpenAI Agents SDK介绍

为什么使用 Agents SDK

安装

Hello world 示例

快速入门

创建项目和虚拟环境

激活虚拟环境

安装 Agents SDK

设置 OpenAI API 密钥

创建您的第一个代理

添加更多代理

定义您的交接

运行代理业务流程

添加护栏

把它们放在一起

查看您的跟踪


OpenAI Agents SDK介绍

OpenAI Agents SDK 使您能够在轻量级、易于使用的包中构建agents AI 应用程序,抽象非常少。这是我们之前针对代理 Swarm 的实验的生产就绪升级。agents SDK 有一组非常小的基元:

  • agents,即配备说明和工具的 LLM
  • handoffs,允许代理将特定任务委派给其他代理
  • guiderail,用于验证代理的输入

与 Python 结合使用时,这些基元功能强大,足以表达工具和代理之间的复杂关系,并允许您构建真实世界的应用程序,而无需陡峭的学习曲线。此外,SDK 还附带了内置跟踪功能,可让您可视化和调试代理流,以及评估它们,甚至为您的应用程序微调模型。

为什么使用 Agents SDK

SDK 有两个驱动设计原则:

  1. 足够多的功能值得使用,但足够少的原语可以快速学习。
  2. 开箱即用,但您可以准确自定义发生的情况。

以下是 SDK 的主要功能:

  • 代理循环:内置的代理循环,用于处理调用工具、将结果发送到 LLM 并循环直到 LLM 完成。
  • Python 优先:使用内置语言功能来编排和链接代理,而无需学习新的抽象。
  • 交接:在多个座席之间进行协调和委派的强大功能。
  • 护栏:与代理并行运行输入验证和检查,如果检查失败,则提前中断。
  • 函数工具:将任何 Python 函数转换为工具,具有自动架构生成和 Pydantic 支持的验证功能。
  • 跟踪:内置跟踪,可让您可视化、调试和监控工作流程,以及使用 OpenAI 评估、微调和蒸馏工具套件。

安装

pip install openai-agents

Hello world 示例

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)

# Code within the code,
# Functions calling themselves,
# Infinite loop's dance.

(如果运行此命令,请确保设置 OPENAI_API_KEY 环境变量)

export OPENAI_API_KEY=sk-...

快速入门

创建项目和虚拟环境

您只需执行一次此作。

mkdir my_project
cd my_project
python -m venv .venv

激活虚拟环境

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

source .venv/bin/activate

安装 Agents SDK

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

设置 OpenAI API 密钥

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

export OPENAI_API_KEY=sk-...

创建您的第一个代理

代理使用说明、名称和可选配置(例如model_config)

from agents import Agent

agent = Agent(
    name="Math Tutor",
    instructions="You provide help with math problems. Explain your reasoning at each step and include examples",
)

添加更多代理

可以采用相同的方式定义其他代理。 为确定 Handoff 路由提供额外的上下文handoff_descriptions

from agents import Agent

history_tutor_agent = Agent(
    name="History Tutor",
    handoff_description="Specialist agent for historical questions",
    instructions="You provide assistance with historical queries. Explain important events and context clearly.",
)

math_tutor_agent = Agent(
    name="Math Tutor",
    handoff_description="Specialist agent for math questions",
    instructions="You provide help with math problems. Explain your reasoning at each step and include examples",
)

定义您的交接

在每个座席上,您可以定义一个传出交接选项清单,座席可以从中进行选择,以决定如何推进其任务。

triage_agent = Agent(
    name="Triage Agent",
    instructions="You determine which agent to use based on the user's homework question",
    handoffs=[history_tutor_agent, math_tutor_agent]
)

运行代理业务流程

让我们检查工作流程是否运行,以及分类代理是否在两个专业代理之间正确路由。

from agents import Runner

async def main():
    result = await Runner.run(triage_agent, "What is the capital of France?")
    print(result.final_output)

添加护栏

您可以定义要在输入或输出上运行的自定义护栏。

from agents import GuardrailFunctionOutput, Agent, Runner
from pydantic import BaseModel

class HomeworkOutput(BaseModel):
    is_homework: bool
    reasoning: str

guardrail_agent = Agent(
    name="Guardrail check",
    instructions="Check if the user is asking about homework.",
    output_type=HomeworkOutput,
)

async def homework_guardrail(ctx, agent, input_data):
    result = await Runner.run(guardrail_agent, input_data, context=ctx.context)
    final_output = result.final_output_as(HomeworkOutput)
    return GuardrailFunctionOutput(
        output_info=final_output,
        tripwire_triggered=not final_output.is_homework,
    )

把它们放在一起

让我们把它们放在一起,使用切换和输入护栏运行整个工作流程。

from agents import Agent, InputGuardrail,GuardrailFunctionOutput, Runner
from pydantic import BaseModel
import asyncio

class HomeworkOutput(BaseModel):
    is_homework: bool
    reasoning: str

guardrail_agent = Agent(
    name="Guardrail check",
    instructions="Check if the user is asking about homework.",
    output_type=HomeworkOutput,
)

math_tutor_agent = Agent(
    name="Math Tutor",
    handoff_description="Specialist agent for math questions",
    instructions="You provide help with math problems. Explain your reasoning at each step and include examples",
)

history_tutor_agent = Agent(
    name="History Tutor",
    handoff_description="Specialist agent for historical questions",
    instructions="You provide assistance with historical queries. Explain important events and context clearly.",
)


async def homework_guardrail(ctx, agent, input_data):
    result = await Runner.run(guardrail_agent, input_data, context=ctx.context)
    final_output = result.final_output_as(HomeworkOutput)
    return GuardrailFunctionOutput(
        output_info=final_output,
        tripwire_triggered=not final_output.is_homework,
    )

triage_agent = Agent(
    name="Triage Agent",
    instructions="You determine which agent to use based on the user's homework question",
    handoffs=[history_tutor_agent, math_tutor_agent],
    input_guardrails=[
        InputGuardrail(guardrail_function=homework_guardrail),
    ],
)

async def main():
    result = await Runner.run(triage_agent, "who was the first president of the united states?")
    print(result.final_output)

    result = await Runner.run(triage_agent, "what is life")
    print(result.final_output)

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

查看您的跟踪

要查看代理运行期间发生的情况,请导航到 OpenAI 控制面板中的 Trace 查看器以查看代理运行的跟踪。

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐