gateway: a Claude reply's thinking tokens are counted as its reasoning, and told to Claude Code when another protocol's model reasoned (#3430)

A Messages API reply can say in its message_delta how many of its output
tokens were thinking (usage.output_tokens_details.thinking_tokens), as
Copilot's Claude replies do. aUsage had no field for it, so every such
reply, relayed or translated, was recorded with reasoning 0 (#3430: all
277 claude-desktop rows through Copilot on 2026-10-23). The Claude
subscription's cliUsage already read the field
(claude_subscription.go:4272), and the Chat, Responses and Gemini usages
read their own counts.

aUsage now reads output_tokens_details into Usage.Reasoning, and
Usage.anthropic() writes it when there is some, so a Claude Code client
of a Chat or Responses model that reasoned is told its thinking tokens in
message_delta, as Usage.chat() and the Responses encoder tell theirs. A
usage without reasoning is written as before. Reasoning is a part of
Output and is priced nowhere on its own (usage, request_page), so no cost
changes. The change is mdwsk88's patch (6bdf0fe53) as written; reviewed
line by line, nothing taken out.

Run on mote (macOS 27, go1.26.8) at dc49feca9 plus this change:
- go test -count=1 -run 'Thinking|Reasoning|Anthropic.*Usage|Usage'
  ./internal/gateway/: ok (75s), the two new tests among them:
  TestAnthropicThinkingTokensCounted (Copilot's own reply bytes, through
  /v1/messages, /v1/chat/completions and /v1/responses) and
  TestTranslatedReasoningToldAsThinkingTokens.
- Broken by hand: anthropic.go put back at dc49feca9, the tests kept:
  both fail, "thinking tokens not counted: 200 output 1277 reasoning 0"
  on each of the three paths and "message_delta doesn't tell the
  thinking tokens".
- gofmt -l on the two files: nothing.
Not tried: a live Copilot Claude request through a built magpie (the
fixture is the reporter's real Copilot reply); whether Anthropic's own
API sends the field.

Reported-by: mdwsk88 (dawei on Discord)
Co-authored-by: mdwsk88 <11055210+mdwsk88@users.noreply.github.com>
This commit is contained in:
yetone
2026-11-07 04:03:01 +08:00
co-authored by mdwsk88
parent 4e0e8e7933
commit fc7fde82c5
2 changed files with 114 additions and 1 deletions
+20 -1
View File
@@ -1406,6 +1406,13 @@ type aUsage struct {
// Kiro caches but tells only credits, never tokens (zeewell on X).
// It is read, never told: anthropic() leaves it false.
CacheUnknown bool `json:"magpie_cache_unknown,omitempty"`
// OutputTokensDetails says how many of the output tokens were
// thinking, as Copilot counts them on a message_delta: the reasoning
// count the other protocols' usage carries (completion_tokens_details,
// Gemini's thoughtsTokenCount) and the Claude subscription's cliUsage
// reads from Claude Code. A vendor that leaves it out is told by its
// stream (hidesReasoning, #4545)
OutputTokensDetails *aOutputDetails `json:"output_tokens_details,omitempty"`
}
type aCacheCreation struct {
@@ -1413,6 +1420,10 @@ type aCacheCreation struct {
Ephemeral1h int `json:"ephemeral_1h_input_tokens"`
}
type aOutputDetails struct {
ThinkingTokens int `json:"thinking_tokens"`
}
func (u aUsage) usage() Usage {
out := Usage{Input: u.InputTokens, Output: u.OutputTokens, CacheRead: u.CacheReadInputTokens, CacheWrite: u.CacheCreationInputTokens, cacheUnknown: u.CacheUnknown}
if c := u.CacheCreation; c != nil {
@@ -1421,16 +1432,24 @@ func (u aUsage) usage() Usage {
out.CacheWrite = max(out.CacheWrite, c.Ephemeral5m+c.Ephemeral1h)
out.CacheWrite1h = c.Ephemeral1h
}
if d := u.OutputTokensDetails; d != nil {
out.Reasoning = d.ThinkingTokens
}
return out
}
// anthropic is the usage as Anthropic says it, the cache writes split by
// how long they are kept when upstream reported TTLs or some were for an hour.
// how long they are kept when upstream reported TTLs or some were for an
// hour, and the thinking among the output tokens when the upstream counted
// its reasoning.
func (u Usage) anthropic() aUsage {
out := aUsage{InputTokens: u.Input, OutputTokens: u.Output, CacheReadInputTokens: u.CacheRead, CacheCreationInputTokens: u.CacheWrite}
if h := min(u.CacheWrite1h, u.CacheWrite); u.cacheCreationReported || h > 0 {
out.CacheCreation = &aCacheCreation{Ephemeral5m: u.CacheWrite - h, Ephemeral1h: h}
}
if u.Reasoning > 0 {
out.OutputTokensDetails = &aOutputDetails{ThinkingTokens: u.Reasoning}
}
return out
}
@@ -0,0 +1,94 @@
package gateway
import (
"net/http/httptest"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// copilotThinkingReply is Claude's reply as Copilot's /v1/messages streamed
// it (claude-opus-5.5 at effort high, 2026-10-24), the signature cut short:
// its message_delta counts 710 of the 1277 output tokens as thinking, in
// output_tokens_details.
var copilotThinkingReply = []string{
`data: {"message":{"container":null,"content":[],"context_management":null,"diagnostics":null,"id":"msg_011CgKVXZcKWy1fj39CoDg5H","model":"claude-opus-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":3858},"cache_creation_input_tokens":3858,"cache_read_input_tokens":12030,"inference_geo":"global","input_tokens":2,"output_tokens":4,"speed":"standard"}},"type":"message_start"}`,
`data: {"content_block":{"signature":"","thinking":"","type":"thinking"},"index":0,"type":"content_block_start"}`,
`data: {"delta":{"thinking":"","type":"thinking_delta"},"index":0,"type":"content_block_delta"}`,
`data: {"delta":{"signature":"CAQSpQ8KEAgTGAI4AUIIdGhp","type":"signature_delta"},"index":0,"type":"content_block_delta"}`,
`data: {"index":0,"type":"content_block_stop"}`,
`data: {"content_block":{"text":"","type":"text"},"index":1,"type":"content_block_start"}`,
`data: {"delta":{"text":"ANSWER: 1245","type":"text_delta"},"index":1,"type":"content_block_delta"}`,
`data: {"index":1,"type":"content_block_stop"}`,
`data: {"context_management":{"applied_edits":[]},"copilot_usage":{"token_details":[{"batch_size":1000000,"cost_per_batch":400000000000,"model":"claude-opus-5.5","token_count":2,"token_type":"input"},{"batch_size":1000000,"cost_per_batch":20000000000,"model":"claude-opus-5.5","token_count":12030,"token_type":"cache_read"},{"batch_size":1000000,"cost_per_batch":500000000000,"model":"claude-opus-5.5","token_count":3858,"token_type":"cache_write"},{"batch_size":1000000,"cost_per_batch":2000000000000,"model":"claude-opus-5.5","token_count":1277,"token_type":"output"}],"total_nano_aiu":4724400000},"delta":{"container":null,"stop_details":null,"stop_reason":"end_turn","stop_sequence":null},"type":"message_delta","usage":{"cache_creation_input_tokens":3858,"cache_read_input_tokens":12030,"input_tokens":2,"iterations":[{"cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":3858},"cache_creation_input_tokens":3858,"cache_read_input_tokens":12030,"input_tokens":2,"output_tokens":1277,"type":"message"}],"output_tokens":1277,"output_tokens_details":{"thinking_tokens":710}}}`,
`data: {"type":"message_stop"}`,
}
// Claude's thinking is counted from what its usage says, as every other
// protocol's reasoning is: a reply relayed as it came and one translated
// for a Chat or Responses client both record its 710 thinking tokens, and
// the translated reply tells the client so. Before, an Anthropic reply's
// usage row had no reasoning at all.
func TestAnthropicThinkingTokensCounted(t *testing.T) {
for _, tc := range []struct{ path, told string }{
{"/v1/messages", `"thinking_tokens":710`},
{"/v1/chat/completions", `"reasoning_tokens":710`},
{"/v1/responses", `"reasoning_tokens":710`},
} {
t.Run(tc.path, func(t *testing.T) {
fresh(t)
up := httptest.NewServer(&paced{events: copilotThinkingReply})
t.Cleanup(up.Close)
if err := provider.Save(provider.Provider{ID: "fake", Name: "Fake", Anthropic: up.URL, Key: "k", Models: []string{"m1"}}); err != nil {
t.Fatal(err)
}
body := `{"model":"fake/m1","stream":true,"messages":[{"role":"user","content":"hi"}],"max_tokens":300}`
if tc.path == "/v1/responses" {
body = `{"model":"fake/m1","stream":true,"input":"hi"}`
}
rec := httptest.NewRecorder()
New().Handler().ServeHTTP(rec, httptest.NewRequest("POST", tc.path, strings.NewReader(body)))
u := lastUsage(t)
if rec.Code != 200 || u.Output != 1277 || u.Reasoning != 710 {
t.Fatalf("thinking tokens not counted: %d output %d reasoning %d\n%s", rec.Code, u.Output, u.Reasoning, rec.Body)
}
// counted, its reasoning isn't marked hidden, as one a stream shows
// and its usage doesn't count is (#4545), but for a Responses
// client's, which is marked hidden however it went
if u.ReasoningHidden && tc.path != "/v1/responses" {
t.Fatalf("710 thinking tokens counted, and the reasoning still marked hidden")
}
if !strings.Contains(rec.Body.String(), tc.told) {
t.Fatalf("the client isn't told the thinking tokens (%s):\n%s", tc.told, rec.Body)
}
})
}
}
// A Claude Code client served by a Chat model that reasoned is told how
// many of the output tokens were thinking, in output_tokens_details as
// Copilot tells it, as a Chat or Responses client is told in its own
// usage.
func TestTranslatedReasoningToldAsThinkingTokens(t *testing.T) {
fresh(t)
up := httptest.NewServer(&paced{events: []string{
`data: {"choices":[{"delta":{"reasoning_content":"a thought"}}]}`,
`data: {"choices":[{"delta":{"content":"hello"}}]}`,
`data: {"choices":[{"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":5,"completion_tokens":120,"completion_tokens_details":{"reasoning_tokens":100}}}`,
`data: [DONE]`,
}})
t.Cleanup(up.Close)
if err := provider.Save(provider.Provider{ID: "fake", Name: "Fake", Chat: up.URL + "/v1", Key: "k", Models: []string{"m1"}}); err != nil {
t.Fatal(err)
}
rec := httptest.NewRecorder()
New().Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/messages", strings.NewReader(
`{"model":"fake/m1","stream":true,"messages":[{"role":"user","content":"hi"}],"max_tokens":300}`)))
if u := lastUsage(t); rec.Code != 200 || u.Reasoning != 100 {
t.Fatalf("%d %+v\n%s", rec.Code, u, rec.Body)
}
if !strings.Contains(rec.Body.String(), `"output_tokens_details":{"thinking_tokens":100}`) {
t.Fatalf("message_delta doesn't tell the thinking tokens:\n%s", rec.Body)
}
}