Agents
Agents 是您应用的核心构建块。一个 Agent 是一个大型语言模型 (LLM),配置了指令和工具。
基本配置
您将配置的 Agent 最常见的属性是
name: 一个必需的字符串,用于标识您的 Agent。instructions: 也称为开发者消息或系统提示。model: 使用哪个 LLM,以及可选的model_settings来配置模型调整参数,如 temperature、top_p 等。tools: Agent 可以用来完成任务的工具。
from agents import Agent, ModelSettings, function_tool
@function_tool
def get_weather(city: str) -> str:
"""returns weather info for the specified city."""
return f"The weather in {city} is sunny"
agent = Agent(
name="Haiku agent",
instructions="Always respond in haiku form",
model="gpt-5-nano",
tools=[get_weather],
)
Context
Agents 在其 context 类型上是通用的。Context 是一种依赖注入工具:您创建并传递给 Runner.run() 的对象,该对象会传递给每个 Agent、工具、handoff 等,它充当 Agent 运行的依赖项和状态的集合。您可以提供任何 Python 对象作为 context。
@dataclass
class UserContext:
name: str
uid: str
is_pro_user: bool
async def fetch_purchases() -> list[Purchase]:
return ...
agent = Agent[UserContext](
...,
)
输出类型
默认情况下,Agents 产生纯文本 (即 str) 输出。如果您希望 Agent 产生特定类型的输出,可以使用 output_type 参数。一个常见的选择是使用 Pydantic 对象,但我们支持任何可以包装在 Pydantic TypeAdapter 中的类型 - dataclasses、lists、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 时,它会告诉模型使用 结构化输出 而不是常规的纯文本响应。
多Agent系统设计模式
设计多 Agent 系统有很多种方法,但我们通常看到两种广泛适用的模式
- 管理器 (Agents 作为工具):一个中央管理器/编排器调用专门的子 Agents 作为工具,并保留对对话的控制权。
- Handoffs:对等 Agents 将控制权移交给一个专门的 Agent,该 Agent接管对话。这是去中心化的。
请参阅 我们的构建 Agents 的实用指南 以获取更多详细信息。
管理器 (Agents 作为工具)
customer_facing_agent 处理所有用户交互,并调用作为工具公开的专门的子 Agents。请在 tools 文档中了解更多信息。
from agents import Agent
booking_agent = Agent(...)
refund_agent = Agent(...)
customer_facing_agent = Agent(
name="Customer-facing agent",
instructions=(
"Handle all direct user communication. "
"Call the relevant tools when specialized expertise is needed."
),
tools=[
booking_agent.as_tool(
tool_name="booking_expert",
tool_description="Handles booking questions and requests.",
),
refund_agent.as_tool(
tool_name="refund_expert",
tool_description="Handles refund questions and requests.",
)
],
)
交接
Handoffs 是 Agent 可以委托的子 Agents。当发生 handoff 时,被委托的 Agent 会收到对话历史记录并接管对话。这种模式能够实现模块化、专门的 Agents,它们擅长于单一任务。请在 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, hand off to the booking agent. "
"If they ask about refunds, hand off to the refund agent."
),
handoffs=[booking_agent, refund_agent],
)
动态指令
在大多数情况下,您可以在创建 Agent 时提供指令。但是,您也可以通过一个函数提供动态指令。该函数将接收 Agent 和 context,并且必须返回提示。同时接受常规函数和 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)
有时,您希望观察 Agent 的生命周期。例如,您可能希望记录事件,或者在某些事件发生时预取数据。您可以使用 hooks 属性挂接到 Agent 生命周期。继承 AgentHooks 类,并覆盖您感兴趣的方法。
Guardrails
Guardrails 允许您在 Agent 运行的同时,对用户输入进行检查/验证,并在 Agent 产生输出后对其进行验证。例如,您可以筛选用户的输入和 Agent 的输出,以检查其相关性。请在 guardrails 文档中了解更多信息。
克隆/复制 Agents
通过使用 Agent 上的 clone() 方法,您可以复制一个 Agent,并选择性地更改任何属性。
pirate_agent = Agent(
name="Pirate",
instructions="Write like a pirate",
model="gpt-5.2",
)
robot_agent = pirate_agent.clone(
name="Robot",
instructions="Write like a robot",
)
强制使用工具
提供工具列表并不总是意味着 LLM 会使用工具。您可以强制使用工具,方法是设置 ModelSettings.tool_choice。有效值是
auto,允许 LLM 决定是否使用工具。required,要求 LLM 使用工具(但它可以智能地决定使用哪个工具)。none,要求 LLM 不 使用工具。- 设置特定的字符串,例如
my_tool,要求 LLM 使用该特定工具。
from agents import Agent, Runner, function_tool, ModelSettings
@function_tool
def get_weather(city: str) -> str:
"""Returns weather info for the specified city."""
return f"The weather in {city} is sunny"
agent = Agent(
name="Weather Agent",
instructions="Retrieve weather details.",
tools=[get_weather],
model_settings=ModelSettings(tool_choice="get_weather")
)
工具使用行为
tool_use_behavior 参数在 Agent 配置中控制如何处理工具输出
"run_llm_again":默认值。工具运行后,LLM 处理结果以产生最终响应。"stop_on_first_tool":第一个工具调用的输出用作最终响应,无需进一步的 LLM 处理。
from agents import Agent, Runner, function_tool, ModelSettings
@function_tool
def get_weather(city: str) -> str:
"""Returns weather info for the specified city."""
return f"The weather in {city} is sunny"
agent = Agent(
name="Weather Agent",
instructions="Retrieve weather details.",
tools=[get_weather],
tool_use_behavior="stop_on_first_tool"
)
StopAtTools(stop_at_tool_names=[...]):如果调用了任何指定的工具,则停止,并使用其输出作为最终响应。
from agents import Agent, Runner, function_tool
from agents.agent import StopAtTools
@function_tool
def get_weather(city: str) -> str:
"""Returns weather info for the specified city."""
return f"The weather in {city} is sunny"
@function_tool
def sum_numbers(a: int, b: int) -> int:
"""Adds two numbers."""
return a + b
agent = Agent(
name="Stop At Stock Agent",
instructions="Get weather or sum numbers.",
tools=[get_weather, sum_numbers],
tool_use_behavior=StopAtTools(stop_at_tool_names=["get_weather"])
)
ToolsToFinalOutputFunction:一个自定义函数,用于处理工具结果并决定是停止还是继续使用 LLM。
from agents import Agent, Runner, function_tool, FunctionToolResult, RunContextWrapper
from agents.agent import ToolsToFinalOutputResult
from typing import List, Any
@function_tool
def get_weather(city: str) -> str:
"""Returns weather info for the specified city."""
return f"The weather in {city} is sunny"
def custom_tool_handler(
context: RunContextWrapper[Any],
tool_results: List[FunctionToolResult]
) -> ToolsToFinalOutputResult:
"""Processes tool results to decide final output."""
for result in tool_results:
if result.output and "sunny" in result.output:
return ToolsToFinalOutputResult(
is_final_output=True,
final_output=f"Final weather: {result.output}"
)
return ToolsToFinalOutputResult(
is_final_output=False,
final_output=None
)
agent = Agent(
name="Weather Agent",
instructions="Retrieve weather details.",
tools=[get_weather],
tool_use_behavior=custom_tool_handler
)
注意
为了防止无限循环,框架会自动在工具调用后将 tool_choice 重置为 "auto"。可以通过 agent.reset_tool_choice 配置此行为。无限循环的原因是工具结果被发送到 LLM,然后 LLM 由于 tool_choice 而生成另一个工具调用,以此类推。