eca icon indicating copy to clipboard operation
eca copied to clipboard

Context counter shows output-only tokens on Z.AI anthropic endpoint (usage reported in message_delta is discarded)

Open qwota opened this issue 2 months ago • 2 comments

Describe the bug

session-tokens (context bar, /context) collapses to the output tokens of the last turn only when the provider reports usage in message_delta instead of message_start — which is what the Z.AI anthropic-compatible endpoint (https://api.z.ai/api/anthropic) does in streaming mode (and ECA always streams).

Root cause in src/eca/llm_providers/anthropic.clj (0.159.0):

  • message_start handler stores ctx with nil→0 normalization: {:input-tokens (or (:input_tokens usage) 0), ...}
  • message_delta handler prefers ctx: {:input-tokens (or (:input-tokens ctx) (:input_tokens usage)), ...}

Since ctx values are always numbers and 0 is truthy in Clojure, the message_delta fallback is dead code: real input/cache numbers from message_delta are overwritten by zeros from message_start.

Side effect: auto-compact compares this counter against the context limit, so on such providers it never fires from the counter (only via the context-overflow recovery heuristic).

To Reproduce

  1. Configure a provider:
    {
      "api": "anthropic",
      "url": "https://api.z.ai/api/anthropic",
      "models": { "glm-5.3-flash": { "limit": { "context": 1000000, "output": 131072 } } }
    }
    
  2. Chat a few turns (context grows to tens of thousands of tokens).
  3. Watch the context bar / /context: it shows only the last turn's output tokens (a tiny number), never the real context size.

Raw SSE from Z.AI (live probe, 2026-09-14, identical request twice, ~820-token prompt, warm cache):

event: message_start
data: {"type": "message_start", "message": {..., "usage": {"input_tokens": 0, "output_tokens": 0}}}

event: message_delta
data: {"type": "message_delta", "delta": {"stop_reason": "end_turn", "stop_sequence": null},
       "usage": {"input_tokens": 52, "output_tokens": 40, "cache_read_input_tokens": 768, ...}}

Non-streaming responses from the same endpoint report the full usage object in the body (input_tokens = non-cached tail, cache_read_input_tokens separately; 52 + 768 = 820), so the bug is specific to the streaming path.

Expected behavior

Per the Anthropic streaming contract (docs.claude.com), message_start carries the input usage (real Anthropic: {"input_tokens": 472, ...}), and message_delta carries cumulative output_tokens only. Z.AI swaps these roles: zeros in message_start, full usage in message_delta.

The official anthropic-sdk-typescript accumulator (src/lib/MessageStream.ts → #accumulateMessage) resolves this with a per-field merge — delta-over-start with != null checks:

// Update other usage fields if they exist in the event
if (event.usage.input_tokens != null) {
  snapshot.usage.input_tokens = event.usage.input_tokens;
}
if (event.usage.cache_read_input_tokens != null) { ... }

ECA's message_delta handler should do the same (delta-first). This is a no-op for real Anthropic (no input fields in its message_delta) and fixes any provider that reports final usage there:

(on-usage-updated {:input-tokens (or (:input_tokens usage) (:input-tokens ctx))
                   :input-cache-creation-tokens (or (:cache_creation_input_tokens usage) (:cache-creation-input-tokens ctx))
                   :input-cache-read-tokens (or (:cache_read_input_tokens usage) (:cache-read-input-tokens ctx))
                   :output-tokens (:output_tokens usage)})

Doctor

eca-emacs: 4d38c35 (2026-09-01) | server: eca 0.159.0 | emacs: GNU Emacs 31.1 (build 2, x86_64-w64-mingw32)

Additional context

  • Related provider-specific usage fixes: #414 (gemini), #567 (ollama) — same class, different adapters; #471 already covers Z.AI's max_tokens-as-overflow quirk (the max-tokens-input-overflow? heuristic in this same file); open PR #602 is fixing usage semantics for OpenAI-compatible providers.
  • The provider side is already tracked upstream: zai-org/GLM-5#139 (message_start reports zero usage.input_tokens on the Z.AI anthropic-compatible endpoint). This report is not about fixing Z.AI, though: per-field delta-over-start merging is what the official Anthropic SDK does, so usage arriving in message_delta is a supported shape — ECA's adapter should tolerate it regardless of what any single provider does.
  • The (or ctx delta) fallback in the current code suggests handling delta-reported usage was already intended; it just can't trigger because of the nil→0 normalization in the message_start handler.

qwota avatar Sep 14 '26 05:09 qwota

thank you! I fixed with a more safe way that should work for z.ai and anthropic

ericdallo avatar Sep 14 '26 15:09 ericdallo

Checked it → it works! Thanks!

qwota avatar Sep 15 '26 07:09 qwota