Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

usage.ts

69 lines2.4 KB

1import { buildBaseUsage } from '@tanstack/ai'
2import type { TokenUsage } from '@tanstack/ai'
3import type { ChatResponse } from 'ollama'
4​
5/**
6 * Ollama-specific provider usage details.
7 * These fields are unique to Ollama and placed in providerUsageDetails.
8 */
9export type OllamaProviderUsageDetails = {
10 /** Time spent loading the model in nanoseconds */
11 loadDuration?: number
12 /** Time spent evaluating the prompt in nanoseconds */
13 promptEvalDuration?: number
14 /** Time spent generating the response in nanoseconds */
15 evalDuration?: number
16 /** Total duration of the request in nanoseconds */
17 totalDuration?: number
18 /** Number of prompt evaluation steps */
19 promptEvalCount?: number
20 /** Number of evaluation steps for generation */
21 evalCount?: number
23​
24/**
25 * Build normalized TokenUsage from Ollama's ChatResponse.
26 * Handles duration metrics as provider-specific details.
27 */
28export function buildOllamaUsage(
29 response: ChatResponse,
30): TokenUsage | undefined {
31 // Ollama can omit prompt_eval_count / eval_count at runtime even though the
32 // SDK types them as required. `|| 0` coalesces a missing count to 0 for
33 // arithmetic so totalTokens never becomes NaN, and stays lint-clean (matches
34 // the other provider builders).
35 const promptTokens = response.prompt_eval_count || 0
36 const completionTokens = response.eval_count || 0
37 const hasTokenCounts = promptTokens > 0 || completionTokens > 0
38​
39 const result = buildBaseUsage<OllamaProviderUsageDetails>({
40 promptTokens,
41 completionTokens,
42 totalTokens: promptTokens + completionTokens,
43 })
44​
45 // Add provider-specific duration details. Durations are optional too; guard
46 // each before comparing so missing fields don't throw under strict mode.
47 const providerDetails = {
48 ...(response.load_duration ? { loadDuration: response.load_duration } : {}),
49 ...(response.prompt_eval_duration
50 ? { promptEvalDuration: response.prompt_eval_duration }
51 : {}),
52 ...(response.eval_duration ? { evalDuration: response.eval_duration } : {}),
53 ...(response.total_duration
54 ? { totalDuration: response.total_duration }
55 : {}),
56 } satisfies OllamaProviderUsageDetails
57​
58 const hasProviderDetails = Object.keys(providerDetails).length > 0
59 if (hasProviderDetails) {
60 result.providerUsageDetails = providerDetails
61 }
62​
63 // Nothing useful to report: no token counts and no duration metrics.
64 if (!hasTokenCounts && !hasProviderDetails) {
65 return undefined
66 }
67​
68 return result