436 字
2 分钟
New-Api 使用参数覆盖解决 Claude Code x-anthropic-billing-header 缓存失效问题
0. 前言
使用自建 New-Api,在 OpenCode 上还好好的,换到 Claude Code 以后就没见过缓存命中的标识。之前还以为是特性,结果前几天刷到相关技术新闻,才知道是 Anthropic 悄咪咪往 System Prompt 里面塞东西,导致缓存前缀不匹配。网络上有现成的客户端解决办法,但现尝试在转发层进行过滤。
1. 问题原因
新版本 Claude Code 发送请求时会在 System Prompt 前面插入以下字符串:
x-anthropic-billing-header: cc_version=2.1.123.5d3; cc_entrypoint=cli; cch=7b56f;You are Claude Code, ...
其中这个 cch=7b56f; 每次请求都会变,导致缓存失效。
该字符串位于 messages.0.content。
2. 客户端解决办法
设置以下环境变量即可:
export CLAUDE_CODE_ATTRIBUTION_HEADER=0
export CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1
3. New-Api 参数过滤办法
用这一招可以直接把计费 header 直接删除。直接粘贴以下内容到 New-Api 的参数过滤里面:
{
"operations": [
{
"mode": "regex_replace",
"description": "删除 Claude Code 发送的 x-anthropic-billing-header,防止缓存失效",
"path": "messages.0.content",
"from": "^x-anthropic-billing-header:[\\s\\S]*?cch=[^;]*;",
"conditions": [
{
"path": "messages",
"mode": "contains",
"value": "x-anthropic-billing-header"
}
],
"logic": "OR"
},
{
"mode": "return_error",
"description": "检测到 x-anthropic-billing-header,返回错误",
"value": {
"message": "Detected invalid header: x-anthropic-billing-header, Please contact the admin to report this error.",
"status_code": 400,
"code": "invalid_request",
"type": "invalid_request_error"
},
"conditions": [
{
"path": "messages",
"mode": "contains",
"value": "x-anthropic-billing-header"
},
{
"path": "instructions",
"mode": "contains",
"value": "x-anthropic-billing-header"
},
{
"path": "messages",
"mode": "contains",
"value": "cch="
}
],
"logic": "OR"
}
]
}
该规则做了两件事:
- 用正则匹配
^x-anthropic-billing-header:[\\s\\S]*?cch=[^;]*;删除了messages.0.content中的x-anthropic-billing-header。 - 检测处理后是否还有没删干净的 header,如果有,返回客户端错误。
修改后,发往上游的提示词就正常了。提示词不含变化内容,缓存自然也就生效了。
另外,有的国内大模型厂商(如 DeepSeek)已经知晓此事并提前适配。
References:
- https://github.com/cnighswonger/claude-code-cache-fix/blob/main/README.zh.md
- https://github.com/claude-code-best/claude-code/issues/356
- https://linux.do/t/topic/2192543
- https://linux.do/t/topic/2049973
- https://github.com/QuantumNous/new-api/issues/1735
- https://linux.do/t/topic/2090128
- https://vibex.iflow.cn/t/topic/5923/62
- https://github.com/QuantumNous/new-api/issues/4678
- https://www.reddit.com/r/ClaudeAI/comments/1s7mkn3/psa_claude_code_has_two_cache_bugs_that_can/
New-Api 使用参数覆盖解决 Claude Code x-anthropic-billing-header 缓存失效问题
https://blog.lzc256.com/posts/new-api-use-arg-override-to-resolve-claude-code-cache-miss-caused-by-x-anthropic-billing-header/Loading Comment Component...
