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) and `cacheWriteTokens` (write). `totalTokens` is
29 * `promptTokens + completionTokens`.
30 *
31 * Also handles server tool use metrics. Returns `undefined` when the provider
32 * reported no usage object, so callers omit the field rather than fabricating
33 * zeroed totals.
34 */
35export function buildAnthropicUsage(
36 usage:
37 | Anthropic_SDK.Beta.BetaUsage
38 | Anthropic_SDK.Beta.BetaMessageDeltaUsage
39 | undefined
40 | null,
41 start?: Anthropic_SDK.Beta.BetaUsage,
42): TokenUsage<AnthropicProviderUsageDetails> | undefined {
43 if (!usage) return undefined
44
45 const inputTokens = usage.input_tokens ?? start?.input_tokens ?? 0
46 // `|| 0` (rather than `?? 0`) matches the sibling builders and stays defensive
47 // against a runtime-absent count without tripping no-unnecessary-condition
48 // (the SDK types output_tokens as a required number).
49 const outputTokens = usage.output_tokens || 0
50 const cacheCreation =
51 usage.cache_creation_input_tokens ?? start?.cache_creation_input_tokens
52 const cacheRead =
53 usage.cache_read_input_tokens ?? start?.cache_read_input_tokens
54 // `input_tokens` is only the uncached part. Add the cache parts so
55 // promptTokens is the total input, the same as the other adapters.
56 const promptTokens = inputTokens + (cacheRead ?? 0) + (cacheCreation ?? 0)
57
58 const result = buildBaseUsage<AnthropicProviderUsageDetails>({
59 promptTokens,
60 completionTokens: outputTokens,
61 totalTokens: promptTokens + outputTokens,
62 })
63
64 // Add prompt token details for cache tokens. Only attach the details object
65 // when at least one field is present so we don't emit an empty `{}` (every
66 // other adapter guards with the same Object.keys check).
67 const promptTokensDetails = {
68 ...(cacheCreation ? { cacheWriteTokens: cacheCreation } : {}),
69 ...(cacheRead ? { cachedTokens: cacheRead } : {}),
70 }
71 if (Object.keys(promptTokensDetails).length > 0) {
72 result.promptTokensDetails = promptTokensDetails
73 }
74
75 // Add provider-specific usage details for server tool use, again only when
76 // the provider actually reported any server tool requests.
77 const serverToolUse = usage.server_tool_use ?? start?.server_tool_use
78 const serverToolUseDetails = {
79 ...(serverToolUse?.web_search_requests
80 ? { webSearchRequests: serverToolUse.web_search_requests }
81 : {}),
82 ...(serverToolUse?.web_fetch_requests
83 ? { webFetchRequests: serverToolUse.web_fetch_requests }
84 : {}),
85 }
86 if (Object.keys(serverToolUseDetails).length > 0) {
87 result.providerUsageDetails = {
88 serverToolUse: serverToolUseDetails,
89 } satisfies AnthropicProviderUsageDetails
90 }
91
92 return result
93}