跳转至

智能体

Agents 智能体是您应用程序中的核心构建块。一个智能体是一个配置了指令和工具的大语言模型(LLM)。

基础配置

您最常配置的智能体属性包括:

  • instructions: 也称为开发者消息或系统提示。
  • model: 使用哪个LLM,以及可选的model_settings来配置模型调优参数如temperature、top_p等。
  • tools: 智能体可以用来完成任务的各种工具。
from agents import Agent, ModelSettings, function_tool

@function_tool
def get_weather(city: str) -> str:
    return f"The weather in {city} is sunny"

agent = Agent(
    name="Haiku agent",
    instructions="Always respond in haiku form",
    model="o3-mini",
    tools=[get_weather],
)

上下文

智能体是泛型于其context类型的。上下文是一个依赖注入工具:它是您创建并传递给Runner.run()的对象,会被传递给每个智能体、工具、交接等,作为智能体运行时的依赖和状态的集合。您可以提供任何Python对象作为上下文。

@dataclass
class UserContext:
    uid: str
    is_pro_user: bool

    async def fetch_purchases() -> list[Purchase]:
        return ...

agent = Agent[UserContext](
    ...,
)

输出类型

默认情况下,智能体产生纯文本(即str)输出。如果您希望智能体产生特定类型的输出,可以使用output_type参数。常见的选择是使用Pydantic对象,但我们支持任何可以被Pydantic TypeAdapter包装的类型 - 数据类、列表、TypedDict等。

from pydantic import BaseModel
from agents import Agent


class CalendarEvent(BaseModel):
    name: str
    date: str
    participants: list[str]

agent = Agent(
    name="Calendar extractor",
    instructions="Extract calendar events from text",
    output_type=CalendarEvent,
)

注意

当您传递output_type时,这会告诉模型使用结构化输出而不是常规的纯文本响应。

交接

Handoffs 交接是智能体可以委托的子智能体。您提供交接列表,智能体可以在相关时选择委托给它们。这是一种强大的模式,允许编排模块化、专门化的智能体,每个智能体都擅长单一任务。更多信息请参阅交接文档。

from agents import Agent

booking_agent = Agent(...)
refund_agent = Agent(...)

triage_agent = Agent(
    name="Triage agent",
    instructions=(
        "Help the user with their questions."
        "If they ask about booking, handoff to the booking agent."
        "If they ask about refunds, handoff to the refund agent."
    ),
    handoffs=[booking_agent, refund_agent],
)

动态指令

在大多数情况下,您可以在创建智能体时提供指令。但是,您也可以通过函数提供动态指令。该函数将接收智能体和上下文,并且必须返回提示。常规函数和async函数都被接受。

def dynamic_instructions(
    context: RunContextWrapper[UserContext], agent: Agent[UserContext]
) -> str:
    return f"The user's name is {context.context.name}. Help them with their questions."


agent = Agent[UserContext](
    name="Triage agent",
    instructions=dynamic_instructions,
)

生命周期事件/钩子

有时,您可能希望观察智能体的生命周期。例如,您可能希望记录事件,或在某些事件发生时预取数据。您可以使用hooks属性挂钩到智能体生命周期中。子类化AgentHooks类,并重写您感兴趣的方法。

防护栏

防护栏允许您在智能体运行的同时对用户输入进行检查/验证。例如,您可以筛选用户输入的相关性。更多信息请参阅防护栏文档。

克隆/复制智能体

通过在智能体上使用clone()方法,您可以复制一个智能体,并可选地更改您喜欢的任何属性。

pirate_agent = Agent(
    name="Pirate",
    instructions="Write like a pirate",
    model="o3-mini",
)

robot_agent = pirate_agent.clone(
    name="Robot",
    instructions="Write like a robot",
)

强制工具使用

提供工具列表并不总是意味着LLM会使用工具。您可以通过设置ModelSettings.tool_choice来强制使用工具。有效值为:

  1. auto,允许LLM决定是否使用工具。
  2. required,要求LLM必须使用工具(但可以智能地决定使用哪个工具)。
  3. none,要求LLM不使用工具。
  4. 设置特定字符串如my_tool,要求LLM使用该特定工具。

注意

为了防止无限循环,框架在工具调用后自动将tool_choice重置为"auto"。此行为可通过agent.reset_tool_choice配置。无限循环是因为工具结果被发送给LLM,然后由于tool_choice而生成另一个工具调用,如此循环往复。

如果您希望智能体在工具调用后完全停止(而不是继续自动模式),可以设置[Agent.tool_use_behavior="stop_on_first_tool"],这将直接使用工具输出作为最终响应,而不进行进一步的LLM处理。