You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@apisix.apache.org by "AlinsRan (via GitHub)" <gi...@apache.org> on 2026/10/12 02:17:42 UTC
[PR] fix(ai-proxy): include cache tokens in Anthropic prompt usage and read them from message_delta [apisix]
AlinsRan opened a new pull request, #14028:
URL: https://github.com/apache/apisix/pull/14028
### Description
Two problems in how the Anthropic Messages protocol reports token usage:
1. **Cache tokens in `message_delta` were dropped.** Streaming usage took `cache_read_input_tokens` / `cache_creation_input_tokens` only from `message_start`. Some Anthropic-compatible providers report the final usage, cache tokens included, only in `message_delta`. On those providers `$llm_cache_read_input_tokens` stayed `0`.
2. **Anthropic prompt tokens did not include cache tokens.** Anthropic reports cache tokens alongside `input_tokens`, not inside it. The gateway used `input_tokens` as `prompt_tokens`. So on Anthropic `$llm_prompt_tokens` / `$llm_total_tokens` meant something different than on OpenAI, where `prompt_tokens` already includes cached tokens. Because the field included no cache tokens, ratios such as cache reads / prompt tokens could exceed 100%.
#### Changes
The behavior follows LiteLLM (`AnthropicConfig.calculate_usage` and the streaming `_handle_usage` in `litellm/llms/anthropic/chat/`):
- `prompt_tokens = input_tokens + cache_read_input_tokens + cache_creation_input_tokens`
- `total_tokens = prompt_tokens + completion_tokens`
- Streaming accumulates the raw usage fields across `message_start` and `message_delta` before computing usage, so cache tokens reported in either event are counted.
- The Anthropic-to-OpenAI converter now subtracts `cache_creation_input_tokens` as well as `cached_tokens` from the OpenAI `prompt_tokens` when it builds the Anthropic `input_tokens`. LiteLLM's adapter does the same. Without this change, the converted non-streaming path would count cache-creation tokens twice under the new semantics.
The raw upstream usage (`ctx.llm_raw_usage`, which the `expression` strategy of `ai-rate-limiting` and the moderation plugins use) is unchanged.
#### Behavior change
For requests using the Anthropic Messages protocol with prompt caching:
- `$llm_prompt_tokens` and `$llm_total_tokens` (and the matching `llm_summary` log fields) now include cache read and cache creation tokens.
- `apisix_llm_prompt_tokens` and `apisix_llm_prompt_tokens_dist` count these tokens too.
- With `limit_strategy` set to `total_tokens` or `prompt_tokens`, `ai-rate-limiting` now counts cache tokens toward the quota. This matches how OpenAI-compatible requests are already counted.
- In a converted response (Anthropic client, OpenAI-compatible upstream), `input_tokens` excludes `cache_creation_input_tokens` when the upstream reports it.
Docs for `ai-proxy`, `ai-proxy-multi`, `ai-rate-limiting` and `prometheus` (en/zh) are updated.
#### Which issue(s) this PR fixes:
Fixes #
### Checklist
- [x] I have explained the need for this PR and the problem it solves
- [x] I have explained the changes or the new features added to this PR
- [x] I have added tests corresponding to this change
- [x] I have updated the documentation to reflect this change
- [ ] I have verified that this change is backward compatible (If not, please discuss on the [APISIX mailing list](https://github.com/apache/apisix/tree/master#community) first)
The change is not backward compatible for Anthropic token accounting, as described in "Behavior change" above.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@apisix.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] fix(ai-proxy): include cache tokens in Anthropic prompt usage and read them from message_delta [apisix]
Posted by "AlinsRan (via GitHub)" <gi...@apache.org>.
AlinsRan commented on PR #14028:
URL: https://github.com/apache/apisix/pull/14028#issuecomment-6163655185
Thanks @membphis, good catch. Fixed in 03ccd3347.
The cache-token lookups are now shared helpers in `openai-chat` (`cache_read_tokens()` / `cache_creation_tokens()`), used by both `parse_sse_event` / `extract_usage` and the Anthropic converter. Because the code is shared, the converted streaming path logs the same cache-creation value it sends to the client for every field the upstream may use: top-level `cache_creation_input_tokens`, and `prompt_tokens_details.cache_creation_tokens` / `cache_write_tokens` / `cache_creation_input_tokens`. The same applies to cache reads: the converter now also treats DeepSeek's `prompt_cache_hit_tokens` as cache reads, as the parser already did.
Added `t/plugin/ai-proxy-anthropic.t` TEST 71-74 (converted streaming, one per field shape, checking both the client SSE and the access log) and TEST 75 (unit test of `extract_usage` / `parse_sse_event` across the shapes).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@apisix.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] fix(ai-proxy): include cache tokens in Anthropic prompt usage and read them from message_delta [apisix]
Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #14028:
URL: https://github.com/apache/apisix/pull/14028#discussion_r4246656968
##########
apisix/plugins/ai-protocols/converters/anthropic-messages-to-openai-chat.lua:
##########
@@ -787,15 +814,18 @@ function _M.convert_response(res_body, ctx)
usage.output_tokens = completion_tokens
+ -- Anthropic input_tokens excludes both cache reads and cache writes,
+ -- while OpenAI prompt_tokens includes them (same as LiteLLM).
+ local creation = cache_creation_tokens(res_body.usage)
if type(details) == "table" then
local cached = details.cached_tokens or 0
- usage.input_tokens = math_max(0, prompt_tokens - cached)
+ usage.input_tokens = math_max(0, prompt_tokens - cached - creation)
Review Comment:
The stated raw-usage compatibility does not hold for non-streaming converted responses. `base.parse_response` converts `res_body` before assigning `ctx.llm_raw_usage` from `client_proto.extract_usage` (`apisix/plugins/ai-providers/base.lua:393-416`), so this changes an expression such as `cost_expr = "input_tokens"` from 20 to 15 for the updated fixture; moderation consumers see the changed value too. Preserve the original upstream usage before conversion (as the streaming path does), or document and test this additional behavior change.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@apisix.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] fix(ai-proxy): include cache tokens in Anthropic prompt usage and read them from message_delta [apisix]
Posted by "AlinsRan (via GitHub)" <gi...@apache.org>.
AlinsRan merged PR #14028:
URL: https://github.com/apache/apisix/pull/14028
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@apisix.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] fix(ai-proxy): include cache tokens in Anthropic prompt usage and read them from message_delta [apisix]
Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #14028:
URL: https://github.com/apache/apisix/pull/14028#discussion_r4246090347
##########
apisix/plugins/ai-protocols/anthropic-messages.lua:
##########
@@ -29,10 +29,49 @@ local sse = require("apisix.plugins.ai-transport.sse")
local table = table
local type = type
local ipairs = ipairs
+local pairs = pairs
local _M = {}
+-- Anthropic reports cache tokens alongside input_tokens rather than inside it,
+-- so add them back to get a prompt total with the same meaning as OpenAI's
+-- prompt_tokens. Mirrors LiteLLM's AnthropicConfig.calculate_usage.
+local function to_usage(raw)
+ local cache_read = raw.cache_read_input_tokens or 0
+ local cache_creation = raw.cache_creation_input_tokens or 0
+ local prompt = (raw.input_tokens or 0) + cache_read + cache_creation
+ local completion = raw.output_tokens or 0
+ return {
+ prompt_tokens = prompt,
+ completion_tokens = completion,
+ total_tokens = prompt + completion,
+ cache_read_input_tokens = cache_read,
+ cache_creation_input_tokens = cache_creation,
+ reasoning_tokens = 0,
+ }
+end
+
+
+-- message_delta usage is cumulative but may omit fields reported at
+-- message_start (and some providers only report cache tokens there), so
+-- accumulate the raw fields across events before computing usage.
+local function accumulate_usage(state, raw)
+ if type(state) ~= "table" then
+ return raw
+ end
+ local acc = state.anthropic_usage
+ if not acc then
+ acc = {}
+ state.anthropic_usage = acc
+ end
+ for k, v in pairs(raw) do
+ acc[k] = v
+ end
+ return acc
+end
Review Comment:
The function name/comment says “accumulate”, but the implementation is actually a field-wise merge/overwrite (last value wins) rather than numeric accumulation. To prevent future contributors from “fixing” it into a sum (which would break cumulative usage semantics), either rename it to something like `merge_usage_fields`/`coalesce_usage_fields` or adjust the comment to explicitly state it overwrites fields to preserve the latest cumulative values.
##########
apisix/plugins/ai-protocols/converters/anthropic-messages-to-openai-chat.lua:
##########
@@ -102,6 +102,33 @@ end
-- SSE event helpers
+-- prompt_tokens_details keys that carry cache-write tokens, in LiteLLM's
+-- order, followed by the cache_creation_input_tokens shape some upstreams use.
+local CACHE_CREATION_DETAIL_KEYS = {
+ "cache_creation_tokens",
+ "cache_write_tokens",
+ "cache_creation_input_tokens",
+}
+
+
+local function cache_creation_tokens(usage)
+ local v = usage.cache_creation_input_tokens
+ if type(v) == "number" and v > 0 then
+ return v
+ end
+ local details = usage.prompt_tokens_details
+ if type(details) == "table" then
+ for _, key in ipairs(CACHE_CREATION_DETAIL_KEYS) do
+ v = details[key]
+ if type(v) == "number" and v > 0 then
+ return v
+ end
+ end
+ end
+ return 0
+end
Review Comment:
`cache_creation_tokens` will raise an error if it’s ever called with a non-table `usage` (e.g., `nil`). Adding an early `if type(usage) ~= "table" then return 0 end` guard would make this helper safer and easier to reuse without relying on all call sites to pre-validate the shape.
##########
docs/zh/latest/plugins/prometheus.md:
##########
@@ -321,6 +321,8 @@ APISIX 在开始 LLM 上游尝试时递增该 gauge,并在请求的日志阶
### `apisix_llm_prompt_tokens` 的标签
+prompt token 包含从缓存读取和写入缓存的 token。对于 Anthropic Messages API,其值为 `input_tokens + cache_read_input_tokens + cache_creation_input_tokens`,与 OpenAI 的 `prompt_tokens` 含义一致。
Review Comment:
The Chinese docs line mixes singular/plural (“prompt token”) and English “token” wording in a way that’s inconsistent with surrounding terminology (“令牌” is used elsewhere in this doc). Consider revising to consistently use either “prompt tokens” or “提示令牌/提示 tokens”, and keep the cache read/write description consistent across zh docs.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@apisix.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] fix(ai-proxy): include cache tokens in Anthropic prompt usage and read them from message_delta [apisix]
Posted by "AlinsRan (via GitHub)" <gi...@apache.org>.
AlinsRan commented on code in PR #14028:
URL: https://github.com/apache/apisix/pull/14028#discussion_r4247003519
##########
apisix/plugins/ai-protocols/anthropic-messages.lua:
##########
@@ -29,10 +29,49 @@ local sse = require("apisix.plugins.ai-transport.sse")
local table = table
local type = type
local ipairs = ipairs
+local pairs = pairs
local _M = {}
+-- Anthropic reports cache tokens alongside input_tokens rather than inside it,
+-- so add them back to get a prompt total with the same meaning as OpenAI's
+-- prompt_tokens. Mirrors LiteLLM's AnthropicConfig.calculate_usage.
+local function to_usage(raw)
+ local cache_read = raw.cache_read_input_tokens or 0
+ local cache_creation = raw.cache_creation_input_tokens or 0
+ local prompt = (raw.input_tokens or 0) + cache_read + cache_creation
+ local completion = raw.output_tokens or 0
+ return {
+ prompt_tokens = prompt,
+ completion_tokens = completion,
+ total_tokens = prompt + completion,
+ cache_read_input_tokens = cache_read,
+ cache_creation_input_tokens = cache_creation,
+ reasoning_tokens = 0,
+ }
+end
+
+
+-- message_delta usage is cumulative but may omit fields reported at
+-- message_start (and some providers only report cache tokens there), so
+-- accumulate the raw fields across events before computing usage.
+local function accumulate_usage(state, raw)
+ if type(state) ~= "table" then
+ return raw
+ end
+ local acc = state.anthropic_usage
+ if not acc then
+ acc = {}
+ state.anthropic_usage = acc
+ end
+ for k, v in pairs(raw) do
+ acc[k] = v
+ end
+ return acc
+end
Review Comment:
Renamed it to `merge_usage_fields` in 9775c8415. The comment now says that later events overwrite fields instead of adding to them, because the values are cumulative.
##########
apisix/plugins/ai-protocols/converters/anthropic-messages-to-openai-chat.lua:
##########
@@ -102,6 +102,33 @@ end
-- SSE event helpers
+-- prompt_tokens_details keys that carry cache-write tokens, in LiteLLM's
+-- order, followed by the cache_creation_input_tokens shape some upstreams use.
+local CACHE_CREATION_DETAIL_KEYS = {
+ "cache_creation_tokens",
+ "cache_write_tokens",
+ "cache_creation_input_tokens",
+}
+
+
+local function cache_creation_tokens(usage)
+ local v = usage.cache_creation_input_tokens
+ if type(v) == "number" and v > 0 then
+ return v
+ end
+ local details = usage.prompt_tokens_details
+ if type(details) == "table" then
+ for _, key in ipairs(CACHE_CREATION_DETAIL_KEYS) do
+ v = details[key]
+ if type(v) == "number" and v > 0 then
+ return v
+ end
+ end
+ end
+ return 0
+end
Review Comment:
Added the guard in 9775c8415.
##########
docs/zh/latest/plugins/prometheus.md:
##########
@@ -321,6 +321,8 @@ APISIX 在开始 LLM 上游尝试时递增该 gauge,并在请求的日志阶
### `apisix_llm_prompt_tokens` 的标签
+prompt token 包含从缓存读取和写入缓存的 token。对于 Anthropic Messages API,其值为 `input_tokens + cache_read_input_tokens + cache_creation_input_tokens`,与 OpenAI 的 `prompt_tokens` 含义一致。
Review Comment:
Reworded it in 9775c8415. This page uses "prompt token" / "token" everywhere (for example the metric descriptions and the histogram buckets section), so I kept those terms here instead of switching to "令牌".
##########
apisix/plugins/ai-protocols/converters/anthropic-messages-to-openai-chat.lua:
##########
@@ -787,15 +814,18 @@ function _M.convert_response(res_body, ctx)
usage.output_tokens = completion_tokens
+ -- Anthropic input_tokens excludes both cache reads and cache writes,
+ -- while OpenAI prompt_tokens includes them (same as LiteLLM).
+ local creation = cache_creation_tokens(res_body.usage)
if type(details) == "table" then
local cached = details.cached_tokens or 0
- usage.input_tokens = math_max(0, prompt_tokens - cached)
+ usage.input_tokens = math_max(0, prompt_tokens - cached - creation)
Review Comment:
The suggested fix of preserving the upstream usage before conversion would break the moderation plugins (`ai-aws-content-moderation`, `ai-aliyun-content-moderation`, `ai-lakera-guard`). They pass `ctx.llm_raw_usage` to `build_deny_response` of the client protocol, so on this path it has to stay in Anthropic shape. That is also how it worked before this PR: the converted non-streaming path already stored the converted usage. I took the second option:
- The PR description now says that `ctx.llm_raw_usage` on the converted non-streaming path holds the converted Anthropic usage, and lists the change to `input_tokens` (20 to 15 for the fixture) under "Behavior change".
- `t/plugin/ai-rate-limiting-expression.t` TEST 29/30 cover the `expression` strategy on this path. `input_tokens + cache_read_input_tokens + cache_creation_input_tokens` evaluates to 30, which equals the upstream `prompt_tokens`. Before the converter fix it evaluated to 35, because cache writes were counted twice. Fixed in 9775c8415.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@apisix.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] fix(ai-proxy): include cache tokens in Anthropic prompt usage and read them from message_delta [apisix]
Posted by "membphis (via GitHub)" <gi...@apache.org>.
membphis commented on PR #14028:
URL: https://github.com/apache/apisix/pull/14028#issuecomment-6160285552
A non-blocking accounting observation for the author to decide whether to address in this PR or in a follow-up:
The converter now recognizes `usage.cache_creation_input_tokens`, `prompt_tokens_details.cache_creation_tokens`, and `prompt_tokens_details.cache_write_tokens`, but the converted streaming path still collects normalized usage through `openai-chat.parse_sse_event`, which only reads `prompt_tokens_details.cache_creation_input_tokens`.
For example, an Anthropic client with an OpenAI-compatible upstream can receive this final streaming usage:
```json
{
"prompt_tokens": 100,
"completion_tokens": 10,
"cache_creation_input_tokens": 30,
"prompt_tokens_details": { "cached_tokens": 20 }
}
```
A focused probe of the reviewed Lua modules shows that the converted client response reports `input_tokens=50`, `cache_read_input_tokens=20`, and `cache_creation_input_tokens=30`, while the streaming normalized usage reports `cache_creation_input_tokens=0`. That zero flows into `$llm_cache_creation_input_tokens`, the access log, and `llm_summary`. The non-streaming conversion reports 30 correctly. The same mismatch occurs with the other two newly supported cache-write field aliases. The corrected prompt and total token counts on this path remain correct.
Relevant code: [converter](https://github.com/apache/apisix/blob/9775c8415eeab2193128d633bc763310ddc3c4df/apisix/plugins/ai-protocols/converters/anthropic-messages-to-openai-chat.lua#L1042) and [streaming usage extraction](https://github.com/apache/apisix/blob/9775c8415eeab2193128d633bc763310ddc3c4df/apisix/plugins/ai-protocols/openai-chat.lua#L115).
A possible fix is to share the cache-write field extraction rules between conversion and usage normalization, preserving raw usage, and add streaming E2E assertions for both the response and access-log cache counts for all three field shapes.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@apisix.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org