GoForum🌐 V2EX

在 OpenClaw 中使用 HodlAI Claude 模型开启 Prompt Cache:需要改一行代码 + Opus 4.6 计费异常反馈

finne · 2026-02-09 13:17 · 0 次点赞 · 5 条回复

最近在用 HodlAI 的 Claude 模型跑 OpenClaw (一个 AI agent 框架),发现默认情况下 prompt cache 不生效,研究了一下原因和解决方案,分享给有需要的朋友。

背景

HodlAI 的 API 兼容 OpenAI Chat Completions 格式,支持 Anthropic 的 prompt caching 机制——需要在 messages 中对 content block 加上 cache_control: {"type": "ephemeral"} 标记。

但 OpenClaw 底层( pi-ai 库)的 maybeAddOpenRouterAnthropicCacheControl 函数默认只对 OpenRouter 的 anthropic/* 模型注入 cache_control,自定义 provider 的 Claude 模型不会走这个逻辑,导致 cache 完全不生效。

解决方案:改一行代码

文件路径:

node_modules/@mariozechner/pi-ai/dist/providers/openai-completions.js

找到 maybeAddOpenRouterAnthropicCacheControl 函数,原始代码:

function maybeAddOpenRouterAnthropicCacheControl(model, messages) {
    if (model.provider !== "openrouter" || !model.id.startsWith("anthropic/"))
        return;

改为:

function maybeAddOpenRouterAnthropicCacheControl(model, messages) {
    const isOpenRouter = model.provider === "openrouter" && model.id.startsWith("anthropic/");
    const isClaudeOnCustomProvider = model.id.toLowerCase().includes("claude");
    if (!isOpenRouter && !isClaudeOnCustomProvider)
        return;

这样只要 model ID 包含 “claude”(不区分大小写),就会自动注入 cache_control

⚠️ 注意:OpenClaw 更新或 npm update 后会覆盖这个改动,需要重新打 patch 。

测试结果

改完后实测各模型缓存情况:

模型 Cache 命中 计费是否正常
Claude Sonnet 4.5 ✅ 正常(降约 91%)
Claude Opus 4.5 ✅ 正常(降约 91%)
Claude Opus 4.6 ✅ 后台显示命中 ❌ 仍按全量计费
Claude Opus 4-6 ✅ 后台显示命中 ❌ 仍按全量计费

Sonnet 4.5 和 Opus 4.5 缓存命中后费用从 ~\(0.035 降到 ~\)0.003 ( 9k tokens 测试),效果很明显。

Opus 4.6 和 Opus 4-6 虽然后台日志显示 cache 命中了,实际扣费还是按全量计算,感觉是 HodlAI 后端对这两个新模型的 cached token 计价还没适配好。

总结

  1. HodlAI Claude 模型 支持 prompt cache,但仅限 Chat Completions API + 显式 cache_control 标记
  2. OpenClaw 用户需要手动 patch 一行代码让 cache 注入生效
  3. Sonnet 4.5 / Opus 4.5 计费正常,cache 能省约 90% 费用
  4. Opus 4.6 / Opus 4-6 计费疑似有 bug ,希望官方看一下 🙏 @88

有用同样方案的朋友可以试试,省不少钱。

5 条回复
88AI · 2026-02-09 13:37
#1

厉害厉害,支持缓存了!我们已自动添加 cache_control: {“type”: “ephemeral”} 标记,用户无需手动添加。

finne · 2026-02-09 13:42
#2

@88AI 但是我看日志里的 opus4.6 还是按全量的价格计费呀

88AI · 2026-02-09 13:47
#3

@finne 更新了

finne · 2026-02-09 13:47
#4

@88AI okok 刚刚测试下 opus4.6 cache 计费正常工作了

workbest · 2026-02-09 13:52
#5

awesome

添加回复
你还需要 登录 后发表回复

登录后可发帖和回复

登录 注册
主题信息
作者: finne
发布: 2026-02-09
点赞: 0
回复: 0