Skip to content

第 07 章 大模型接入与流式推理(出书级) ​

先修:第 03 章(流式事件)、第 04 章(tool_rounds 位置)。
学完能做:指到 Provider 解析与 stream_chat_with_tools;解释为何必须累积完整 tool call;区分「上游 LLM 超时」与「对客户端心跳」。


07.1 本章目标 ​

  1. 看懂 Provider / 模型覆盖与 resolve_runtime。
  2. 理解发给模型的 messages 与 tools schema 从哪来。
  3. 弄清流式 tool call 为何必须累积完整再执行。
  4. 认识两层超时与静默心跳。
  5. 能对照一份日志标出「文本增量 → tool 完整 → execute」。

07.2 为何重要 ​

没有这一层,前面的 HTTP 与 Run 生命周期都是空壳:真正「想下一步」的是大模型。
联调里最常见的三类事故都落在本章:

现象常见根因
一直没 tool_startarguments 还在拼,或 finish 后未 drain 完
工具参数 JSON 炸半截 execute(实现 bug)或模型吐非法 JSON
前端「假卡死」上游还在想,本服务未发心跳;或代理缓冲

本仓用 OpenAI 兼容协议统一多家网关,业务不绑定某一家 SDK。


07.3 概念与心智模型 ​

目录总览:src/investoday/runtime/llm/

概念含义别和谁搞混
Provider端点 + 密钥 + 超时等运行时配置不是「某一个业务 Skill」
Model具体模型名字符串可被请求级覆盖
请求级覆盖本次 narrative 指定的 model/provider覆盖 Agent 默认
OpenAICompatibleClient统一 chat / tool calling 客户端不是上游账号系统
StreamToolUpdate流式过程中的增量/完成消息不是对外 SSE 的最终协议

持久化:{data_root}/registry/model-providers.json(见 ProviderStore)。


07.4 源码带读:Provider 解析 ​

打开:src/investoday/runtime/llm/provider_store.py
关注:ProviderStore.resolve_runtime(*, model, provider_id)

教学阅读顺序:

  1. list_providers / get_default_provider —— 管理面从哪列表
  2. resolve_runtime —— 返回直觉字段:providerId、model、baseUrl、apiKey、timeoutSeconds
  3. _seed_from_config / _load / _save —— 配置种子与落盘

再打开:openai_compatible.py 中的 OpenAICompatibleClient

方法用途
stream_chat_with_tools主入口(Agent 工具轮)
stream_chat仅文本增量
complete_chat_with_tools非流式,内部仍消费流式接口
_runtime合并 ClientRuntimeConfig 与 AppConfig

辅助类型:runtime/llm/types.py(ClientRuntimeConfig、StreamToolUpdate 等)。


07.5 发给模型的 messages(结构 + 组装入口) ​

每一轮工具轮,大致发送:

text
[
  { "role": "system", "content": "人设 + Skill 契约 + 交付提示 + …" },
  { "role": "user", "content": "…" },
  { "role": "assistant", "tool_calls": [ … ] },
  { "role": "tool", "tool_call_id": "…", "content": "工具结果…" },
  …
]

另附:tools: [ { name, description, parameters }, … ](来自工具注册表 schema)。

组装入口(带读)

阶段路径函数
Bootstrapagent_loop/bootstrap_ops/phase.pybootstrap_phase
系统提示门面agent_loop/prompt_ops/facade.pybuild_system_prompt
Skill 拼接skills/repository_ops/skill_prompt_builder.pybuild_skill_system_prompt
出站 messagesagent_loop/bootstrap_ops/context.pybootstrap_outbound_messages
预算agent_loop/prompt_ops/budget.pycontext_budget 等

小白检查点:上下文是稀缺资源。Skill 又长又空、每轮塞巨型 reminder,会直接又慢又傻。


07.6 源码带读:工具轮如何调模型 ​

打开:src/investoday/runtime/agent_loop/flow_ops/stream_ops/llm_stream.py
函数:stream_tool_round_llm

它做的事(教学翻译):

  1. 调用 client.stream_chat_with_tools(...)(传入 model、messages、tools、runtime、cancel_event 等)
  2. 边收帧边推送文本 / thinking 类事件
  3. 累积 tool call 的 name 与 arguments 增量
  4. 静默过久发心跳(见 07.8)
  5. 超时则尝试用已有部分内容做恢复事件
  6. 结束后把完整 assistant_message(含完整 tool_calls)交还给工具轮逻辑去 execute

取消:cancel_event=handle.stop_event 传入流式客户端;用户 stop 后应尽快打断等待。


07.7 流式 tool call 累积(全书重点) ​

打开:src/investoday/runtime/llm/openai_ops/stream_support.py
关注:_ToolCallAccumulator.absorb / finalize

链路:

text
SSE data: line
  → OpenAIStreamAttemptState.process_data_line()
      → delta["tool_calls"] → _ToolCallAccumulator.absorb()
  → 流结束 → accumulator.finalize()
  → build_stream_done_message(..., tool_calls=...)
  → StreamToolUpdate(kind="done", message=...)
  → 工具轮才 Registry.execute

absorb 按 index 合并 id / function.name / function.arguments(arguments 字符串拼接)。

为什么不能半截执行? ​

arguments 常是流式拼出来的 JSON。半截时:

text
{"fundCode": "00000

一执行必炸或行为未定义。所以:完整 JSON 可用后才进 Registry.execute。

代理坑:finish 早于 arguments ​

部分网关在 finish_reason == "tool_calls" 之后还继续吐 arguments。
代码注释要点:此时不应立刻关流,要继续读到 [DONE] 或上游关闭(见 stream_support 里 _should_close_finished_stream 相关逻辑)。

可对照样例(教学用) ​

上游增量(示意):

json
{"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_1","function":{"name":"investoday_api","arguments":"{\"e"}}]}}]}

下一帧继续:

json
{"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"ndpoint\":\"x\"}"}}]}}]}

累积完成后才是:

json
{
  "role": "assistant",
  "tool_calls": [
    {
      "id": "call_1",
      "type": "function",
      "function": {
        "name": "investoday_api",
        "arguments": "{\"endpoint\":\"x\"}"
      }
    }
  ]
}

此时才允许 execute;workspace 才会出现完整的 tool_calls/*.args.json。


07.8 超时与心跳(两层) ​

A. 上游 LLM SSE 层 ​

符号直觉位置含义
单行轮询超时约 0.1sstream_support不断开连接,用于可取消等待
httpx.Timeout(timeout_seconds, connect=30)openai_compatible整次请求超时来自 Provider
上游重试_MAX_UPSTREAM_RETRIES 等瞬断退避

B. Agent 循环 / 对客户端心跳 ​

符号位置含义
SILENCE_HEARTBEAT_SECONDS = 8.0runtime/stream_keepalive.py静默过久发心跳(注释:代理 idle 常 15~30s)
SilenceHeartbeat.maybe_heartbeat同上发 assistant_thinking_chunk 或 agent_progress
iter_with_silence_heartbeat同上包装 async iterator
工具轮 LLM 等待上限约 300sllm_stream.py 内常量单轮「模型思考」保险丝

容量画像:本服务是长连接、少并发、高时长,不是秒级 QPS API。按「同时活跃 Run」估容量。


07.9 失败与排障 ​

现象先看正确态度
无 tool_start流是否已 done、arguments 是否完整等累积,不猜半截
401/403Provider apiKey / 网关权限修配置,不改 Skill
超时杀 RunProvider timeout vs 工具轮 300s vs 网关分层对照,勿只加一轮
前端假卡死是否有 heartbeat;Nginx 是否缓冲见第 13 章 SSE 坑
stop 不停cancel_event 是否传入客户端查 stream_tool_round_llm 传参

决策树:

text
模型侧异常?
  → 先看 Provider resolve 与网关日志
  → 再看 llm_stream 是否超时/取消
  → 再看 tool_calls 是否完整才 execute
  → 最后才怀疑 Skill 写得差

07.10 与前后章关系 ​

  • 上承第 04/06 章:tool_rounds 里「问模型」发生在本章客户端;「执行工具」在 Registry。
  • 下接第 08 章:完整 tool call 之后,金融工具才进 CLI。
  • 边界:业务口径写进 Skill;密钥、超时、协议兼容写进 Runtime / Provider。

07.11 本章小结 ​

  • Provider 管端点与密钥;请求可覆盖模型。
  • messages = system(Skill/人设)+ 历史 + tool 结果;tools 来自注册表。
  • 流式 tool call 必须累积完整再 execute。
  • 心跳防代理掐流;超时要分清上游与工具轮两层。
  • stop 依赖 cancel_event 传到客户端。

07.12 练习 ​

  1. 在 llm_stream.py 找到 stream_chat_with_tools 调用,列出传入的关键参数名。
  2. 在 stream_support.py 找到 _ToolCallAccumulator,用三句话说明 absorb 做什么。
  3. 用一份日志标出:文本 delta 与 tool 完整后 execute 的先后。
  4. 简答:若 arguments 流到一半就 execute,会出现什么?

07.13 参考答案要点 ​

  1. 至少包含 model、messages、tools、runtime、cancel_event(名称以源码为准)。
  2. 按 index 合并 id/name,并把 arguments 字符串增量拼起来,finalize 后输出完整列表。
  3. 通常先有增量,后有完整 assistant tool_calls,再 tool_start;以你的流为准。
  4. JSON 解析失败 / 错误参数 / 异常 tool result,浪费一轮且污染上下文。

过关标准 ​

  • [ ] 能说明 provider 与请求覆盖,并指到 resolve_runtime
  • [ ] 能画出 messages 里 system/user/assistant/tool 角色
  • [ ] 能解释必须累积完整 tool call 的原因,并指到 _ToolCallAccumulator
  • [ ] 能区分上游超时与对客户端心跳
  • [ ] 知道 stop 如何传到流式客户端

✨ 网站运行时间: 5年2月29天 ❤️ 道阻且长,行则将至 - 微信号: heikedreamer