智能体
智能体是你应用的核心构建单元。一个智能体是一个大型语言模型(LLM),并配置了 instructions 和工具。
基本配置
你将为智能体配置的最常见属性包括:
name: 标识你的智能体的必填字符串。instructions: 也称为开发者消息或系统提示词(system prompt)。model: 要使用的 LLM,以及可选的model_settings,用于配置如 temperature、top_p 等模型调优参数。tools: 智能体可用来完成任务的工具。
fromagentsimportAgent,ModelSettings,function_tool@function_tooldefget_weather(city:str)->str:"""returns weather info for the specified city."""returnf"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 类型上是通用的。Context 是一种依赖注入工具:这是你创建并传递给Runner.run() 的对象,它会传递给每个智能体、工具、任务转移(handoffs)等,并作为本次智能体运行的依赖与状态集合。你可以提供任何 Python 对象作为 context。
@dataclassclassUserContext:name:struid:stris_pro_user:boolasyncdeffetch_purchases()->list[Purchase]:return...agent=Agent[UserContext](...,)输出类型
默认情况下,智能体生成纯文本(即str)输出。如果你希望智能体生成特定类型的输出,可以使用output_type 参数。常见选择是使用Pydantic 对象,但我们支持任何可以被 PydanticTypeAdapter 包装的类型——dataclasses、lists、TypedDict 等。
frompydanticimportBaseModelfromagentsimportAgentclassCalendarEvent(BaseModel):name:strdate:strparticipants:list[str]agent=Agent(name="Calendar extractor",instructions="Extract calendar events from text",output_type=CalendarEvent,)Note
当你传入output_type 时,这会告知模型使用structured outputs 而非常规纯文本响应。
多智能体系统设计模式
设计多智能体系统有很多方法,但我们常见的两种广泛适用的模式是:
- 管理器(智能体作为工具):一个中央管理器/编排器将专业子智能体作为工具调用,并保留对对话的控制权。
- 任务转移:同级智能体将控制权转移给接管对话的专业智能体。这是去中心化的。
参见我们的构建智能体实用指南了解更多细节。
管理器(智能体作为工具)
customer_facing_agent 处理所有用户交互,并调用作为工具暴露的专业子智能体。更多内容参见工具文档。
fromagentsimportAgentbooking_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.",)],)任务转移
任务转移是智能体可以委派给的子智能体。当发生任务转移时,被委派的智能体会接收对话历史并接管对话。该模式支持模块化、专长化的智能体,它们擅长完成单一任务。更多内容参见任务转移文档。
fromagentsimportAgentbooking_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],)动态 instructions
在大多数情况下,你可以在创建智能体时提供 instructions。不过,你也可以通过函数提供动态 instructions。该函数将接收智能体和上下文,并且必须返回提示词。常规函数和async 函数均可。
defdynamic_instructions(context:RunContextWrapper[UserContext],agent:Agent[UserContext])->str:returnf"The user's name is{context.context.name}. Help them with their questions."agent=Agent[UserContext](name="Triage agent",instructions=dynamic_instructions,)生命周期事件(hooks)
有时,你希望观察智能体的生命周期。例如,你可能希望记录事件,或在某些事件发生时预取数据。你可以通过hooks 属性接入智能体生命周期。子类化AgentHooks 并重写你感兴趣的方法。
安全防护措施
安全防护措施允许你在智能体运行的同时对用户输入进行检查/验证,并在智能体生成输出后对其输出进行检查。例如,你可以筛查用户输入和智能体输出的相关性。更多内容参见安全防护措施文档。
克隆/复制智能体
通过在智能体上使用clone() 方法,你可以复制一个智能体,并可选择性地更改任意属性。
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 使用该特定工具。
fromagentsimportAgent,Runner,function_tool,ModelSettings@function_tooldefget_weather(city:str)->str:"""Returns weather info for the specified city."""returnf"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"))工具使用行为
Agent 配置中的tool_use_behavior 参数控制如何处理工具输出:
"run_llm_again":默认值。运行工具后,LLM 会处理结果以生成最终响应。"stop_on_first_tool":首次工具调用的输出将作为最终响应,不再进行后续 LLM 处理。
fromagentsimportAgent,Runner,function_tool,ModelSettings@function_tooldefget_weather(city:str)->str:"""Returns weather info for the specified city."""returnf"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=[...]):如果调用了任一指定工具则停止,使用其输出作为最终响应。
fromagentsimportAgent,Runner,function_toolfromagents.agentimportStopAtTools@function_tooldefget_weather(city:str)->str:"""Returns weather info for the specified city."""returnf"The weather in{city} is sunny"@function_tooldefsum_numbers(a:int,b:int)->int:"""Adds two numbers."""returna+bagent=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。
fromagentsimportAgent,Runner,function_tool,FunctionToolResult,RunContextWrapperfromagents.agentimportToolsToFinalOutputResultfromtypingimportList,Any@function_tooldefget_weather(city:str)->str:"""Returns weather info for the specified city."""returnf"The weather in{city} is sunny"defcustom_tool_handler(context:RunContextWrapper[Any],tool_results:List[FunctionToolResult])->ToolsToFinalOutputResult:"""Processes tool results to decide final output."""forresultintool_results:ifresult.outputand"sunny"inresult.output:returnToolsToFinalOutputResult(is_final_output=True,final_output=f"Final weather:{result.output}")returnToolsToFinalOutputResult(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)Note
为防止无限循环,框架会在工具调用后自动将tool_choice 重置为 "auto"。此行为可通过agent.reset_tool_choice 配置。产生无限循环的原因是工具结果会发送给 LLM,随后由于tool_choice,LLM 又会生成另一次工具调用,如此往复。