Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 3 additions & 4 deletions packages/cli/src/ui/hooks/useAgentStreamingState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,14 +84,13 @@ export function useAgentStreamingState(

// Dedicated listener for usage metadata — updates React state directly
// so the token count is available immediately (even if no other event
// triggers a re-render). Prefers totalTokenCount (prompt + output)
// because output becomes history for the next round, matching
// geminiChat.ts.
// triggers a re-render). Context usage tracks prompt size; output
// isn't in history yet.
const usageHandler = (event: {
usage?: { totalTokenCount?: number; promptTokenCount?: number };
}) => {
const count =
event?.usage?.totalTokenCount ?? event?.usage?.promptTokenCount;
event?.usage?.promptTokenCount ?? event?.usage?.totalTokenCount;
if (typeof count === 'number' && count > 0) {
setLastPromptTokenCount(count);
}
Expand Down
1 change: 0 additions & 1 deletion packages/cli/src/ui/hooks/useSessionPicker.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -275,5 +275,4 @@ describe('useSessionPicker multi-select state', () => {
expect(onConfirmMulti).toHaveBeenCalledWith(['s2']);
expect(onSelect).not.toHaveBeenCalled();
});

});
8 changes: 3 additions & 5 deletions packages/core/src/agents/runtime/agent-core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1637,11 +1637,9 @@ Important Rules:
const thoughtTok = Number(usage.thoughtsTokenCount || 0);
const cachedTok = Number(usage.cachedContentTokenCount || 0);
const totalTok = Number(usage.totalTokenCount || 0);
// Prefer totalTokenCount (prompt + output) for context usage — the
// output from this round becomes history for the next, matching
// the approach in geminiChat.ts.
const contextTok = isFinite(totalTok) && totalTok > 0 ? totalTok : inTok;
if (isFinite(contextTok) && contextTok > 0) {
// Context usage tracks prompt size; output isn't in history yet.
const contextTok = inTok || totalTok;
Comment thread
tanzhenxin marked this conversation as resolved.
Resolved
if (contextTok) {
this.lastPromptTokenCount = contextTok;
}
if (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2269,8 +2269,8 @@ describe('AnthropicContentGenerator', () => {
delta: { stop_reason: 'end_turn' },
usage: {
output_tokens: 5,
input_tokens: 7,
cache_read_input_tokens: 2,
input_tokens: 2,
cache_read_input_tokens: 7,
},
};
yield { type: 'message_stop' };
Expand Down Expand Up @@ -2331,8 +2331,8 @@ describe('AnthropicContentGenerator', () => {
const last = chunks[chunks.length - 1]!;
expect(last.candidates?.[0]?.finishReason).toBe(FinishReason.STOP);
expect(last.usageMetadata).toEqual({
cachedContentTokenCount: 2,
promptTokenCount: 9, // cached(2) + input(7)
cachedContentTokenCount: 7,
promptTokenCount: 9, // input(2) + cached(7) — Anthropic-true (input < cache_read)
candidatesTokenCount: 5,
totalTokenCount: 14,
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ type RawMessageStreamEvent = Anthropic.RawMessageStreamEvent;
import { RequestTokenEstimator } from '../../utils/request-tokenizer/index.js';
import { safeJsonParse } from '../../utils/safeJsonParse.js';
import { AnthropicContentConverter } from './converter.js';
import { buildAnthropicUsageMetadata } from './usage.js';
import {
buildRuntimeFetchOptions,
redactProxyError,
Expand Down Expand Up @@ -770,6 +771,7 @@ export class AnthropicContentGenerator implements ContentGenerator {
let messageId: string | undefined;
let model = this.contentGeneratorConfig.model;
let cachedTokens = 0;
let cacheCreationTokens = 0;
let promptTokens = 0;
let completionTokens = 0;
let finishReason: string | undefined;
Expand All @@ -784,6 +786,9 @@ export class AnthropicContentGenerator implements ContentGenerator {
model = event.message.model ?? model;
cachedTokens =
event.message.usage?.cache_read_input_tokens ?? cachedTokens;
cacheCreationTokens =
event.message.usage?.cache_creation_input_tokens ??
cacheCreationTokens;
promptTokens = event.message.usage?.input_tokens ?? promptTokens;
break;
}
Expand Down Expand Up @@ -910,19 +915,25 @@ export class AnthropicContentGenerator implements ContentGenerator {
cachedTokens = cacheRead;
}
}
if (usageRecord?.['cache_creation_input_tokens'] !== undefined) {
const cacheCreate = usageRecord['cache_creation_input_tokens'];
if (typeof cacheCreate === 'number') {
cacheCreationTokens = cacheCreate;
}
}

if (finishReason || event.usage) {
const chunk = this.buildGeminiChunk(
undefined,
messageId,
model,
finishReason,
{
cachedContentTokenCount: cachedTokens,
promptTokenCount: cachedTokens + promptTokens,
candidatesTokenCount: completionTokens,
totalTokenCount: cachedTokens + promptTokens + completionTokens,
},
buildAnthropicUsageMetadata({
inputTokens: promptTokens,
cacheReadTokens: cachedTokens,
cacheCreationTokens,
outputTokens: completionTokens,
}),
);
collectedResponses.push(chunk);
yield chunk;
Expand All @@ -936,12 +947,12 @@ export class AnthropicContentGenerator implements ContentGenerator {
messageId,
model,
finishReason,
{
cachedContentTokenCount: cachedTokens,
promptTokenCount: cachedTokens + promptTokens,
candidatesTokenCount: completionTokens,
totalTokenCount: cachedTokens + promptTokens + completionTokens,
},
buildAnthropicUsageMetadata({
inputTokens: promptTokens,
cacheReadTokens: cachedTokens,
cacheCreationTokens,
outputTokens: completionTokens,
}),
);
collectedResponses.push(chunk);
yield chunk;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1306,6 +1306,7 @@ describe('AnthropicContentConverter', () => {
promptTokenCount: 3,
candidatesTokenCount: 5,
totalTokenCount: 8,
cachedContentTokenCount: 0,
});

const parts = response.candidates?.[0]?.content?.parts || [];
Expand Down
14 changes: 7 additions & 7 deletions packages/core/src/core/anthropicContentGenerator/converter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import type {
ToolListUnion,
} from '@google/genai';
import { FinishReason, GenerateContentResponse } from '@google/genai';
import { buildAnthropicUsageMetadata } from './usage.js';
import type Anthropic from '@anthropic-ai/sdk';
import { safeJsonParse } from '../../utils/safeJsonParse.js';
import {
Expand Down Expand Up @@ -325,13 +326,12 @@ export class AnthropicContentConverter {
geminiResponse.promptFeedback = { safetyRatings: [] };

if (response.usage) {
const promptTokens = response.usage.input_tokens || 0;
const completionTokens = response.usage.output_tokens || 0;
geminiResponse.usageMetadata = {
promptTokenCount: promptTokens,
candidatesTokenCount: completionTokens,
totalTokenCount: promptTokens + completionTokens,
};
geminiResponse.usageMetadata = buildAnthropicUsageMetadata({
inputTokens: response.usage.input_tokens || 0,
cacheReadTokens: response.usage.cache_read_input_tokens || 0,
cacheCreationTokens: response.usage.cache_creation_input_tokens || 0,
outputTokens: response.usage.output_tokens || 0,
});
}

return geminiResponse;
Expand Down
109 changes: 109 additions & 0 deletions packages/core/src/core/anthropicContentGenerator/usage.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
/**
* @license
* Copyright 2025 Qwen
* SPDX-License-Identifier: Apache-2.0
*/

import { describe, expect, it } from 'vitest';
import { buildAnthropicUsageMetadata } from './usage.js';

describe('buildAnthropicUsageMetadata', () => {
it('sums all three prompt fields under standard Anthropic semantics', () => {
expect(
buildAnthropicUsageMetadata({
inputTokens: 5_000,
cacheReadTokens: 25_000,
cacheCreationTokens: 0,
outputTokens: 1_000,
}),
).toEqual({
promptTokenCount: 30_000,
candidatesTokenCount: 1_000,
totalTokenCount: 31_000,
cachedContentTokenCount: 25_000,
});
});

it('sums when only cache_creation is set (first cache write)', () => {
expect(
buildAnthropicUsageMetadata({
inputTokens: 10_000,
cacheReadTokens: 0,
cacheCreationTokens: 20_000,
outputTokens: 500,
}),
).toEqual({
promptTokenCount: 30_000,
candidatesTokenCount: 500,
totalTokenCount: 30_500,
cachedContentTokenCount: 0,
});
});

it('uses inputTokens alone when it already covers cache fields (OpenAI semantics on Anthropic protocol)', () => {
expect(
buildAnthropicUsageMetadata({
inputTokens: 30_000,
cacheReadTokens: 25_000,
cacheCreationTokens: 0,
outputTokens: 800,
}),
).toEqual({
promptTokenCount: 30_000,
candidatesTokenCount: 800,
totalTokenCount: 30_800,
cachedContentTokenCount: 25_000,
});
});

it('reports inputTokens directly when no cache fields are present', () => {
expect(
buildAnthropicUsageMetadata({
inputTokens: 12_345,
cacheReadTokens: 0,
cacheCreationTokens: 0,
outputTokens: 678,
}),
).toEqual({
promptTokenCount: 12_345,
candidatesTokenCount: 678,
totalTokenCount: 13_023,
cachedContentTokenCount: 0,
});
});

it('keeps summing when inputTokens grows past cache_creation in a long Anthropic conversation', () => {
// Regression: an earlier guard mis-classified this as OpenAI-style
// (because input >= cache_creation) and dropped the cache_creation
// portion, producing a one-shot Footer "drop" at the crossover point.
expect(
buildAnthropicUsageMetadata({
inputTokens: 50_000,
cacheReadTokens: 0,
cacheCreationTokens: 32_088,
outputTokens: 200,
}),
).toEqual({
promptTokenCount: 82_088,
candidatesTokenCount: 200,
totalTokenCount: 82_288,
cachedContentTokenCount: 0,
});
});

it('handles all-zero usage cleanly', () => {
expect(
buildAnthropicUsageMetadata({
inputTokens: 0,
cacheReadTokens: 0,
cacheCreationTokens: 0,
outputTokens: 0,
}),
).toEqual({
promptTokenCount: 0,
candidatesTokenCount: 0,
totalTokenCount: 0,
cachedContentTokenCount: 0,
});
});
});
59 changes: 59 additions & 0 deletions packages/core/src/core/anthropicContentGenerator/usage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/**
* @license
* Copyright 2025 Qwen
* SPDX-License-Identifier: Apache-2.0
*/

import type { GenerateContentResponseUsageMetadata } from '@google/genai';

export interface AnthropicTokenParts {
inputTokens: number;
cacheReadTokens: number;
cacheCreationTokens: number;
outputTokens: number;
}

/**
* Normalize Anthropic-side token counts into Gemini's `usageMetadata` shape.
*
* Anthropic reports the prompt across three mutually-exclusive fields:
* `input_tokens`, `cache_read_input_tokens`, `cache_creation_input_tokens`.
* The full prompt is the sum.
*
* `cache_creation_input_tokens` is unique to Anthropic's protocol — OpenAI
* has no equivalent — so its presence is a strong signal the response
* follows real Anthropic semantics. Use that as the primary discriminator:
*
* - cache_creation > 0 → Anthropic semantics, sum all three
* - else if cache_read > 0 and input ≥ cache_read → OpenAI-style on the
* Anthropic protocol (input already covers the cached portion), trust
* input alone
* - else → sum (when no cache activity, sum equals input)
*
* An earlier version of this guard compared `inputTokens` to *both* cache
* fields and fell back to "input alone" whenever input was the larger
* value. That mis-fired on long real Anthropic conversations: once enough
* history accumulates, `inputTokens` naturally grows past
* `cache_creation_input_tokens`, which would silently drop the cache
* portion from the displayed prompt size and produce a one-shot Footer
* "drop" at the crossover point.
*/
export function buildAnthropicUsageMetadata(
parts: AnthropicTokenParts,
): GenerateContentResponseUsageMetadata {
const { inputTokens, cacheReadTokens, cacheCreationTokens, outputTokens } =
parts;
const looksLikeOpenAi =
Comment thread
tanzhenxin marked this conversation as resolved.
Resolved
cacheCreationTokens === 0 &&
cacheReadTokens > 0 &&
inputTokens >= cacheReadTokens;
const promptTotal = looksLikeOpenAi
? inputTokens
: inputTokens + cacheReadTokens + cacheCreationTokens;
return {
promptTokenCount: promptTotal,
candidatesTokenCount: outputTokens,
totalTokenCount: promptTotal + outputTokens,
cachedContentTokenCount: cacheReadTokens,
};
}
7 changes: 5 additions & 2 deletions packages/core/src/core/geminiChat.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -944,9 +944,12 @@ describe('GeminiChat', async () => {
'prompt-id-1',
);

// Verify that token counting is called when usageMetadata is present
// Verify that token counting is called when usageMetadata is present.
// The Footer-driving counter must reflect *prompt* size only — output
// tokens for the in-flight round are not yet in history. The mock
// returns promptTokenCount=42, so that's what should be reported.
expect(uiTelemetryService.setLastPromptTokenCount).toHaveBeenCalledWith(
57,
42,
);
expect(uiTelemetryService.setLastPromptTokenCount).toHaveBeenCalledTimes(
1,
Expand Down
5 changes: 2 additions & 3 deletions packages/core/src/core/geminiChat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1217,10 +1217,9 @@ export class GeminiChat {
// Collect token usage for consolidated recording
if (chunk.usageMetadata) {
usageMetadata = chunk.usageMetadata;
// Use || instead of ?? so that totalTokenCount=0 falls back to promptTokenCount.
// Some providers omit total_tokens or return 0 in streaming usage chunks.
// Context usage tracks prompt size; output isn't in history yet.
const lastPromptTokenCount =
usageMetadata.totalTokenCount || usageMetadata.promptTokenCount;
usageMetadata.promptTokenCount || usageMetadata.totalTokenCount;
if (lastPromptTokenCount) {
// Always update the per-chat counter so this chat (including
// subagents) can make its own compaction decisions.
Expand Down
15 changes: 15 additions & 0 deletions packages/core/src/services/sessionService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -895,6 +895,21 @@ describe('SessionService', () => {
).toBe(450);
});

it('should prefer promptTokenCount over totalTokenCount when both are present', () => {
const assistant: ChatRecord = {
...baseRecord,
uuid: 'a1',
parentUuid: 'comp',
type: 'assistant',
usageMetadata: { promptTokenCount: 200, totalTokenCount: 450 },
};
expect(
getResumePromptTokenCount(
makeConversation([compressionRecord, assistant]),
),
).toBe(200);
});

it('should fall back to compression when latest assistant has zero usage', () => {
const assistant: ChatRecord = {
...baseRecord,
Expand Down
Loading
Loading