-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
fix(server-utils): Read AI SDK cache token counts in Vercel AI channel subscriber #24350
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
sergical
wants to merge
4
commits into
develop
Choose a base branch
from
fix/vercel-ai-channel-cache-tokens
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+226
−1
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
076ca31
fix(server-utils): Read AI SDK cache token counts in Vercel AI channe…
sergical f427cbe
Keep aggregated cache counts on root operations
sergical 1bd0c23
simplify
sergical fa57569
Skip unreported cache counts instead of setting them to undefined
sergical File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
188 changes: 188 additions & 0 deletions
188
packages/server-utils/test/integrations/vercel-ai/cache-tokens.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,188 @@ | ||
| import { afterEach, beforeEach, describe, expect, it } from 'vitest'; | ||
| import { | ||
| GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS, | ||
| GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, | ||
| GEN_AI_USAGE_INPUT_TOKENS, | ||
| GEN_AI_USAGE_OUTPUT_TOKENS, | ||
| GEN_AI_USAGE_TOTAL_TOKENS, | ||
| } from '@sentry/conventions/attributes'; | ||
| import { getMainCarrier, setCurrentClient, spanToStaticSpanJSON } from '@sentry/core'; | ||
| import type { Span } from '@sentry/core'; | ||
| import { | ||
| createSpanFromMessage, | ||
| enrichSpanOnEnd, | ||
| streamedResultToChannelResult, | ||
| } from '../../../src/integrations/vercel-ai/vercel-ai-dc-subscriber'; | ||
| import { getDefaultTestClientOptions, TestClient } from '../../mocks/client'; | ||
|
|
||
| describe('Vercel AI SDK cache tokens', () => { | ||
| beforeEach(() => { | ||
| getMainCarrier().__SENTRY__ = undefined; | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| getMainCarrier().__SENTRY__ = undefined; | ||
| }); | ||
|
|
||
| function setupClient(): Span[] { | ||
| const client = new TestClient( | ||
| getDefaultTestClientOptions({ | ||
| dsn: 'https://public@dsn.ingest.sentry.io/1337', | ||
| tracesSampleRate: 1, | ||
| }), | ||
| ); | ||
| setCurrentClient(client); | ||
| client.init(); | ||
|
|
||
| const endedSpans: Span[] = []; | ||
| client.on('spanEnd', span => endedSpans.push(span)); | ||
| return endedSpans; | ||
| } | ||
|
|
||
| function runSpan( | ||
| type: string, | ||
| result: Record<string, unknown>, | ||
| existingAttributes: Record<string, number> = {}, | ||
| ): Record<string, unknown> { | ||
| const endedSpans = setupClient(); | ||
| const message = { type, event: {}, result } as Parameters<typeof createSpanFromMessage>[0]; | ||
| const span = createSpanFromMessage(message, {} as Parameters<typeof createSpanFromMessage>[1]); | ||
| span!.setAttributes(existingAttributes); | ||
| enrichSpanOnEnd(span!, message, {} as Parameters<typeof enrichSpanOnEnd>[2]); | ||
| span?.end(); | ||
| return spanToStaticSpanJSON(endedSpans[0]!).data ?? {}; | ||
| } | ||
|
|
||
| it('reads v5 `cachedInputTokens` when providerMetadata has no provider key', () => { | ||
| const data = runSpan('languageModelCall', { | ||
| usage: { | ||
| inputTokens: 120, | ||
| outputTokens: 10, | ||
| totalTokens: 130, | ||
| cachedInputTokens: 100, | ||
| }, | ||
| providerMetadata: { gateway: { routing: {} } }, | ||
| }); | ||
|
|
||
| expect(data[GEN_AI_USAGE_INPUT_TOKENS]).toBe(120); | ||
| expect(data[GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS]).toBe(100); | ||
| expect(data[GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS]).toBeUndefined(); | ||
| }); | ||
|
|
||
| it('reads v6 `inputTokenDetails` cache read and write counts', () => { | ||
| const data = runSpan('languageModelCall', { | ||
| usage: { | ||
| inputTokens: 120, | ||
| inputTokenDetails: { | ||
| noCacheTokens: 20, | ||
| cacheReadTokens: 80, | ||
| cacheWriteTokens: 20, | ||
| }, | ||
| outputTokens: 10, | ||
| totalTokens: 130, | ||
| }, | ||
| }); | ||
|
|
||
| expect(data[GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS]).toBe(80); | ||
| expect(data[GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS]).toBe(20); | ||
| }); | ||
|
|
||
| it('prefers `inputTokenDetails` over the deprecated `cachedInputTokens`', () => { | ||
| const data = runSpan('languageModelCall', { | ||
| usage: { | ||
| inputTokens: 120, | ||
| inputTokenDetails: { cacheReadTokens: 80 }, | ||
| cachedInputTokens: 5, | ||
| outputTokens: 10, | ||
| }, | ||
| }); | ||
|
|
||
| expect(data[GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS]).toBe(80); | ||
| }); | ||
|
|
||
| it('reads v7 `inputTokens` / `outputTokens` objects', () => { | ||
| const data = runSpan('languageModelCall', { | ||
| usage: { | ||
| inputTokens: { total: 120, noCache: 20, cacheRead: 80, cacheWrite: 20 }, | ||
| outputTokens: { total: 10, text: 10, reasoning: 0 }, | ||
| }, | ||
| }); | ||
|
|
||
| expect(data[GEN_AI_USAGE_INPUT_TOKENS]).toBe(120); | ||
| expect(data[GEN_AI_USAGE_OUTPUT_TOKENS]).toBe(10); | ||
| expect(data[GEN_AI_USAGE_TOTAL_TOKENS]).toBe(130); | ||
| expect(data[GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS]).toBe(80); | ||
| expect(data[GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS]).toBe(20); | ||
| }); | ||
|
|
||
| it('sets nothing when the usage object carries no cache counts', () => { | ||
| const data = runSpan('languageModelCall', { | ||
| usage: { inputTokens: 120, outputTokens: 10, totalTokens: 130 }, | ||
| }); | ||
|
|
||
| expect(data[GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS]).toBeUndefined(); | ||
| expect(data[GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS]).toBeUndefined(); | ||
| }); | ||
|
|
||
| it('leaves an existing count in place when the SDK usage does not report it', () => { | ||
| const data = runSpan( | ||
| 'languageModelCall', | ||
| { usage: { inputTokens: 120, cachedInputTokens: 80, outputTokens: 10 } }, | ||
| { [GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS]: 20 }, | ||
| ); | ||
|
|
||
| expect(data[GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS]).toBe(80); | ||
| expect(data[GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS]).toBe(20); | ||
| }); | ||
|
|
||
| it('keeps providerMetadata-derived counts over the SDK usage counts', () => { | ||
| const data = runSpan('languageModelCall', { | ||
| usage: { | ||
| inputTokens: 120, | ||
| inputTokenDetails: { cacheReadTokens: 80, cacheWriteTokens: 20 }, | ||
| cachedInputTokens: 80, | ||
| outputTokens: 10, | ||
| }, | ||
| providerMetadata: { | ||
| anthropic: { cacheReadInputTokens: 81, cacheCreationInputTokens: 21 }, | ||
| }, | ||
| }); | ||
|
|
||
| expect(data[GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS]).toBe(81); | ||
| expect(data[GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS]).toBe(21); | ||
| }); | ||
|
|
||
| it('keeps the aggregated SDK counts on a root operation over last-step providerMetadata', () => { | ||
| const data = runSpan('generateText', { | ||
| usage: { | ||
| inputTokens: 9500, | ||
| inputTokenDetails: { cacheReadTokens: 8000, cacheWriteTokens: 500 }, | ||
| outputTokens: 40, | ||
| }, | ||
| providerMetadata: { | ||
| anthropic: { cacheReadInputTokens: 3000, cacheCreationInputTokens: 0 }, | ||
| }, | ||
| }); | ||
|
|
||
| expect(data[GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS]).toBe(8000); | ||
| expect(data[GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS]).toBe(500); | ||
| }); | ||
|
|
||
| it('reads the counts from a streamed model call result', () => { | ||
| const data = runSpan( | ||
| 'languageModelCall', | ||
| streamedResultToChannelResult({ | ||
| text: 'hi', | ||
| toolCalls: [], | ||
| usage: { | ||
| inputTokens: { total: 120, cacheRead: 80, cacheWrite: 20 }, | ||
| outputTokens: { total: 10 }, | ||
| }, | ||
| }), | ||
| ); | ||
|
|
||
| expect(data[GEN_AI_USAGE_INPUT_TOKENS]).toBe(120); | ||
| expect(data[GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS]).toBe(80); | ||
| expect(data[GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS]).toBe(20); | ||
| }); | ||
| }); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Adding the two cache keys here drops them from
providerAttributeson every root operation, but I think v6/v7 have replacements for them so it's not an issue there.On v4/v5
cache_creationwould get dropped from the root span, is that desirable?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think so. On a root span the other last-step keys (
output_tokens,total_tokens) are already dropped for the same reason, and a last-step cache write count on a span whose input/read counts are aggregated across steps reads as the whole call's writes. On v4/v5 the SDK reports no cache writes at all, so the root span ends up with reads only, which matches what the SDK itself exposes. Model-call spans keep the providerMetadata value in every version.