资讯动态

openai-agents-python Agent 核心配置详解:从基础属性、Prompt 模板到生命周期钩子与工具行为控制

发布时间:2026/9/10 7:46:42 来源:尧图企业网站定制
openai-agents-python Agent 核心配置详解从基础属性、Prompt 模板到生命周期钩子与工具行为控制【免费下载链接】openai-agents-pythonA lightweight, powerful framework for multi-agent workflows项目地址: https://gitcode.com/GitHub_Trending/op/openai-agents-python本文基于 docs/agents.md 系统讲解 openai-agents-python 中Agent的完整定义方式包括 15 项核心配置属性、OpenAI 平台 Prompt 模板、泛型 Context 依赖注入、结构化输出、Manager 与 Handoffs 两种多智能体模式、动态指令、生命周期钩子以及tool_choice与tool_use_behavior等工具行为控制机制。读完后你可以独立定义、调优和编排一个生产级的Agent并理解这些配置在 SDK 源码中的实际执行路径。Agent 是什么LLM 加上运行时行为的定义单元Agent是 openai-agents-python 的核心构建单元一个配置了指令instructions、工具tools以及可选运行时行为handoffs、guardrails、结构化输出的大语言模型。它的定位可以概括为三点Agent 负责定义Runner 负责执行。SDK 对 OpenAI 模型默认走 Responses API但这里的重点是编排Agent加上Runner让 SDK 替你管理轮次、工具调用、guardrails、handoffs 和会话如果你要自己掌控整个循环应直接使用 Responses API。本页只讲基础Agent。如果你要决定多个 agent 如何协作看 Agent orchestration如果 agent 需要在带 manifest 文件定义的隔离工作区中运行应改用SandboxAgent参见 Sandbox agent concepts。SandboxAgent建立在同一套概念之上额外增加default_manifest、base_instructions、capabilities、run_as等面向工作区运行的属性。Agent 核心属性速查与基础配置Agent最常用的属性及说明如下完整继承自官方文档的属性表属性是否必填说明name是人类可读的 agent 名称。instructions否系统提示词或动态指令回调函数强烈建议提供。见动态指令。prompt否OpenAI Responses API 的 prompt 配置接受静态 prompt 对象或函数。见Prompt 模板。handoff_description否当该 agent 作为 handoff 目标时暴露给 LLM 的简短描述。handoffs否允许将对话委派给专家 agent 的列表。见 Handoffs。model否使用的 LLM可传模型名字符串或Model实现。见 Models。model_settings否temperature、top_p、tool_choice等模型调参项。tools否agent 可调用的工具列表。见 Tools。mcp_servers否为 agent 提供 MCP 工具的服务端列表。见 MCP 指南。mcp_config否精细控制 MCP 工具的预处理方式如将 schema 转为 strict 模式、格式化 MCP 失败信息。见 MCP 指南。input_guardrails否在该 agent 链的首条用户输入上运行的护栏。见 Guardrails。output_guardrails否在该 agent 产生最终输出后运行的护栏。见 Guardrails。output_type否用结构化类型替代纯文本输出。见输出类型。hooks否agent 作用域的生命周期回调。见生命周期事件。tool_use_behavior否控制工具结果回传模型还是直接结束运行。见工具使用行为。reset_tool_choice否工具调用后是否重置tool_choice默认True用于避免工具使用死循环。见强制工具使用。最小可用的定义示例与官方文档一致可直接运行from agents import Agent from agents.decorators import tool tool def get_weather(city: str) - str: returns weather info for the specified city. return fThe weather in {city} is sunny agent Agent( nameHaiku agent, instructionsAlways respond in haiku form, modelgpt-5-nano, tools[get_weather], )源码视角Agent 是一个 dataclass从源码结构看Agent 类定义 继承自AgentBaseRealtimeAgent与其共用基类是一个带Generic[TContext]泛型参数的 dataclassinstructions 字段 的类型标注为str | Callable[[RunContextWrapper[TContext], Agent[TContext]], MaybeAwaitable[str]] | None即同时支持静态字符串和同步/异步回调tool_use_behavior 字段 的联合类型精确限定为Literal[run_llm_again, stop_on_first_tool] | StopAtTools | ToolsToFinalOutputFunctionreset_tool_choice 默认值为True__post_init__src/agents/agent.py#L432-L546会对name、tools、model、tool_use_behavior等字段做类型校验传入不合法值会抛出TypeError。另外注意默认模型源码 docstring 声明未指定model时agent 使用agents.models.get_default_model()配置的默认模型src/agents/agent.py#L337-L342因此示例中显式写modelgpt-5-nano等模型名是推荐的显式做法。Prompt 模板引用 OpenAI 平台上的提示词prompt参数允许 agent 引用在 OpenAI 平台上创建的 prompt 模板仅在通过 Responses API 访问 OpenAI 模型时可用。官方文档给出的操作步骤是进入 OpenAI Playground 的 Prompts 页面创建一个新的 prompt在 prompt 中定义变量例如poem_style系统提示词内容形如Write a poem in {{poem_style}}在代码中通过id、version、variables三个键引用它。静态引用的写法from agents import Agent agent Agent( namePrompted assistant, prompt{ id: pmpt_123, version: 1, variables: {poem_style: haiku}, }, )也可以在运行时动态生成 prompt——回调函数接收GenerateDynamicPromptData从其中取出 context 并返回 prompt 字典from dataclasses import dataclass from agents import Agent, GenerateDynamicPromptData, Runner dataclass class PromptContext: prompt_id: str poem_style: str async def build_prompt(data: GenerateDynamicPromptData): ctx: PromptContext data.context.context return { id: ctx.prompt_id, version: 1, variables: {poem_style: ctx.poem_style}, } agent Agent(namePrompted assistant, promptbuild_prompt) result await Runner.run( agent, Say hello, contextPromptContext(prompt_idpmpt_123, poem_stylelimerick), )仓库中的完整可运行示例是 examples/basic/prompt_template.py它用argparse提供--prompt-id和--dynamic两个命令行参数静态模式直接使用 dict动态模式由_get_dynamic_prompt(data: GenerateDynamicPromptData)从DynamicContext中随机挑选poem_style后生成 prompt。从源码看prompt 的解析在 src/agents/prompts.py 中完成Prompt是一个TypedDict含必填id与可选version、variables字段src/agents/prompts.py#L23-L34GenerateDynamicPromptData是携带contextRunContextWrapper与agent两个字段的数据类src/agents/prompts.py#L36-L48PromptUtil.to_model_input负责在调用时解析 dict 或调用回调同步/异步均可并统一输出{id, version, variables}结构src/agents/prompts.py#L56-L82。Context给 Agent 泛型化一个依赖注入容器Agent 对context类型是泛型的。Context 本质上是依赖注入工具它是你创建并通过Runner.run()传入的对象会被传递给本次运行中的每一个 agent、tool、handoff 等充当依赖和运行状态的杂物袋。任何 Python 对象都可以作为 context。更完整的RunContextWrapper表面、共享用量统计、嵌套tool_input与序列化注意事项见 Context 管理指南。典型用法——为 agent 绑定用户上下文from dataclasses import dataclass dataclass class Purchase: id: str dataclass class UserContext: name: str uid: str is_pro_user: bool async def fetch_purchases(self) - list[Purchase]: # implement your logic here return [] agent AgentUserContext绑定后工具函数、动态指令、guardrail、hook 都能拿到同一个类型化的上下文对象例如工具可以直接await context.fetch_purchases()而无需全局状态。输出类型output_type默认情况下 agent 产出纯文本str。若需要特定类型的输出使用output_type参数。常见选择是 Pydantic 模型但任何可以被 PydanticTypeAdapter包装的类型都可以——dataclass、list、TypedDict 等from pydantic import BaseModel from agents import Agent class CalendarEvent(BaseModel): name: str date: str participants: list[str] agent Agent( nameCalendar extractor, instructionsExtract calendar events from text, output_typeCalendarEvent, )需要注意传入output_type后模型会使用结构化的 structured outputs 能力而非普通纯文本响应。从源码看output_type还支持两种定制方式src/agents/agent.py#L360-L367需要非 strict schema 时传AgentOutputSchema(MyClass, strict_json_schemaFalse)需要完全自定义 JSON schema不走 SDK 自动 schema 生成时继承AgentOutputSchemaBase并传入子类实例。__post_init__会校验output_type必须是type、AgentOutputSchemaBase实例或带泛型 origin 的类型否则抛TypeErrorsrc/agents/agent.py#L508-L518。多智能体系统设计模式Manager 与 Handoffs设计多智能体系统的方式有很多种但最常见、通用性最强的是两种模式Manageragents as tools中心管理器/编排器把专家子 agent 当作工具来调用对话控制权始终留在管理者手里。Handoffs平级 agent 之间把控制权移交给接管对话的专家 agent属于去中心化模式。Manager 模式agent.as_tool()customer_facing_agent负责所有用户交互并把暴露为工具的专家子 agent 按需调用from agents import Agent booking_agent Agent(...) refund_agent Agent(...) customer_facing_agent Agent( nameCustomer-facing agent, instructions( Handle all direct user communication. Call the relevant tools when specialized expertise is needed. ), tools[ booking_agent.as_tool( tool_namebooking_expert, tool_descriptionHandles booking questions and requests., ), refund_agent.as_tool( tool_namerefund_expert, tool_descriptionHandles refund questions and requests., ) ], )仓库中对应的完整示例见 examples/agent_patterns/agents_as_tools.py。从源码看as_tool()与 handoff 的本质区别在两处src/agents/agent.py#L583-L634输入handoff 中新 agent 接收完整对话历史as_tool()中子 agent 接收的是主 agent 生成的工具入参默认是input文本也可通过parameters指定 dataclass/Pydantic 结构化入参并用input_builder自定义构造逻辑控制权handoff 后对话由新 agent 接管as_tool()结束后对话仍由原 agent 继续子 agent 的final_output作为工具输出返回。as_tool()还支持is_enabled动态隐藏工具、on_stream订阅嵌套 agent 的流式事件、failure_error_function工具失败时生成给 LLM 的可见错误而非抛异常、needs_approval审批暂停等参数。Handoffs 模式配置好的 handoff 目标是该 agent 可以委派的子 agent。发生 handoff 时被委派 agent 接收对话历史并接管对话。该模式支持模块化、各司其职的专家 agentfrom agents import Agent booking_agent Agent(...) refund_agent Agent(...) triage_agent Agent( nameTriage 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], )更多细节见 Handoffs 文档多 agent 编排的整体决策框架见 Agent orchestration。动态指令多数情况下在创建 agent 时提供instructions即可但它同样可以是一个函数——函数接收context和agent两个参数并返回提示词字符串同步和async函数都支持from agents import Agent, RunContextWrapper def dynamic_instructions( context: RunContextWrapper[UserContext], agent: Agent[UserContext] ) - str: return fThe users name is {context.context.name}. Help them with their questions. agent AgentUserContext从源码看解析逻辑在Agent.get_system_prompt字符串直接返回callable 则先经inspect.signature校验其必须恰好接收 2 个参数context、agent调用后若结果是 awaitable 会自动await——这个先调用再判断的写法还覆盖了__call__为协程的 callable 实例这一iscoroutinefunction无法识别的边界情况。生命周期事件hooks当你需要观察 agent 生命周期——记录日志、预取数据、在特定事件发生时统计用量——时使用 hooks。SDK 提供两种作用域src/agents/lifecycle.pyRunHooksRunHooksBasesrc/agents/lifecycle.py#L13-L103观察整个Runner.run(...)调用包括向其他 agent 的 handoffAgentHooksAgentHooksBasesrc/agents/lifecycle.py#L106-L200通过agent.hooks挂载到具体 agent 实例上。回调收到的 context 类型也随事件变化agent 开始/结束钩子收到AgentHookContext它包装了你的原始 context 并携带本次运行共享的 usage 状态LLM、工具、handoff 钩子收到RunContextWrapper。典型钩子时序on_agent_start某个 agent 开始运行时触发on_agent_end该 agent 产出最终输出时触发on_llm_start/on_llm_end紧贴每次模型调用的前后on_tool_start/on_tool_end紧贴每次本地工具调用。对 function tool 而言钩子的context通常是ToolContext可以检查tool_call_id等工具调用元数据on_handoff控制权从一个 agent 转移到另一个 agent 时触发。选择原则想用一个观察者覆盖整个工作流就用RunHooks只想监听某个特定 agent 的生命周期就用AgentHooks。完整示例from agents import Agent, RunHooks, Runner class LoggingHooks(RunHooks): async def on_agent_start(self, context, agent): print(fStarting {agent.name}) async def on_llm_end(self, context, agent, response): print(f{agent.name} produced {len(response.output)} output items) async def on_agent_end(self, context, agent, output): print(f{agent.name} finished with usage: {context.usage}) agent Agent(nameAssistant, instructionsBe concise.) result await Runner.run(agent, Explain quines, hooksLoggingHooks()) print(result.final_output)完整的回调 API 面见 Lifecycle API reference。Guardrails 护栏Guardrails 允许你在 agent 运行期间并行地对用户输入做检查/校验并在 agent 产出最终输出后再对输出做检查。例如可以筛查用户输入和 agent 输出的相关性。input_guardrails仅在 agent 是链中第一个 agent 时运行output_guardrails在该 agent 产出最终输出时运行src/agents/agent.py#L350-L358。完整配置方式见 Guardrails 文档。克隆 Agent浅拷贝语义与陷阱clone()方法可以复制一个 Agent 并按需覆盖任意属性pirate_agent Agent( namePirate, instructionsWrite like a pirate, modelgpt-5.6-sol, ) robot_agent pirate_agent.clone( nameRobot, instructionsWrite like a robot, )关键细节在于clone()底层使用dataclasses.replace执行的是浅拷贝src/agents/agent.py#L548-L581你没有覆盖的列表属性tools、handoffs、mcp_servers、input_guardrails、output_guardrails仍然引用原 agent 持有的是同一个 list 对象。因此通过任意一方append那个列表都会同时影响两个 agent。给克隆体一个独立的列表容器应传入新列表例如pirate_agent.clone(tools[*pirate_agent.tools, extra_tool])不过注意复制进新列表的条目仍是同一批 tool/handoff 对象除非你也替换这些条目。clone()还有一个隐式行为如果你只改了model而原 agent 的model_settings恰好还是该模型的默认值SDK 会自动为新模型初始化对应的默认model_settingssrc/agents/agent.py#L568-L573。强制工具使用tool_choice给 agent 配了工具不代表 LLM 一定会用。通过ModelSettings.tool_choice可以强制工具使用合法取值有四种auto允许 LLM 自行决定是否调用工具required强制 LLM 必须调用某个工具由它智能决定是哪个none强制 LLM不调用工具具体工具名字符串如get_weather强制 LLM 调用该指定工具。from agents import Agent, ModelSettings from agents.decorators import tool tool def get_weather(city: str) - str: Returns weather info for the specified city. return fThe weather in {city} is sunny agent Agent( nameWeather Agent, instructionsRetrieve weather details., tools[get_weather], model_settingsModelSettings(tool_choiceget_weather) )对应示例见 examples/agent_patterns/forcing_tool_use.py。一个需要注意的限制当使用 OpenAI Responses 的 tool search 时具名工具选择受限——不能用tool_choice指向裸命名空间名或仅处于 deferred 状态的工具且tool_choicetool_search并不能指向ToolSearchTool本身。这些场景下优先使用auto或requiredResponses 侧的具体约束见 Hosted tool search。工具使用行为tool_use_behaviortool_use_behavior控制工具产出的处理策略源码中支持四种形态src/agents/agent.py#L373-L393run_llm_again默认工具执行后结果回传 LLM 继续处理并产出最终响应stop_on_first_tool第一个工具调用的输出直接作为最终响应不再经过 LLM 处理StopAtTools(stop_at_tool_names[...])列表中任一工具被调用即停止运行用它的输出作为最终响应自定义函数ToolsToFinalOutputFunction接收RunContextWrapper和FunctionToolResult列表返回ToolsToFinalOutputResult(is_final_output, final_output)由你决定是结束运行还是继续让 LLM 处理。注意该配置仅针对FunctionToolfile search、web search 等托管工具始终由 LLM 处理src/agents/agent.py#L391-L392。三种进阶形态的完整示例from agents import Agent from agents.agent import StopAtTools from agents.decorators import tool tool def get_weather(city: str) - str: Returns weather info for the specified city. return fThe weather in {city} is sunny tool def sum_numbers(a: int, b: int) - int: Adds two numbers. return a b agent Agent( nameStop At Stock Agent, instructionsGet weather or sum numbers., tools[get_weather, sum_numbers], tool_use_behaviorStopAtTools(stop_at_tool_names[get_weather]) )from agents import Agent, FunctionToolResult, RunContextWrapper from agents.agent import ToolsToFinalOutputResult from agents.decorators import tool from typing import List, Any tool def get_weather(city: str) - str: Returns weather info for the specified city. return fThe 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_outputTrue, final_outputfFinal weather: {result.output} ) return ToolsToFinalOutputResult( is_final_outputFalse, final_outputNone ) agent Agent( nameWeather Agent, instructionsRetrieve weather details., tools[get_weather], tool_use_behaviorcustom_tool_handler )从源码看这些分支的裁决集中在check_for_final_output_from_tools每轮模型响应被处理后依次判断run_llm_again返回非最终→stop_on_first_tool取第一个工具输出为最终输出→ dict 形态的StopAtTools按tool.name或tool.qualified_name匹配命中即终止→ 自定义 callable支持 async结果直接透传。tool_choice 的自动重置防止工具死循环当tool_choice被强制为某个工具时工具结果会送回 LLM而 LLM 又因tool_choice再次生成同一个工具调用形成无限循环。为此框架默认在每次工具调用后把tool_choice重置为默认值由agent.reset_tool_choice默认True控制开关。从源码看该逻辑实现在maybe_reset_tool_choice当agent.reset_tool_choice is True且该 agent 在本轮中已经使用过工具由tool_use_tracker.has_used_tools(agent)判定时用dataclasses.replace(model_settings, tool_choiceNone)生成一份不带tool_choice的新 settings它被调用在每轮进入模型前的 settings 组装处src/agents/run_internal/run_loop.py#L2154 与 L2577 两处调用点分别覆盖不同路径。如果你的场景确实需要连续强制调用同一工具可显式设置reset_tool_choiceFalse——但要自行保证循环能够终止例如用max_turns兜底。从本页继续的导航地图docs/agents.md本身是 agent 定义的枢纽页以下决策到相邻文档的跳转关系值得保留你的下一步是…继续阅读选择模型或 provider 配置Models给 agent 增加能力Tools让 agent 跑在真实仓库、文档包或隔离工作区上Sandbox agents quickstart在 manager 式编排与 handoffs 之间做决策Agent orchestration配置 handoff 行为Handoffs运行轮次、流式事件、管理对话状态Running agents检查最终输出、运行项、可恢复状态Results共享本地依赖与运行期状态Context management小结Agent的全部核心配置可以归纳为四条主线指令线instructions静态/动态 prompt平台模板、能力线tools、mcp_servers/mcp_config、约束线output_type、input/output_guardrails、tool_choice、tool_use_behavior、reset_tool_choice与协作线handoffs、as_tool()、hooks。官方文档给出的每个属性在 src/agents/agent.py 中都有对应的字段定义与__post_init__校验工具行为的裁决逻辑在 src/agents/run_internal/turn_resolution.py 与 src/agents/run_internal/tool_execution.py 中可以直接对照阅读这为调试 agent 行为偏差比如工具没有被强制调用、循环提前终止提供了明确的代码定位路径。【免费下载链接】openai-agents-pythonA lightweight, powerful framework for multi-agent workflows项目地址: https://gitcode.com/GitHub_Trending/op/openai-agents-python创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

读完文章,也想定制专属网站?

尧图设计师 24 小时内与您沟通定制方案

免费获取报价