ARTICLE DETAIL

资讯详情

深耕网站视觉设计与运营推广的一线实战洞察。

openai-agents-python 的 Agent 定义完全指南:配置属性、提示模板、输出类型与生命周期钩子

openai-agents-python 的 Agent 定义完全指南:配置属性、提示模板、输出类型与生命周期钩子 openai-agents-python 的 Agent 定义完全指南配置属性、提示模板、输出类型与生命周期钩子【免费下载链接】openai-agents-pythonA lightweight, powerful framework for multi-agent workflows项目地址: https://gitcode.com/GitHub_Trending/op/openai-agents-python本篇围绕 openai-agents-pythonOpenAI Agents SDK for Python中最核心的构件Agent展开讲清它的全部常用配置属性、提示模板与上下文机制、结构化输出类型、多智能体设计模式以及工具执行行为与生命周期钩子这两个容易踩坑的运行时控制点。读完你可以独立完成一个带工具、守卫、结构化输出和自定义钩子的 Agent 定义并理解框架在运行循环中是如何管理tool_choice、工具结果回传与生命周期回调的。什么是 AgentLLM 加运行时行为Agent 是应用的核心构件一个被指令instructions、工具tools以及可选运行时行为handoffs、guardrails、结构化输出配置过的大语言模型LLM。两个重要边界需要明确本页描述的是单一的基础Agent的定义与定制。如果要让多个 Agent 协作参见 Agent 编排multi_agent如果 Agent 需要在带清单manifest定义文件、具备沙箱原生能力的隔离工作区中运行参见 Sandbox Agent 概念。SDK 对 OpenAI 模型默认使用 Responses API但这里的关键区别在于编排Agent配合Runner时SDK 会替你管理回合turns、工具、守卫、交接与会话如果你想自己掌握这个循环可以直接使用 Responses API。从源码结构看这一分工体现在Agent只是配置描述一个 dataclass而回合循环、工具执行、钩子触发都由Runner及src/agents/run_internal/下的运行循环代码完成例如 run_loop.py 中反复调用maybe_reset_tool_choice来重置tool_choice。相邻指南导航以本页为 Agent 定义的中心指南按下一步要做的决策跳转你想做什么继续阅读选择模型或提供方设置模型为 Agent 添加能力工具让 Agent 在真实仓库、文档包或隔离工作区中运行Sandbox Agents 快速上手在管理员式编排与handoff之间做选择Agent 编排配置 handoff 行为Handoffs执行回合、流式事件、管理对话状态运行 Agent检查最终输出、运行项或可恢复状态结果共享本地依赖与运行时状态上下文管理基本配置属性Agent 最常用的属性如下属性语义已在 agent.py 的Agentdataclass 字段与__post_init__校验中逐一确认属性是否必填说明name是人类可读的 Agent 名称instructions否系统提示词或动态指令回调。强烈建议提供。见 动态指令prompt否OpenAI Responses API 的提示词配置接受静态提示对象或函数。见 提示模板handoff_description否当该 Agent 作为 handoff 目标提供时展示的简短描述handoffs否将会话委托给专家 Agent。见 Handoffsmodel否要使用的 LLM。见 模型model_settings否模型调参如temperature、top_p、tool_choicetools否Agent 可调用的工具。见 工具mcp_servers否为 Agent 提供 MCP 工具的 MCP 服务器。见 MCP 指南mcp_config否微调 MCP 工具的准备工作方式如把 schema 转为严格模式、指定 MCP 失败格式等。见 MCP 指南input_guardrails否在本 Agent 链的第一个用户输入上执行的守卫。见 Guardrailsoutput_guardrails否在本 Agent 的最终输出上执行的守卫。见 Guardrailsoutput_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.__post_init__agent.py会检查name必须是字符串、instructions必须是字符串或可调用对象、prompt必须是Prompt或函数、tool_use_behavior必须是run_llm_again/stop_on_first_tool/StopAtTools字典/可调用对象、reset_tool_choice必须是布尔值等配置错误会在构造阶段而非运行阶段暴露。model缺省值来自 SDK 默认模型。不设置model时Agent 使用agents.models.get_default_model()返回的默认模型从 default_models.py 看当前默认值为gpt-5.6-luna且可通过环境变量OPENAI_DEFAULT_MODEL覆盖。model_settings会随模型联动。__post_init__中如果显式传入了model而model_settings仍是全局默认SDK 会改用该模型对应的初始默认设置agent.py避免把上一个模型的推理参数误套到新模型上。上述全部内容同样适用于SandboxAgent后者在此基础上新增default_manifest、base_instructions、capabilities、run_as四个面向工作区运行的参数见 Sandbox Agent 概念。提示模板设置prompt可以引用在 OpenAI 平台上创建的提示词模板prompt template。该能力仅在使用 Responses API 访问 OpenAI 模型时生效。使用步骤前往 OpenAI 平台的提示词页面Playground → Prompts创建一个新的提示变量poem_style用如下内容创建系统提示词Write a poem in {{poem_style}}使用--prompt-id标志运行示例仓库中对应的可运行示例是 prompt_template.py它通过--prompt-id和--dynamic参数分别演示静态与动态两种用法。静态引用from agents import Agent agent Agent( namePrompted assistant, prompt{ id: pmpt_123, version: 1, variables: {poem_style: haiku}, }, )在运行时动态生成提示词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), )源码印证Prompt是一个TypedDict字段为必填的id与可选的version、variables动态函数接收GenerateDynamicPromptData内含context与agent同步或异步均可返回值必须是Prompt字典否则抛出UserError。这一解析逻辑集中在 prompts.py 的 PromptUtil.to_model_input。注意prompt与instructions是两个正交的机制prompt把提示词配置外置到 OpenAI 平台instructions是代码内联的系统提示词。上下文ContextAgent 对context类型是泛型的Agent[TContext]。上下文是一个依赖注入工具它是由用户创建并通过Runner.run()传入的对象会被传递给所有 Agent、工具、handoff 等充当承载 Agent 运行所需依赖与状态的容器。任何 Python 对象都可以作为上下文。完整的RunContextWrapper接口、共享用量统计、嵌套tool_input与序列化注意事项见 上下文指南。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在 agent.py 的Agent类文档 中上下文被描述为一个可变的由用户创建的对象会传递给工具函数、handoff、守卫等——这正是动态指令、动态提示模板、守卫与钩子能够共享同一份依赖的基础。输出类型output_type默认情况下 Agent 生成纯文本即str输出。若希望 Agent 产出特定类型的输出使用output_type参数。通常使用 Pydantic 对象但数据类、列表、TypedDict 等任何能用 PydanticTypeAdapter包装的类型都支持。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而非一般的纯文本响应。从 agent.py 的output_type字段文档还能看到两个进阶定制方式需要非严格non-strictschema 时传入AgentOutputSchema(MyClass, strict_json_schemaFalse)想完全自定义 JSON schema绕过 SDK 的自动 schema 生成时继承AgentOutputSchemaBase并传入其子类见 agent_output.py。多 Agent 系统设计模式多 Agent 系统有多种设计方式但最广泛使用的可通用模式是以下两种管理员Agents as tools中央管理员/编排者把专家子 Agent 作为工具调用并始终持有对话控制权Handoffs交接对等 Agent 把对话控制权移交给接管对话的专家 Agent是去中心化的方式。管理员Agents as toolscustomer_facing_agent处理所有用户交互并调用以工具形式暴露的专家子 Agent详见 工具文档 的 Agents as tools 一节可运行参考 agents_as_tools.pyfrom 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., ) ], )as_tool()的实现见 agent.py其文档明确了它和 handoff 的两点本质区别handoff 中新 Agent 收到完整对话历史并接管对话而as_tool中被调用的 Agent 收到的是生成的输入执行完毕后对话仍由原 Agent 继续。此外as_tool()还支持custom_output_extractor自定义输出提取、is_enabled动态启停、on_stream透传子 Agent 的流式事件、max_turns、needs_approval等参数用于精细控制Agent 作为工具的边界。Handoffs交接配置好的 handoff 目标是 Agent 可以委托任务的子 Agent。发生 handoff 后被委托的 Agent 会接收对话记录并继续对话。这种模式允许把单一任务拆成模块化的专家 Agent详见 Handoffs 文档from 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], )动态指令大多数情况下在创建 Agent 时直接给出指令即可但也可以通过函数提供动态指令该函数接收上下文与 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.py 中instructions的类型定义一致str | Callable[[RunContextWrapper[TContext], Agent[TContext]], MaybeAwaitable[str]] | None。生命周期事件钩子有时你需要观察 Agent 的整个生命周期例如在某事件发生时打日志、预取数据、记录用量。钩子分两种作用域[RunHooks][src/agents/lifecycle.py] 观察整个Runner.run(...)调用包括向其他 Agent 的 handoff[AgentHooks][src/agents/lifecycle.py] 通过agent.hooks绑定到特定 Agent 实例。回调收到的上下文也随事件类型不同而不同Agent 开始/结束钩子收到 [AgentHookContext][src/agents/run_context.py]——它包装了原始上下文并包含共享的运行用量状态LLM、工具与 handoff 钩子收到 [RunContextWrapper][src/agents/run_context.py]。常见钩子触发时机签名定义见 lifecycle.py 的 RunHooksBaseon_agent_start某个 Agent 开始运行on_agent_end该 Agent 完成最终输出生成on_llm_start/on_llm_end每次模型调用之前/之后on_tool_start/on_tool_end每次本地工具调用前后。函数工具的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 参考。相关行为有测试覆盖例如 test_agent_hooks.py 与 test_global_hooks.py。Guardrails守卫使用 guardrails 可以让输入检查/校验与 Agent 执行并行运行并在 Agent 输出产生之后检查该输出——例如验证用户输入与 Agent 输出的相关性。input_guardrails只在 Agent 是链条中第一个 Agent 时运行output_guardrails只在 Agent 产生最终输出时运行语义见 agent.py 的字段文档。完整用法见 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的浅拷贝未传入的列表属性tools、handoffs、mcp_servers、input_guardrails、output_guardrails与原 Agent 共享同一个列表通过任一 Agent 执行cloned.tools.append(...)都会同时影响另一个传入的属性按原样使用想让克隆体持有独立的列表请显式传一个新列表例如agent.clone(tools[*agent.tools, extra_tool])条目仍是原对象额外细节如果clone时更换了model但未指定model_settings且原model_settings与旧模型的隐式默认值一致SDK 会自动换成新模型的默认设置agent.py避免跨模型套用错误的推理参数。强制工具使用Forcing tool use提供了工具列表并不代表 LLM 一定会调用工具。通过ModelSettings.tool_choice可以强制工具使用有效取值有四类auto由 LLM 自行决定是否使用工具requiredLLM 必须使用工具但用哪个由它智能决定none指定 LLM不要使用工具特定字符串如my_tool强制 LLM 调用该指定工具。使用 OpenAI Responses 托管工具搜索hosted tool search时对指名道姓的工具选择有额外限制不能用tool_choice单独指定命名空间名称或延迟专用工具且tool_choicetool_search并不指向ToolSearchTool这些场景建议使用auto或required详见 工具文档 的 Hosted tool search 一节。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) )工具使用行为tool_use_behaviorAgent配置中的tool_use_behavior参数控制工具输出的处理方式共有四种形态类型定义见 agent.pyrun_llm_again默认值。工具执行后结果回传给 LLM 处理并生成最终响应stop_on_first_tool第一个工具调用的输出直接作为最终响应不再送回 LLM 处理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( nameWeather Agent, instructionsRetrieve weather details., tools[get_weather], tool_use_behaviorstop_on_first_tool )StopAtTools(stop_at_tool_names[...])agent.py 中定义为TypedDict指定工具中任何一个被调用即停止运行并以其输出作为最终响应自定义函数ToolsToFinalOutputFunction接收运行上下文与工具结果列表返回ToolsToFinalOutputResult自行决定是终结运行还是继续让 LLM 处理。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 )需要留意两个源码层面的细节该配置只作用于 FunctionTool。tool_use_behavior的字段文档明确注明文件搜索、联网搜索等托管工具hosted tools始终由 LLM 处理不受此参数影响reset_tool_choice防止无限循环框架会在工具调用后自动把tool_choice重置为auto。这个行为的实现是 tool_execution.py 的 maybe_reset_tool_choice——当agent.reset_tool_choice is True且该 Agent 本轮已用过工具时把model_settings中的tool_choice替换为None运行循环run_loop.py在每次进入下一轮模型调用前调用它。之所以必要是因为若tool_choice保持强制状态工具结果送回 LLM → LLM 再次发起工具调用会无限循环。此行为通过agent.reset_tool_choice默认True见 agent.py配置。小结Agent 定义中的关键决策点用instructions静态或动态函数表达角色与行为约束用prompt把提示词外置到 OpenAI 平台用toolsmcp_servers装配能力用tool_choice控制用不用、用哪个用tool_use_behavior控制工具输出之后怎么办两者配合reset_tool_choice才能既强制又安全用output_type把自然语言输出升级为可程序化消费的结构化数据用handoffs去中心化接管或as_tool中心化调用搭建多 Agent 结构用RunHooks/AgentHooks观测与埋点用input_guardrails/output_guardrails做并行校验复制变体时用clone()并注意其浅拷贝语义。如需继续深入可依次阅读 工具、Handoffs、运行 Agent、结果 与 上下文管理并对照 src/agents/agent.py 与 tests/test_agent_config.py 验证各配置项的边界行为。【免费下载链接】openai-agents-pythonA lightweight, powerful framework for multi-agent workflows项目地址: https://gitcode.com/GitHub_Trending/op/openai-agents-python创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表