跳转至

mainspring.model

ChatModel 抽象、模型设置、Provider 注册与包装器(降级 / 限流 / 测试替身)

本页由 scripts/gen_api_docs.py 从模块 __all__ 自动生成,请勿手改。 新增或删除公开符号:先改模块 __all__ 与 tests/test_public_api.py 快照, 再重新生成本页。

模型层:Runner 与真实 LLM 端点之间的唯一边界。

数据流:上层(Runner / Agent)持有 ChatModel,经 chat(一次性)或 stream(逐帧)调用; 方言适配在 core/providers/,本模块只定契约与公共机制——重试(call_with_retry)、 断流重试(stream_single_retry)、流式聚合(StreamAggregator)、多模型降级(FallbackModel) 与零网络测试替身(TestModel)。实现方必须把一切失败映射为 ModelAPIError 并带上 error_type / retryable(分类表见 core/errors.py):上层对错误的一切处置都靠这两个字段。

两级容错各管一段,不要越界:call_with_retry 在单模型内按 RetryPolicy 退避,耗尽后把 retryable 置 False 上抛;FallbackModel 据此换模型,自己不再退避。流式另有硬约束:内容 帧一旦推出就无法撤回,故断流重试与流式降级都只允许发生在首帧之前。

T1-2 落地(§2.3 / §2.8 / §2.11;六轮终审归属调整):

ChatModel      chat / stream 双入口 + profile / provider 挂载
ModelSettings  单次调用可调项全集(方言专有参数走 Provider.extra,不进本表)
RetryPolicy    可重试标签白名单 + 指数退避 + 抖动;call_with_retry 为执行器
Provider       鉴权与端点来源(api_key 为 SecretStr,序列化自动掩码)
ModelProfile   能力标志(降级与压缩的公共分母)
StreamEvent    provider 层流式增量;StreamAggregator 聚合为 ModelResponse
TestModel      最小脚本化模型,支撑后续全部单测(CI 零 API 调用)

ToolSpec / ToolCall / ToolResult 整组归 types.py:ChatModel 签名引用它们、tool.py 又引 RetryPolicy,留在这里会构成 model.py ↔ tool.py 环(六轮终审)。 异常层级单点收口在 core/errors.py(ADR-012)。

ChatModel

Bases: ABC

模型层契约(§2.11):chat / stream 双入口 + profile / provider 挂载。

实现方职责:两个入口收到的 settings 是本次调用的权威配置(retry / timeout 亦随调用 传入,见 _openai_compat 的编排);失败必须收敛为 ModelAPIError,不得裸抛 httpx / SDK 异常——否则重试与降级两层判据全部失效。profile / provider 与实现正交,换端点换厂商 不动实现类(工厂与能力守卫见 providers/base.py)。

profile instance-attribute

profile: ModelProfile = profile

provider instance-attribute

provider: Provider = provider

settings instance-attribute

settings: ModelSettings = settings or ModelSettings()

__init__

__init__(
    *,
    profile: ModelProfile,
    provider: Provider,
    settings: ModelSettings | None = None,
) -> None

chat abstractmethod async

chat(
    messages: list[Message],
    tools: list[ToolSpec],
    settings: ModelSettings,
) -> ModelResponse

stream abstractmethod

stream(
    messages: list[Message],
    tools: list[ToolSpec],
    settings: ModelSettings,
) -> AsyncIterator[StreamEvent]

ConcurrencyLimitedModel

Bases: ChatModel

并发限流包装器(T2-9):同一模型同时在途调用不超过 limit。

组合优于继承——它自己就是 ChatModel,profile / provider / settings 全部透传,因此可以和 任意模型包装器(FallbackModel、录制回放、重试装饰器)按任意顺序嵌套,限流层不必知道 内层是谁;peak / in_flight 是观测口,让「真的限住了」可以被断言,而不是靠读代码相信。

并发约束:槽位自获取起持有到 chat 返回 / stream 耗尽(含异常与上游放弃消费),一条 慢流会占住一个坑;计数在信号量临界区内更新,单事件循环内无竞态。

inner instance-attribute

inner = inner

limit instance-attribute

limit = limit

peak instance-attribute

peak = 0

in_flight property

in_flight: int

当前在途调用数(观测用)。

__init__

__init__(inner: ChatModel, *, limit: int = 4) -> None

chat async

chat(
    messages: list[Message],
    tools: list[ToolSpec],
    settings: ModelSettings,
) -> ModelResponse

stream async

stream(
    messages: list[Message],
    tools: list[ToolSpec],
    settings: ModelSettings,
) -> AsyncIterator[StreamEvent]

FallbackEvent

Bases: BaseModel

一次降级记录(§2.4 model_fallback 事件的模型层来源,T3-3)。

降级事实发生在模型层,事件落点只能在 Runner——所以模型层先记账,Runner 在调用返回后 drain_fallbacks() 取走并补上 run_id / step_id 发成 RunEvent(provider 层不产 RunEvent 的分层不变)。reason 区分「失败后降级」与「冷却窗口命中直接走备选」。

from_model instance-attribute

from_model: str

to_model instance-attribute

to_model: str

error_type instance-attribute

error_type: str

reason class-attribute instance-attribute

reason: Literal['error', 'cooldown'] = 'error'

FallbackModel

Bases: ChatModel

多模型容灾组合器(T3-3):错误分类 → 按序降级 → 冷却窗口。

三条边界写死在实现里,而不是留给调用方「记得」:

  1. 只有值得降级的错误才降级:判据是 DEGRADABLE_ERROR_TYPES(T2-9 分类表)。 invalid_request 换一家也一样错,content_filter 换一家也被拦——这类错误原样上抛, 否则只是把同一个 400 拿去别处再撞一次;
  2. 重试在降级之前:内层模型自己的 call_with_retry 已经用尽退避,到这里说明该换模型了 (retryable=False),这一层不再退避;
  3. 流式遵循 ADR-003 简化策略:首字节前失败可降级,一旦开始向外推流就不再降级—— 半个回答接半个回答会污染上下文,不如让上层明确失败。

失败的一段进入冷却窗口(cooldown 秒),窗口内后续调用直接跳过它但仍会记一条 reason="cooldown" 的降级记录(审计要能回答「这次为什么没用主模型」); 全部段都在冷却时按序照试(fail-open):宁可在冷却期试一次,也不硬失败。

cooldown instance-attribute

cooldown = cooldown

fallbacks_taken instance-attribute

fallbacks_taken = 0

chain property

chain: list[str]

降级链的模型标识(声明序)。

failures property

failures: dict[str, int]

各段累计失败次数(冷却判定之外的运维视图)。

segments property

segments: tuple[ChatModel, ...]

各段模型对象(声明序)。

它是「穿透取记录」的公开入口:FallbackModel 有多个下游而不是单个 .inner, 审计函数(降级 / 结构化重试)只能靠它走进去,否则套在里面的记录会被静默丢掉。

__init__

__init__(
    primary: ChatModel,
    *fallbacks: ChatModel,
    cooldown: float = 30.0,
    clock: Callable[[], float] | None = None,
) -> None

cooldown_remaining

cooldown_remaining(model: str) -> float

指定模型还剩多少秒冷却(不在冷却返回 0)。

drain_fallbacks

drain_fallbacks() -> list[FallbackEvent]

取走并清空待上报的降级记录(Runner 每次调用后调用一次)。

chat async

chat(
    messages: list[Message],
    tools: list[ToolSpec],
    settings: ModelSettings,
) -> ModelResponse

按序尝试降级链;段失败即记账换下一段,全部失败抛链上最后一个错误。

stream async

stream(
    messages: list[Message],
    tools: list[ToolSpec],
    settings: ModelSettings,
) -> AsyncIterator[StreamEvent]

流式降级:先取首帧再对外产出,首帧后的失败一律上抛(ADR-003)。

ModelCall dataclass

TestModel 记录的一次调用,便于断言消息 / 工具 / 设置。

messages instance-attribute

messages: list[Message]

tools instance-attribute

tools: list[ToolSpec]

settings class-attribute instance-attribute

settings: ModelSettings = field(
    default_factory=ModelSettings
)

__init__

__init__(
    messages: list[Message],
    tools: list[ToolSpec],
    settings: ModelSettings = ModelSettings(),
) -> None

ModelProfile

Bases: BaseModel

模型能力画像(§2.8):能力标志驱动降级,不靠运行时撞错。

消费方:providers.base 的 apply_profile / check_message_capabilities 以此做调用前 守卫(硬需求缺报错、软需求降级告警),context_window 供 Runner 的上下文压缩定窗口, supports_json 决定 output.py 结构化输出走哪条路径。默认全关是保守原则:错开能力 的代价是撞 provider 500,多关一个的代价只是少一项优化。

model instance-attribute

model: str

context_window instance-attribute

context_window: int

max_output_tokens class-attribute instance-attribute

max_output_tokens: int | None = None

supports_tools class-attribute instance-attribute

supports_tools: bool = False

supports_parallel_tool_calls class-attribute instance-attribute

supports_parallel_tool_calls: bool = False

supports_json class-attribute instance-attribute

supports_json: (
    Literal["json_schema", "json_object"] | None
) = None

supports_reasoning class-attribute instance-attribute

supports_reasoning: bool = False

supports_prompt_cache class-attribute instance-attribute

supports_prompt_cache: bool = False

supports_vision class-attribute instance-attribute

supports_vision: bool = False

ModelSettings

Bases: BaseModel

单次调用可调项全集(§2.3)。

方言专有参数(top_k / num_ctx / Bedrock region 等)走 Provider.extra,不进本表—— ModelSettings 只收跨厂商公共分母。timeout / retry 是调用编排而非采样参数,也在本表: 每次调用自带完整的墙钟与退避策略,provider 层无需再向外找配置。

temperature class-attribute instance-attribute

temperature: float | None = None

top_p class-attribute instance-attribute

top_p: float | None = None

max_output_tokens class-attribute instance-attribute

max_output_tokens: int | None = None

stop class-attribute instance-attribute

stop: list[str] = []

timeout class-attribute instance-attribute

timeout: float = 120.0

retry class-attribute instance-attribute

extra_headers class-attribute instance-attribute

extra_headers: dict[str, str] = {}

reasoning_effort class-attribute instance-attribute

reasoning_effort: (
    Literal["minimal", "low", "medium", "high"] | None
) = None

cache_hint class-attribute instance-attribute

cache_hint: bool = True

replay_thinking class-attribute instance-attribute

replay_thinking: bool = False

response_format class-attribute instance-attribute

response_format: dict[str, Any] | None = None

tool_choice class-attribute instance-attribute

tool_choice: (
    Literal["auto", "none", "required"] | str | None
) = None

parallel_tool_calls class-attribute instance-attribute

parallel_tool_calls: bool | None = None

seed class-attribute instance-attribute

seed: int | None = None

Provider

Bases: BaseModel

鉴权与端点来源(§2.11;归 model.py,六轮终审自 providers/base.py 前移)。

api_key 为 SecretStr:序列化自动掩码;密钥只经环境变量进入,永不进事件 / trace。 extra 为方言逃逸口(Bedrock region / Vertex project / 端点专有参数)。

name instance-attribute

name: str

base_url class-attribute instance-attribute

base_url: str | None = None

api_key class-attribute instance-attribute

api_key: SecretStr | None = None

api_version class-attribute instance-attribute

api_version: str | None = None

extra class-attribute instance-attribute

extra: dict[str, Any] = {}

RetryPolicy

Bases: BaseModel

重试策略(§2.3):error_type 白名单 + 指数退避 + 抖动。

retry_on 按 ModelAPIError.error_type 过滤(默认三项与 errors.RETRYABLE_ERROR_TYPES 同源,均由 T2-9 分类表派生),而不是按异常类型判断——非 ModelAPIError 一律不重试。 max_attempts 是总尝试次数(含首次);退避公式见 call_with_retry,tool.py 的工具 重试复用本模型与同一公式。

max_attempts class-attribute instance-attribute

max_attempts: int = 3

initial_backoff class-attribute instance-attribute

initial_backoff: float = 1.0

max_backoff class-attribute instance-attribute

max_backoff: float = 30.0

retry_on class-attribute instance-attribute

retry_on: tuple[str, ...] = (
    "rate_limit",
    "server_error",
    "timeout",
)

StreamAggregator

把 provider 流式增量聚合为完整 ModelResponse(1.4 SSE 边界 / 2.4)。

容忍空 choices 帧(仅 usage)、finish_reason 中间帧为 null(以末帧为准)。 末帧完全缺失时按聚合结果推断(§2.4「以聚合结果为准」):有工具调用即 tool_calls,否则 stop——否则兼容端点省略 finish 帧时工具会被静默丢弃。

__init__

__init__() -> None

feed

feed(event: StreamEvent) -> None

result

result() -> ModelResponse

组装最终响应;工具调用按 index 升序(分片乱序到达仍还原模型声明序)。

StreamEvent

Bases: BaseModel

provider 层流式增量(§2.11 辅助类型;T3-5 细化)。

与运行层 RunEvent 是两层:ChatModel.stream 产 StreamEvent,Runner 组装为 RunEvent。 signature 承载 Anthropic 的 signature_delta(T3-1):思考文本与签名在流式里是两个 独立分片,聚合器要把签名补回 Message.thinking_signature,否则工具链后续轮回传会失败。 attempts 只落在 finish 帧上(T3-5):断流重试过一次就要如实上报,否则 llm_call 会声称「一次就成功」,把重试成本藏起来。

type instance-attribute

type: Literal[
    "text", "thinking", "tool_call", "usage", "finish"
]

text class-attribute instance-attribute

text: str | None = None

thinking class-attribute instance-attribute

thinking: str | None = None

signature class-attribute instance-attribute

signature: str | None = None

tool_call class-attribute instance-attribute

tool_call: ToolCallDelta | None = None

usage class-attribute instance-attribute

usage: Usage | None = None

finish_reason class-attribute instance-attribute

finish_reason: ModelFinishReason | None = None

attempts class-attribute instance-attribute

attempts: int | None = None

TestModel

Bases: ChatModel

脚本化模型(CI 主力,零网络):按顺序回放,字符串自动包成助手消息。

responses 里可以是 ModelResponse / str / Exception(第 N 次调用抛出,用于异常路径)。 脚本耗尽抛 AgentRunError——故意不返回默认回答:少写一条脚本和「用例其实没跑到底」 长得一模一样,静默兜底会把这类错误藏起来。

T2-8 完善:add 运行中追加脚本、call_count / last_call 断言便利属性、 assert_exhausted 锁住「脚本必须全部用完」。

__test__ class-attribute instance-attribute

__test__ = False

calls instance-attribute

calls: list[ModelCall] = []

call_count property

call_count: int

remaining property

remaining: int

未消耗的脚本条数。

last_call property

last_call: ModelCall

最近一次调用(断言模型看到了什么);尚无调用即报错。

__init__

__init__(
    responses: list[ModelResponse | str | Exception]
    | None = None,
    *,
    profile: ModelProfile | None = None,
    provider: Provider | None = None,
    settings: ModelSettings | None = None,
) -> None

add

add(*items: ModelResponse | str | Exception) -> None

追加脚本(多步场景里前一步结果决定后一步怎么答时用)。

assert_exhausted

assert_exhausted() -> None

脚本必须全部用完:剩下条目说明用例少跑了步骤,断言其实没验到。

chat async

chat(
    messages: list[Message],
    tools: list[ToolSpec],
    settings: ModelSettings,
) -> ModelResponse

stream async

stream(
    messages: list[Message],
    tools: list[ToolSpec],
    settings: ModelSettings,
) -> AsyncIterator[StreamEvent]

ToolCallDelta

Bases: BaseModel

流式工具调用分片;聚合器按 index 归组,同组 name / arguments 为增量拼接。

id 例外:非空即覆盖而非拼接(部分端点会在首帧之后重复补发完整 id)。

index class-attribute instance-attribute

index: int = 0

id class-attribute instance-attribute

id: str | None = None

name class-attribute instance-attribute

name: str | None = None

arguments class-attribute instance-attribute

arguments: str | None = None

call_with_retry async

call_with_retry(
    operation: Callable[[], Awaitable[T]],
    policy: RetryPolicy,
    *,
    sleep: Callable[[float], Awaitable[None]] | None = None,
) -> tuple[T, int]

按 RetryPolicy 执行 operation,返回 (结果, 总尝试数)。

重试判据三条同时满足才退避重来:ModelAPIError 实例、.retryable 为真、error_type 在 policy.retry_on 白名单内;其余错误原样上抛。退避 = min(max_backoff, initial_backoff * 2^(attempt-1)) * 抖动(0.5~1.5,防同批调用同刻重发); sleep 参数供测试注入假时钟,免得单测真的睡在退避上。

重试耗尽时抛新的 ModelAPIError 且 retryable=False:这一层已经用尽手段, 上层(FallbackModel)该做的不是再退避,而是换模型——错误类型 / 状态码 / provider 原样保留,只是把「还能重试」这一项关掉。

drain_fallbacks

drain_fallbacks(model: ChatModel) -> list[FallbackEvent]

收集模型包装链上累积的降级记录(降级在模型层,事件由 Runner 落 trace)。

沿包装链向内走:调用方常把限流 / 录制回放套在 FallbackModel 外面,降级记录在最里层, 不穿透取就会被静默丢掉。_walk_models 同时走 .inner(单下游)与 .segments (FallbackModel 的多下游),因此 FallbackModel(FallbackModel(a, b), c) 这种嵌套也取得到。

stream_single_retry async

stream_single_retry(
    open_stream: Callable[[], AsyncIterator[StreamEvent]],
) -> AsyncIterator[StreamEvent]

SSE 断流在单次调用内重试一次(T3-5 / ADR-003 边界)。

两条判据缺一不可:

  1. 一帧内容都还没向外推:已推出去的半个回答撤不回来,重来只会让调用方看到两段 拼接的答案(usage / finish 这类元数据帧算「尚未推出内容」,它们撤回无害);
  2. 错误可重试(ModelAPIError.retryable):网络抖动 / 5xx / 超时值得重来, 401 / 400 再来一次还是同一个结果。

重试固定 1 次且立即重来(不按 RetryPolicy 退避):流已经开着,长退避只是把客户端晾在 那儿;也不跨步重试——跨步是 Runner 的循环语义,模型层不替它决定再花一步。

重试次数落在 finish 帧的 attempts 上,聚合器据此回填 ModelResponse.attempts, 免得 llm_call 声称「一次就成功」把重试成本藏掉。