|
| 1 | +# 智能体 |
| 2 | + |
| 3 | +智能体是应用程序中的核心构建块。一个智能体是一个大型语言模型(LLM),配置了指令和工具。 |
| 4 | + |
| 5 | +## 基本配置 |
| 6 | + |
| 7 | +智能体最常用到的配置属性包括: |
| 8 | + |
| 9 | +- `name`: 一个必需的字符串,用于标识你的智能体。 |
| 10 | +- `instructions`: 也称为开发者消息或系统提示。 |
| 11 | +- `model`: 使用哪个LLM,以及可选的 `model_settings` 来配置模型调优参数如temperature、top_p等。 |
| 12 | +- `tools`: 智能体可以用来完成任务的工具。 |
| 13 | + |
| 14 | +```python |
| 15 | +from agents import Agent, ModelSettings, function_tool |
| 16 | + |
| 17 | +@function_tool |
| 18 | +def get_weather(city: str) -> str: |
| 19 | + """returns weather info for the specified city.""" |
| 20 | + return f"The weather in {city} is sunny" |
| 21 | + |
| 22 | +agent = Agent( |
| 23 | + name="Haiku agent", |
| 24 | + instructions="Always respond in haiku form", |
| 25 | + model="gpt-5-nano", |
| 26 | + tools=[get_weather], |
| 27 | +) |
| 28 | +``` |
| 29 | + |
| 30 | +## 上下文 |
| 31 | + |
| 32 | +智能体对于其 `context` 类型是通用的。上下文是一种依赖注入工具:它是你创建并传递给 `Runner.run()` 的对象,会传递给每个智能体、工具、交接等,作为智能体运行的依赖项和状态的容器。你可以提供任何Python对象作为上下文。 |
| 33 | + |
| 34 | +```python |
| 35 | +@dataclass |
| 36 | +class UserContext: |
| 37 | + name: str |
| 38 | + uid: str |
| 39 | + is_pro_user: bool |
| 40 | + |
| 41 | + async def fetch_purchases() -> list[Purchase]: |
| 42 | + return ... |
| 43 | + |
| 44 | +agent = Agent[UserContext]( |
| 45 | + ..., |
| 46 | +) |
| 47 | +``` |
| 48 | + |
| 49 | +## 输出类型 |
| 50 | + |
| 51 | +默认情况下,智能体会产生纯文本(即 `str`)输出。如果你想让智能体产生特定类型的输出,可以使用 `output_type` 参数。一个常见的选择是使用 [Pydantic](https://docs.pydantic.dev/) 对象,但我们支持任何可以包装在 Pydantic [TypeAdapter](https://docs.pydantic.dev/latest/api/type_adapter/) 中的类型 - 数据类、列表、TypedDict等。 |
| 52 | + |
| 53 | +```python |
| 54 | +from pydantic import BaseModel |
| 55 | +from agents import Agent |
| 56 | + |
| 57 | + |
| 58 | +class CalendarEvent(BaseModel): |
| 59 | + name: str |
| 60 | + date: str |
| 61 | + participants: list[str] |
| 62 | + |
| 63 | +agent = Agent( |
| 64 | + name="Calendar extractor", |
| 65 | + instructions="Extract calendar events from text", |
| 66 | + output_type=CalendarEvent, |
| 67 | +) |
| 68 | +``` |
| 69 | + |
| 70 | +!!! note |
| 71 | + |
| 72 | + 当你传递一个 `output_type` 时,这告诉模型使用 [结构化输出](https://platform.openai.com/docs/guides/structured-outputs) 而不是常规的纯文本响应。 |
| 73 | + |
| 74 | +## 多智能体系统设计模式 |
| 75 | + |
| 76 | +设计多智能体系统有很多方法,但我们通常看到两种广泛适用的模式: |
| 77 | + |
| 78 | +1. 管理器(智能体作为工具):一个中央管理器/编排器调用作为工具公开的专门子智能体,并保持对对话的控制。 |
| 79 | +2. 交接:对等智能体将控制权委托给一个专门的智能体,该智能体接管对话。这是分散式的。 |
| 80 | + |
| 81 | +更多详细信息请参见[我们的智能体构建实用指南](https://cdn.openai.com/business-guides-and-resources/a-practical-guide-to-building-agents.pdf)。 |
| 82 | + |
| 83 | +### 管理器(智能体作为工具) |
| 84 | + |
| 85 | +`customer_facing_agent` 处理所有用户交互,并调用作为工具公开的专门子智能体。更多详细信息请参见 [tools](tools.md#agents-as-tools) 文档。 |
| 86 | + |
| 87 | +```python |
| 88 | +from agents import Agent |
| 89 | + |
| 90 | +booking_agent = Agent(...) |
| 91 | +refund_agent = Agent(...) |
| 92 | + |
| 93 | +customer_facing_agent = Agent( |
| 94 | + name="Customer-facing agent", |
| 95 | + instructions=( |
| 96 | + "Handle all direct user communication. " |
| 97 | + "Call the relevant tools when specialized expertise is needed." |
| 98 | + ), |
| 99 | + tools=[ |
| 100 | + booking_agent.as_tool( |
| 101 | + tool_name="booking_expert", |
| 102 | + tool_description="Handles booking questions and requests.", |
| 103 | + ), |
| 104 | + refund_agent.as_tool( |
| 105 | + tool_name="refund_expert", |
| 106 | + tool_description="Handles refund questions and requests.", |
| 107 | + ) |
| 108 | + ], |
| 109 | +) |
| 110 | +``` |
| 111 | + |
| 112 | +### 交接 |
| 113 | + |
| 114 | +交接是智能体可以委托的子智能体。当发生交接时,被委托的智能体接收对话历史并接管对话。这种模式使得在单一任务上表现出色的模块化专门智能体成为可能。更多详细信息请参见 [handoffs](handoffs.md) 文档。 |
| 115 | + |
| 116 | +```python |
| 117 | +from agents import Agent |
| 118 | + |
| 119 | +booking_agent = Agent(...) |
| 120 | +refund_agent = Agent(...) |
| 121 | + |
| 122 | +triage_agent = Agent( |
| 123 | + name="Triage agent", |
| 124 | + instructions=( |
| 125 | + "Help the user with their questions. " |
| 126 | + "If they ask about booking, hand off to the booking agent. " |
| 127 | + "If they ask about refunds, hand off to the refund agent." |
| 128 | + ), |
| 129 | + handoffs=[booking_agent, refund_agent], |
| 130 | +) |
| 131 | +``` |
| 132 | + |
| 133 | +## 动态指令 |
| 134 | + |
| 135 | +在大多数情况下,你可以在创建智能体时提供指令。然而,你也可以通过函数提供动态指令。该函数将接收智能体和上下文,并必须返回提示。既可以使用普通函数,也可以使用 `async` 函数。 |
| 136 | + |
| 137 | +```python |
| 138 | +def dynamic_instructions( |
| 139 | + context: RunContextWrapper[UserContext], agent: Agent[UserContext] |
| 140 | +) -> str: |
| 141 | + return f"The user's name is {context.context.name}. Help them with their questions." |
| 142 | + |
| 143 | + |
| 144 | +agent = Agent[UserContext]( |
| 145 | + name="Triage agent", |
| 146 | + instructions=dynamic_instructions, |
| 147 | +) |
| 148 | +``` |
| 149 | + |
| 150 | +## 生命周期事件(钩子) |
| 151 | + |
| 152 | +有时候,你可能想要观察智能体的生命周期。例如,你可能想要记录事件,或者在某些事件发生时预取数据。你可以通过 `hooks` 属性在智能体的生命周期中设置钩子。子类化 [`AgentHooks`][agents.lifecycle.AgentHooks] 类,并覆盖你感兴趣的方法。 |
| 153 | + |
| 154 | +## 护栏 |
| 155 | + |
| 156 | +护栏允许你在智能体运行的同时并行运行对用户输入的检查/验证,并在智能体输出产生后对其进行检查/验证。例如,你可以根据相关性筛选用户输入和智能体输出。更多详细信息请参见 [guardrails](guardrails.md) 文档。 |
| 157 | + |
| 158 | +## 克隆/复制智能体 |
| 159 | + |
| 160 | +通过使用智能体上的 `clone()` 方法,你可以复制智能体,并选择性地更改任何属性。 |
| 161 | + |
| 162 | +```python |
| 163 | +pirate_agent = Agent( |
| 164 | + name="Pirate", |
| 165 | + instructions="Write like a pirate", |
| 166 | + model="gpt-4.1", |
| 167 | +) |
| 168 | + |
| 169 | +robot_agent = pirate_agent.clone( |
| 170 | + name="Robot", |
| 171 | + instructions="Write like a robot", |
| 172 | +) |
| 173 | +``` |
| 174 | + |
| 175 | +## 强制工具使用 |
| 176 | + |
| 177 | +提供工具列表并不总是意味着LLM会使用工具。你可以通过设置 [`ModelSettings.tool_choice`][agents.model_settings.ModelSettings.tool_choice] 来强制工具使用。有效值包括: |
| 178 | + |
| 179 | +1. `auto`,允许LLM决定是否使用工具。 |
| 180 | +2. `required`,要求LLM使用工具(但它可以智能地决定使用哪个工具)。 |
| 181 | +3. `none`,要求LLM _不_ 使用工具。 |
| 182 | +4. 设置特定字符串,例如 `my_tool`,要求LLM使用该特定工具。 |
| 183 | + |
| 184 | +```python |
| 185 | +from agents import Agent, Runner, function_tool, ModelSettings |
| 186 | + |
| 187 | +@function_tool |
| 188 | +def get_weather(city: str) -> str: |
| 189 | + """Returns weather info for the specified city.""" |
| 190 | + return f"The weather in {city} is sunny" |
| 191 | + |
| 192 | +agent = Agent( |
| 193 | + name="Weather Agent", |
| 194 | + instructions="Retrieve weather details.", |
| 195 | + tools=[get_weather], |
| 196 | + model_settings=ModelSettings(tool_choice="get_weather") |
| 197 | +) |
| 198 | +``` |
| 199 | + |
| 200 | +## 工具使用行为 |
| 201 | + |
| 202 | +`Agent` 配置中的 `tool_use_behavior` 参数控制如何处理工具输出: |
| 203 | + |
| 204 | +- `"run_llm_again"`: 默认。工具运行后,LLM处理结果以产生最终响应。 |
| 205 | +- `"stop_on_first_tool"`: 第一个工具调用的输出用作最终响应,无需进一步的LLM处理。 |
| 206 | + |
| 207 | +```python |
| 208 | +from agents import Agent, Runner, function_tool, ModelSettings |
| 209 | + |
| 210 | +@function_tool |
| 211 | +def get_weather(city: str) -> str: |
| 212 | + """Returns weather info for the specified city.""" |
| 213 | + return f"The weather in {city} is sunny" |
| 214 | + |
| 215 | +agent = Agent( |
| 216 | + name="Weather Agent", |
| 217 | + instructions="Retrieve weather details.", |
| 218 | + tools=[get_weather], |
| 219 | + tool_use_behavior="stop_on_first_tool" |
| 220 | +) |
| 221 | +``` |
| 222 | + |
| 223 | +- `StopAtTools(stop_at_tool_names=[...])`: 当指定的工具中的任何一个被调用时停止,并将其输出用作最终响应。 |
| 224 | + |
| 225 | +```python |
| 226 | +from agents import Agent, Runner, function_tool |
| 227 | +from agents.agent import StopAtTools |
| 228 | + |
| 229 | +@function_tool |
| 230 | +def get_weather(city: str) -> str: |
| 231 | + """Returns weather info for the specified city.""" |
| 232 | + return f"The weather in {city} is sunny" |
| 233 | + |
| 234 | +@function_tool |
| 235 | +def sum_numbers(a: int, b: int) -> int: |
| 236 | + """Adds two numbers.""" |
| 237 | + return a + b |
| 238 | + |
| 239 | +agent = Agent( |
| 240 | + name="Stop At Stock Agent", |
| 241 | + instructions="Get weather or sum numbers.", |
| 242 | + tools=[get_weather, sum_numbers], |
| 243 | + tool_use_behavior=StopAtTools(stop_at_tool_names=["get_weather"]) |
| 244 | +) |
| 245 | +``` |
| 246 | + |
| 247 | +- `ToolsToFinalOutputFunction`: 处理工具结果并决定是停止还是继续LLM的自定义函数。 |
| 248 | + |
| 249 | +```python |
| 250 | +from agents import Agent, Runner, function_tool, FunctionToolResult, RunContextWrapper |
| 251 | +from agents.agent import ToolsToFinalOutputResult |
| 252 | +from typing import List, Any |
| 253 | + |
| 254 | +@function_tool |
| 255 | +def get_weather(city: str) -> str: |
| 256 | + """Returns weather info for the specified city.""" |
| 257 | + return f"The weather in {city} is sunny" |
| 258 | + |
| 259 | +def custom_tool_handler( |
| 260 | + context: RunContextWrapper[Any], |
| 261 | + tool_results: List[FunctionToolResult] |
| 262 | +) -> ToolsToFinalOutputResult: |
| 263 | + """Processes tool results to decide final output.""" |
| 264 | + for result in tool_results: |
| 265 | + if result.output and "sunny" in result.output: |
| 266 | + return ToolsToFinalOutputResult( |
| 267 | + is_final_output=True, |
| 268 | + final_output=f"Final weather: {result.output}" |
| 269 | + ) |
| 270 | + return ToolsToFinalOutputResult( |
| 271 | + is_final_output=False, |
| 272 | + final_output=None |
| 273 | + ) |
| 274 | + |
| 275 | +agent = Agent( |
| 276 | + name="Weather Agent", |
| 277 | + instructions="Retrieve weather details.", |
| 278 | + tools=[get_weather], |
| 279 | + tool_use_behavior=custom_tool_handler |
| 280 | +) |
| 281 | +``` |
| 282 | + |
| 283 | +!!! note |
| 284 | + |
| 285 | + 为了防止无限循环,框架会在工具调用后自动将 `tool_choice` 重置为 "auto"。此行为可通过 [`agent.reset_tool_choice`][agents.agent.Agent.reset_tool_choice] 进行配置。无限循环的发生是因为工具结果被发送给LLM,然后由于 `tool_choice` 导致LLM再次生成工具调用,如此循环往复。 |
0 commit comments