openai-agents-python 输出 Schema 机制完全指南:AgentOutputSchema 与 AgentOutputSchemaBase 深入解析

openai-agents-python 输出 Schema 机制完全指南:AgentOutputSchema 与 AgentOutputSchemaBase 深入解析 openai-agents-python 输出 Schema 机制完全指南AgentOutputSchema 与 AgentOutputSchemaBase 深入解析【免费下载链接】openai-agents-pythonA lightweight, powerful framework for multi-agent workflows项目地址: https://gitcode.com/GitHub_Trending/op/openai-agents-python导读在 openai-agents-python 多智能体框架中Agent.output_type决定了智能体最终输出的结构是纯文本字符串还是严格校验的 JSON 对象。本文围绕 docs/ref/agent_output.md 对应的agents.agent_output模块系统讲解AgentOutputSchemaBase与AgentOutputSchema两个核心类的设计原理、严格模式strict JSON schema机制、自动包装逻辑以及自定义输出 Schema 的完整方法。读完本文你将掌握如何为 Agent 配置结构化输出、如何处理非严格 Schema 的类型、如何编写自己的输出校验器并理解其底层实现与验证链路。一、模块定位输出 Schema 在 Agent 运行链路中的角色在 openai-agents-python 中Agent 的输出类型由 Agent 的output_type字段 控制。从源码可以看出其取值约定不设置None或传入str输出为纯文本传入普通 Python 类型dataclass、Pydantic 模型、TypedDict 等框架自动为其生成 JSON Schema 并校验 LLM 返回的 JSON传入AgentOutputSchema(MyClass, strict_json_schemaFalse)使用非严格 Schema传入自定义的AgentOutputSchemaBase子类完全接管 Schema 定义与 JSON 解析。真正把output_type解析成 Schema 对象的地方在 src/agents/run_internal/turn_preparation.py 的get_output_schema()def get_output_schema(agent: Agent[Any]) - AgentOutputSchemaBase | None: Return the resolved output schema for the agent, if any. if agent.output_type is None or agent.output_type is str: return None elif isinstance(agent.output_type, AgentOutputSchemaBase): return agent.output_type return AgentOutputSchema(agent.output_type)也就是说每次运行 Agent 前框架都会把output_type归一化为一个AgentOutputSchemaBase实例供后续模型调用与结果校验使用。这个归一化入口正是agents.agent_output模块对外提供的能力。二、抽象基类 AgentOutputSchemaBase输出 Schema 的统一契约AgentOutputSchemaBase定义于 src/agents/agent_output.py是一个abc.ABC抽象基类其 docstring 明确了定位一个捕获输出 JSON Schema并负责把 LLM 产生的 JSON 校验/解析为目标输出类型的对象。它定义了四个抽象方法构成输出 Schema 的统一契约方法签名职责is_plain_text()() - bool输出类型是否为纯文本而非 JSON 对象。纯文本类型不会生成、也不需要 JSON Schemaname()() - str输出类型的名称json_schema()() - dict[str, Any]返回输出的 JSON Schema。仅当输出类型不是纯文本时才会被调用is_strict_json_schema()() - bool是否处于严格模式。严格模式约束了 JSON Schema 特性但能保证输出是合法 JSONvalidate_json(json_str)(str) - Any用输出类型校验一段 JSON 字符串返回校验后的对象校验失败时抛出ModelBehaviorError这一设计使得输出 Schema 与具体模型解耦无论是内置的AgentOutputSchema还是开发者自定义的校验器只要实现上述契约就能无缝接入运行链路。注意validate_json的异常约定——失败必须抛 ModelBehaviorError该异常在 src/agents/init.py 中作为公开 API 导出调用方可以据此捕获模型输出不符合 Schema这类行为错误与配置错误UserError区分开。三、内置实现 AgentOutputSchema从类型到 Schema 的自动化AgentOutputSchemasrc/agents/agent_output.py是框架内置的默认实现一个dataclass(initFalse)类。它的构造签名是def __init__(self, output_type: type[Any], strict_json_schema: bool True):两个参数的含义与默认值output_type输出类型可以是None、str、dataclass、PydanticBaseModel、TypedDict、dict等strict_json_schema默认True。源码 docstring 强调强烈建议设为 True因为它能提高 JSON 输出正确的概率。3.1 构造期的三个分支构造逻辑src/agents/agent_output.py分三种情况分支一纯文本类型output_type is None or output_type is strif output_type is None or output_type is str: self._is_wrapped False self._type_adapter TypeAdapter(output_type) self._output_schema self._type_adapter.json_schema() return此时_is_wrapped为Falseis_plain_text()返回True后续json_schema()会抛出UserError(Output type is plain text, so no JSON schema is available)。分支二可表示为 JSON Schema 对象的类型PydanticBaseModel或dict子类通过_is_subclass_of_base_model_or_dict()src/agents/agent_output.py判断若类型是BaseModel或dict的子类包括泛型别名如list[int]通过get_origin解析则直接构建TypeAdapter(output_type)。分支三其余类型自动包装如 dataclass、TypedDict、普通类型if self._is_wrapped: OutputType TypedDict( OutputType, { _WRAPPER_DICT_KEY: output_type, }, ) self._type_adapter TypeAdapter(OutputType)框架会用键名为response常量_WRAPPER_DICT_KEY的 TypedDict 把原类型包一层。这就是为什么 dataclass 等类型也能产出 JSON Schema——它们先被包装成{response: YourType}的结构。3.2 严格模式的自动降级报错当strict_json_schemaTrue时构造器会调用 src/agents/strict_schema.py 的ensure_strict_json_schema()对生成的 Schema 做约束化处理。若你的类型不满足严格约束例如使用了dict[int, str]这类非严格兼容的键类型会抛出带引导信息的UserErrorStrict JSON schema is enabled, but the output type is not valid. Either make the output type strict, or wrap your type with AgentOutputSchema(YourType, strict_json_schemaFalse)这条报错信息本身就是最实用的排错指引要么改造类型使其满足严格约束要么显式声明strict_json_schemaFalse放弃严格模式。四、四个关键方法的行为细节4.1is_plain_text()与name()def is_plain_text(self) - bool: return self.output_type is None or self.output_type is strname()通过模块内的_type_to_str()src/agents/agent_output.py生成类型名简单类型取__name__如str、int泛型类型递归拼接为list[int]、dict[str, str]这样的字符串。4.2json_schema()按需取 Schemadef json_schema(self) - dict[str, Any]: if self.is_plain_text(): raise UserError(Output type is plain text, so no JSON schema is available) return self._output_schema纯文本类型调用会抛UserError非纯文本返回构造期生成的可能是严格化处理后的Schema。4.3validate_json()LLM 输出的最终把关这是校验链路的核心src/agents/agent_output.py逻辑如下调用_json.validate_json(json_str, self._type_adapter, partialFalse, strict...)做严格校验严格模式下strictTrue校验失败抛出的ModelBehaviorError若被判定为数据脱敏错误_is_error_data_redacted会先分离 traceback、把self置为None、把 JSON 替换为redacted后再抛出避免敏感数据泄漏到错误信息中若_is_wrapped为真则校验结果必须是 dict且必须包含response键否则抛出带详细信息的ModelBehaviorErrorExpected a dict, got ... 或 Could not find key response in JSON最终返回validated[response]包装类型或validated原生类型。这里还能看到错误追踪的细节校验失败时会通过_error_tracing.attach_error_to_current_span()把SpanError(messageInvalid JSON, data{...})挂到当前追踪 Span 上方便在 tracing 数据里定位模型输出问题。五、实战三种输出类型的完整用法5.1 基础用法dataclass 结构化输出最常规的用法是直接把 dataclass 传给output_type框架自动完成包装 → 生成 Schema → 严格化 → 校验全流程import asyncio from dataclasses import dataclass from agents import Agent, Runner dataclass class WeatherOutput: city: str temperature: float condition: str async def main(): agent Agent( nameWeatherAgent, instructions返回给定城市的天气信息。, output_typeWeatherOutput, ) result await Runner.run(agent, 北京今天天气如何) print(result.final_output) # WeatherOutput(city北京, temperature..., condition...) print(result.final_output.city) if __name__ __main__: asyncio.run(main())注意此时默认走严格模式strict_json_schemaTrue。如果WeatherOutput的字段类型全部满足严格约束运行会非常稳定反之会直接抛UserError。5.2 非严格模式何时需要strict_json_schemaFalse当输出类型无法满足严格 JSON Schema 约束时典型如dict[int, str]这类整型键必须显式关闭严格模式。仓库提供了可直接运行的完整示例 examples/basic/non_strict_output_type.py核心片段dataclass class OutputType: jokes: dict[int, str] # 非严格兼容整型键 # 严格模式会报错 try: await Runner.run(agent, input) except UserError as e: print(fError (expected): {e}) # 显式关闭严格模式 agent.output_type AgentOutputSchema(OutputType, strict_json_schemaFalse) result await Runner.run(agent, input) print(result.final_output)运行该示例可以观察到两个关键现象不处理时严格模式抛出UserError错误信息明确指向改为AgentOutputSchema(YourType, strict_json_schemaFalse)关闭严格模式后可以运行但示例 docstring 特别提醒非严格 Schema 下模型可能产出非法 JSON此时validate_json()会抛ModelBehaviorError——代码里也要准备好捕获这种可能性。5.3 自定义 Schema继承 AgentOutputSchemaBase如果需要完全接管 Schema 定义例如模型提供商不兼容自动生成的 Schema可以继承AgentOutputSchemaBase并实现四个抽象方法。同样参考 examples/basic/non_strict_output_type.py 中的演示类class CustomOutputSchema(AgentOutputSchemaBase): def is_plain_text(self) - bool: return False def name(self) - str: return CustomOutputSchema def json_schema(self) - dict[str, Any]: return { type: object, properties: {jokes: {type: object, properties: {joke: {type: string}}}}, } def is_strict_json_schema(self) - bool: return False def validate_json(self, json_str: str) - Any: json_obj json.loads(json_str) return list(json_obj[jokes].values()) # 自定义解析返回任意结构 # 使用 agent.output_type CustomOutputSchema() result await Runner.run(agent, input)这是最灵活的输出控制方式Schema 的生成、严格标志、JSON 解析完全由你决定返回值甚至可以不是原始 JSON 对象示例中把 jokes 字典转成了列表。自定义类通过isinstance(agent.output_type, AgentOutputSchemaBase)判断在 get_output_schema 中会被直接采用不再经过自动包装。六、与结果对象及公开 API 的关系校验成功后validate_json()返回的对象会成为运行结果final_output的内容最终以 RunResult对应 src/agents/result.py的形式返回给调用方。因此理解agent_output模块是理解结构化结果从哪来的关键一环。在公开 API 层面AgentOutputSchema、AgentOutputSchemaBase均通过 src/agents/init.py 导出from .agent_output import AgentOutputSchema, AgentOutputSchemaBase并在all中声明因此你可以直接from agents import AgentOutputSchema, AgentOutputSchemaBase无需关心内部模块路径。七、常见问题速查现象原因处理方式构造 Agent 时抛UserError: Strict JSON schema is enabled...输出类型不满足严格约束改造类型或AgentOutputSchema(YourType, strict_json_schemaFalse)运行时抛ModelBehaviorError非严格模式下模型产出了非法 JSON捕获ModelBehaviorError重试或调整 instructions调用json_schema()抛UserError输出类型是纯文本None/str先确认is_plain_text()为False输出类型是dict[int, str]、TypedDict 等框架用response键自动包装正常现象final_output会自动解包出真实对象需要完全自定义 Schema自动 Schema 不满足需求继承AgentOutputSchemaBase实现四个方法八、总结agents.agent_output模块虽然代码量不大却是 openai-agents-python 结构化输出的核心枢纽AgentOutputSchemaBase定义了输出 Schema 的统一契约AgentOutputSchema以strict_json_schema为开关、以自动包装与严格化处理为手段把任意 Python 类型转化为可供模型与校验链路使用的 JSON Schemavalidate_json()则在最后一道关卡保证结果的正确性与安全性包括脱敏。掌握AgentOutputSchema(YourType, strict_json_schemaFalse)与自定义AgentOutputSchemaBase子类这两条扩展路径你就能在绝大多数结构化输出场景下游刃有余。相关源码与示例可继续查阅 src/agents/agent_output.py、src/agents/run_internal/turn_preparation.py 与 examples/basic/non_strict_output_type.py。【免费下载链接】openai-agents-pythonA lightweight, powerful framework for multi-agent workflows项目地址: https://gitcode.com/GitHub_Trending/op/openai-agents-python创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考