Open History to see the last commit
1import { buildBaseUsage } from '@tanstack/ai'
2import type { TokenUsage } from '@tanstack/ai'
3import type Anthropic_SDK from '@anthropic-ai/sdk'
4
5/**
6 * Anthropic-specific provider usage details.
7 * These fields are unique to Anthropic and placed in providerUsageDetails.
8 */
9export type AnthropicProviderUsageDetails = {
10 /**
11 * Server-side tool usage metrics.
12 * Available when using Anthropic's built-in tools like web search.
13 */
14 serverToolUse?: {
15 /** Number of web search requests made during the response */
16 webSearchRequests?: number
17 /** Number of web fetch requests made during the response */
18 webFetchRequests?: number
19 }
20}
21
22/**
23 * Build normalized TokenUsage from Anthropic's usage object.
24 *
25 * `promptTokens` is the total input: uncached + cache read + cache write.
26 * Anthropic's `input_tokens` counts only the uncached part, so this function
27 * adds the cache parts. The cache parts are also in `promptTokensDetails`:
28 * `cachedTokens` (read), `cacheWriteTokens` (write), and `cacheWrite1hTokens`
29 * (the 1-hour part of the write). `totalTokens` is
30 * `promptTokens + completionTokens`.
31 *
32 * Also handles server tool use metrics. Returns `undefined` when the provider
33 * reported no usage object, so callers omit the field rather than fabricating
34 * zeroed totals.
35 */
36export function buildAnthropicUsage(
37 usage:
38 | Anthropic_SDK.Beta.BetaUsage
39 | Anthropic_SDK.Beta.BetaMessageDeltaUsage
40 | undefined
41 | null,
42 start?: Anthropic_SDK.Beta.BetaUsage,
43): TokenUsage<AnthropicProviderUsageDetails> | undefined {
44 if (!usage) return undefined
45
46 const inputTokens = usage.input_tokens ?? start?.input_tokens ?? 0
47 // `|| 0` (rather than `?? 0`) matches the sibling builders and stays defensive
48 // against a runtime-absent count without tripping no-unnecessary-condition
49 // (the SDK types output_tokens as a required number).
50 const outputTokens = usage.output_tokens || 0
51 const cacheCreation =
52 usage.cache_creation_input_tokens ?? start?.cache_creation_input_tokens
53 const cacheRead =
54 usage.cache_read_input_tokens ?? start?.cache_read_input_tokens
55 // The 1-hour part of the cache write. A closing message_delta has no
56 // `cache_creation`, so a stream takes message_start's.
57 const cacheWrite1h = (
58 ('cache_creation' in usage ? usage.cache_creation : null) ??
59 start?.cache_creation
60 )?.ephemeral_1h_input_tokens
61 // `input_tokens` is only the uncached part. Add the cache parts so
62 // promptTokens is the total input, the same as the other adapters.
63 const promptTokens = inputTokens + (cacheRead ?? 0) + (cacheCreation ?? 0)
64
65 const result = buildBaseUsage<AnthropicProviderUsageDetails>({
66 promptTokens,
67 completionTokens: outputTokens,
68 totalTokens: promptTokens + outputTokens,
69 })
70
71 // Add prompt token details for cache tokens. Only attach the details object
72 // when at least one field is present so we don't emit an empty `{}` (every
73 // other adapter guards with the same Object.keys check).
74 const promptTokensDetails = {
75 ...(cacheCreation ? { cacheWriteTokens: cacheCreation } : {}),
76 ...(cacheWrite1h ? { cacheWrite1hTokens: cacheWrite1h } : {}),
77 ...(cacheRead ? { cachedTokens: cacheRead } : {}),
78 }
79 if (Object.keys(promptTokensDetails).length > 0) {
80 result.promptTokensDetails = promptTokensDetails
81 }
82
83 // Add provider-specific usage details for server tool use, again only when
84 // the provider actually reported any server tool requests.
85 const serverToolUse = usage.server_tool_use ?? start?.server_tool_use
86 const serverToolUseDetails = {
87 ...(serverToolUse?.web_search_requests
88 ? { webSearchRequests: serverToolUse.web_search_requests }
89 : {}),
90 ...(serverToolUse?.web_fetch_requests
91 ? { webFetchRequests: serverToolUse.web_fetch_requests }
92 : {}),
93 }
94 if (Object.keys(serverToolUseDetails).length > 0) {
95 result.providerUsageDetails = {
96 serverToolUse: serverToolUseDetails,
97 } satisfies AnthropicProviderUsageDetails
98 }
99
100 return result
101}