mainspring.output¶
结构化输出三策略(原生 json_schema / prompt 校验 / 工具折叠)
本页由
scripts/gen_api_docs.py从模块__all__自动生成,请勿手改。 新增或删除公开符号:先改模块__all__与tests/test_public_api.py快照, 再重新生成本页。
结构化输出三策略(T3-4):按 Profile 自动分派,不靠用户手配。
为什么要三套策略而不是三套 API:
Profile.supports_json == "json_schema" → 原生结构化输出(OpenAI / Gemini)
Profile.supports_json == "json_object" → 只支持「对象模式」:注入 schema 指令 + 校验重试
Profile.supports_json is None → 连对象模式都没有:把 schema 包成一个工具让模型调
分派看的是模型能力,不是调用方偏好——同一份 Agent.output_type 声明在三家方言上都能跑,
用户不需要知道自己在哪一档。
两条边界写死在实现里:
- 校验失败要反馈重试,且成本不许吞:每次重试都是一次真实调用,用量逐次累加后随最终响应
返回(
ModelResponse.usage是三次调用之和,attempts是真实调用次数)。重试次数用尽抛OutputValidationError,错误里带每次的校验明细,排查不用靠猜; - 结构化只约束终答:中间轮该调工具照调(wrapper 见到 tool_calls 原样透传,不校验也不 折叠)——否则「先查数再总结」这类任务会在第一步就被判「输出不合 schema」。
策略 C(tool_call)的折叠:模型调用合成的 final_answer 工具时不进工具管道,而是就地翻成
一条普通助手消息(content 是 JSON 参数原文)。因此它不会被执行、不会落 tool 消息、也不经过
Hook 白名单——合成工具没有副作用,把它当真实工具审反而会误导。
v1 边界(如实记录):流式下结构化校验不重试(已推出的半个答案不能撤回),失败直接上抛; 重试过程中的临时反馈消息不进 Session 历史(只在模型层存在),历史里只有最终答案。
用法:用 StructuredOutputModel(inner, OutputModel) 包住任意 ChatModel 再交给 Runner,
套在模型链哪个位置都行;重试明细沿包装链由 drain_output_retries 收集(与 drain_fallbacks
同一套遍历),由 Runner 发 output 侧 guardrail 事件。
OutputStrategy
module-attribute
¶
OutputRetry ¶
OutputValidationError ¶
Bases: AgentRunError
结构化输出校验失败(重试用尽)。
errors 是最后一次失败的校验明细(历次记录走 OutputRetry / drain_retries,不堆进 异常);继承 AgentRunError,调用方按运行错误的同一捕获面处理,无需特判。
StructuredOutputModel ¶
Bases: ChatModel
结构化输出包装器(T3-4):塑形 → 调用 → 校验 → 反馈重试。
组合器(与 FallbackModel / ConcurrencyLimitedModel 同):profile / provider / settings
透传,可与它们任意嵌套;降级记录仍能在最外层被 drain_fallbacks 取到。
max_retries 语义:额外重试上限,总调用次数 ≤ max_retries + 1(首查 + 重试);0 表示 不重试,校验失败当场抛——重试成本由此参数显式封顶,不会静默放大账单。
__init__ ¶
__init__(
inner: ChatModel,
output_type: type[BaseModel],
*,
max_retries: int = 2,
) -> None
drain_retries ¶
drain_retries() -> list[OutputRetry]
取走并清空重试记录(Runner 每次调用后发 output 侧 guardrail 事件)。
chat
async
¶
chat(
messages: list[Message],
tools: list[ToolSpec],
settings: ModelSettings,
) -> ModelResponse
非流式主路径:注入指令/工具 → 调用 → 校验 → 失败反馈重试。
成功返回的 message 必已通过 output_type 校验;usage 是逐次调用的合计,attempts 是 真实调用次数——两者都按「花掉的钱如实上报」口径,不含任何估算。
stream
async
¶
stream(
messages: list[Message],
tools: list[ToolSpec],
settings: ModelSettings,
) -> AsyncIterator[StreamEvent]
流式:增量原样转发,收尾校验一次(已推出的内容撤不回来,所以不重试)。
策略 C 在流式下直接拒绝:它的实现前提是「看到 final_answer 工具调用再折叠成终答」, 而增量一旦推出去就已经被调用方看到,折叠不成立。
drain_output_retries ¶
drain_output_retries(model: ChatModel) -> list[OutputRetry]
收集包装链上的重试记录(与 drain_fallbacks 同一条遍历:inner + segments)。
套在 FallbackModel 里面时走 segments,套在限流 / 回放外面时走 inner —— 两条路
都走通,才不会出现「重试真的发生了,但 trace 里一条记录都没有」。
output_prompt ¶
output_prompt(
output_type: type[BaseModel], strategy: OutputStrategy
) -> str
注入 system 尾部的结构化指令(策略 A 不需要:约束已经在原生参数里)。
两个变体:prompt_json 要求纯 JSON 文本;tool_call 明示「中间步骤可正常调其他工具」, 防止模型把中间轮也当 final_answer 提交。schema 序列化固定 sort_keys,同一 output_type 生成的指令文本逐字节稳定——prompt 缓存与 fixture 请求指纹不因字典序波动而漂移。
output_tools ¶
output_tools(
output_type: type[BaseModel], strategy: OutputStrategy
) -> list[ToolSpec]
策略 C 的合成工具声明(仅承载 schema;不注册进 ToolRegistry)。
非策略 C 返回空列表;调用方按 [*用户工具, *合成工具] 拼接(chat/stream 均如此), 合成工具排尾部,不挤占用户工具的展示位置。
parse_output ¶
parse_output(
message: Message, output_type: type[BaseModel]
) -> BaseModel
从助手消息里取出 JSON 并校验;失败抛 OutputValidationError(带可读明细)。
三步:剥围栏 → json.loads → model_validate,各自失败都归一为同一个异常类型,调用方 无需按失败形态分流;空文本同样视为失败(没有任何内容可解析)。
response_format_for ¶
response_format_for(
output_type: type[BaseModel], strategy: OutputStrategy
) -> dict[str, Any] | None
策略 A 的原生 response_format;其余策略返回 None(不下发无意义的参数)。
name 取 output_type 类名,schema 由 pydantic 现场导出——与 parse_output 校验用的 model_validate 同源,「下发给模型的约束」和「本地校验的标尺」不会各说各话。
select_strategy ¶
select_strategy(profile: ModelProfile) -> OutputStrategy
Profile 三态 → 策略(§2.8):json_schema / json_object / 不支持。
只读 supports_json 一个字段的纯函数:同一 profile 恒定映射同一策略,是 StructuredOutputModel 构造期分派的唯一依据——分派错档,注入的指令/工具全会错位。