MCPcopy Create free account
hub / github.com/TanStack/ai / buildAnthropicUsage

Function buildAnthropicUsage

packages/ai-anthropic/src/usage.ts:28–81  ·  view source on GitHub ↗
(
  usage:
    | Anthropic_SDK.Beta.BetaUsage
    | Anthropic_SDK.Beta.BetaMessageDeltaUsage
    | undefined
    | null,
)

Source from the content-addressed store, hash-verified

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

Callers 2

structuredOutputMethod · 0.90

Calls 1

buildBaseUsageFunction · 0.90

Tested by

no test coverage detected