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

usage-extraction.test.ts

379 lines9.8 KB

1import type { TokenUsage } from '@tanstack/ai'
2import { beforeEach, describe, expect, it, vi } from 'vitest'
3import { chat } from '@tanstack/ai'
4import { GeminiTextAdapter } from '../src/adapters/text'
5import type { AdapterYieldChunk } from '@tanstack/ai'
6​
7/** `chat()` restores a TokenUsage object on RUN_FINISHED. */
8function tokenUsageOf(chunk: unknown): TokenUsage | undefined {
9 if (typeof chunk !== 'object' || chunk === null || !('usage' in chunk)) {
10 return undefined
11 }
12 const usage = chunk.usage
13 if (
14 typeof usage !== 'object' ||
15 usage === null ||
16 Array.isArray(usage) ||
17 !('promptTokens' in usage)
18 ) {
19 return undefined
20 }
21 return usage as TokenUsage
23​
24const mocks = vi.hoisted(() => {
25 return {
26 constructorSpy: vi.fn<(options: { apiKey: string }) => void>(),
27 generateContentStreamSpy: vi.fn(),
28 }
29})
30​
31vi.mock('@google/genai', async () => {
32 const { constructorSpy, generateContentStreamSpy } = mocks
33​
34 const actual = await vi.importActual('@google/genai')
35 class MockGoogleGenAI {
36 public models = {
37 generateContentStream: generateContentStreamSpy,
38 }
39​
40 constructor(options: { apiKey: string }) {
41 constructorSpy(options)
42 }
43 }
44​
45 return {
46 GoogleGenAI: MockGoogleGenAI,
47 Type: actual.Type,
48 FinishReason: actual.FinishReason,
49 }
50})
51​
52const createAdapter = () =>
53 new GeminiTextAdapter({ apiKey: 'test-key' }, 'gemini-2.5-pro')
54​
55function createMockStream(
56 chunks: Array<Record<string, unknown>>,
57): AsyncIterable<Record<string, unknown>> {
58 return {
59 // eslint-disable-next-line @typescript-eslint/require-await
60 async *[Symbol.asyncIterator]() {
61 for (const chunk of chunks) {
62 yield chunk
63 }
64 },
65 }
67​
68describe('Gemini usage extraction', () => {
69 beforeEach(() => {
70 vi.clearAllMocks()
71 })
72​
73 it('extracts basic token usage from usageMetadata', async () => {
74 const mockStream = createMockStream([
75 {
76 candidates: [
77 {
78 content: {
79 parts: [{ text: 'Hello world' }],
80 },
81 finishReason: 'STOP',
82 },
83 ],
84 usageMetadata: {
85 promptTokenCount: 100,
86 candidatesTokenCount: 50,
87 totalTokenCount: 150,
88 },
89 },
90 ])
91​
92 mocks.generateContentStreamSpy.mockResolvedValueOnce(mockStream)
93​
94 const chunks: Array<AdapterYieldChunk> = []
95 for await (const chunk of chat({
96 threadId: 'thread-1',
97 adapter: createAdapter(),
98 messages: [{ role: 'user', content: 'Hello' }],
99 })) {
100 chunks.push(chunk)
101 }
102​
103 const doneChunk = chunks.find((c) => c.type === 'RUN_FINISHED')
104 expect(doneChunk).toBeDefined()
105 expect(doneChunk?.usage).toMatchObject({
106 promptTokens: 100,
107 completionTokens: 50,
108 totalTokens: 150,
109 })
110 })
111​
112 it('extracts cached content token count', async () => {
113 const mockStream = createMockStream([
114 {
115 candidates: [
116 {
117 content: {
118 parts: [{ text: 'Hello world' }],
119 },
120 finishReason: 'STOP',
121 },
122 ],
123 usageMetadata: {
124 promptTokenCount: 100,
125 candidatesTokenCount: 50,
126 totalTokenCount: 150,
127 cachedContentTokenCount: 25,
128 },
129 },
130 ])
131​
132 mocks.generateContentStreamSpy.mockResolvedValueOnce(mockStream)
133​
134 const chunks: Array<AdapterYieldChunk> = []
135 for await (const chunk of chat({
136 threadId: 'thread-1',
137 adapter: createAdapter(),
138 messages: [{ role: 'user', content: 'Hello' }],
139 })) {
140 chunks.push(chunk)
141 }
142​
143 const doneChunk = chunks.find((c) => c.type === 'RUN_FINISHED')
144 expect(doneChunk).toBeDefined()
145 expect(tokenUsageOf(doneChunk)?.promptTokensDetails).toMatchObject({
146 cachedTokens: 25,
147 })
148 })
149​
150 it('extracts thoughts/reasoning tokens', async () => {
151 const mockStream = createMockStream([
152 {
153 candidates: [
154 {
155 content: {
156 parts: [{ text: 'Hello world' }],
157 },
158 finishReason: 'STOP',
159 },
160 ],
161 usageMetadata: {
162 promptTokenCount: 100,
163 candidatesTokenCount: 50,
164 totalTokenCount: 150,
165 thoughtsTokenCount: 30,
166 },
167 },
168 ])
169​
170 mocks.generateContentStreamSpy.mockResolvedValueOnce(mockStream)
171​
172 const chunks: Array<AdapterYieldChunk> = []
173 for await (const chunk of chat({
174 threadId: 'thread-1',
175 adapter: createAdapter(),
176 messages: [{ role: 'user', content: 'Hello' }],
177 })) {
178 chunks.push(chunk)
179 }
180​
181 const doneChunk = chunks.find((c) => c.type === 'RUN_FINISHED')
182 expect(doneChunk).toBeDefined()
183 expect(tokenUsageOf(doneChunk)?.completionTokensDetails).toMatchObject({
184 reasoningTokens: 30,
185 })
186 })
187​
188 it('extracts modality token breakdown for prompt', async () => {
189 const mockStream = createMockStream([
190 {
191 candidates: [
192 {
193 content: {
194 parts: [{ text: 'Hello world' }],
195 },
196 finishReason: 'STOP',
197 },
198 ],
199 usageMetadata: {
200 promptTokenCount: 150,
201 candidatesTokenCount: 50,
202 totalTokenCount: 200,
203 promptTokensDetails: [
204 { modality: 'TEXT', tokenCount: 100 },
205 { modality: 'IMAGE', tokenCount: 50 },
206 ],
207 },
208 },
209 ])
210​
211 mocks.generateContentStreamSpy.mockResolvedValueOnce(mockStream)
212​
213 const chunks: Array<AdapterYieldChunk> = []
214 for await (const chunk of chat({
215 threadId: 'thread-1',
216 adapter: createAdapter(),
217 messages: [{ role: 'user', content: 'Hello' }],
218 })) {
219 chunks.push(chunk)
220 }
221​
222 const doneChunk = chunks.find((c) => c.type === 'RUN_FINISHED')
223 expect(doneChunk).toBeDefined()
224 expect(tokenUsageOf(doneChunk)?.promptTokensDetails).toMatchObject({
225 textTokens: 100,
226 imageTokens: 50,
227 })
228 })
229​
230 it('extracts modality token breakdown for completion', async () => {
231 const mockStream = createMockStream([
232 {
233 candidates: [
234 {
235 content: {
236 parts: [{ text: 'Hello world' }],
237 },
238 finishReason: 'STOP',
239 },
240 ],
241 usageMetadata: {
242 promptTokenCount: 100,
243 candidatesTokenCount: 80,
244 totalTokenCount: 180,
245 candidatesTokensDetails: [
246 { modality: 'TEXT', tokenCount: 50 },
247 { modality: 'AUDIO', tokenCount: 30 },
248 ],
249 },
250 },
251 ])
252​
253 mocks.generateContentStreamSpy.mockResolvedValueOnce(mockStream)
254​
255 const chunks: Array<AdapterYieldChunk> = []
256 for await (const chunk of chat({
257 threadId: 'thread-1',
258 adapter: createAdapter(),
259 messages: [{ role: 'user', content: 'Hello' }],
260 })) {
261 chunks.push(chunk)
262 }
263​
264 const doneChunk = chunks.find((c) => c.type === 'RUN_FINISHED')
265 expect(doneChunk).toBeDefined()
266 expect(tokenUsageOf(doneChunk)?.completionTokensDetails).toMatchObject({
267 textTokens: 50,
268 audioTokens: 30,
269 })
270 })
271​
272 it('extracts provider-specific traffic type', async () => {
273 const mockStream = createMockStream([
274 {
275 candidates: [
276 {
277 content: {
278 parts: [{ text: 'Hello world' }],
279 },
280 finishReason: 'STOP',
281 },
282 ],
283 usageMetadata: {
284 promptTokenCount: 100,
285 candidatesTokenCount: 50,
286 totalTokenCount: 150,
287 trafficType: 'ON_DEMAND',
288 },
289 },
290 ])
291​
292 mocks.generateContentStreamSpy.mockResolvedValueOnce(mockStream)
293​
294 const chunks: Array<AdapterYieldChunk> = []
295 for await (const chunk of chat({
296 threadId: 'thread-1',
297 adapter: createAdapter(),
298 messages: [{ role: 'user', content: 'Hello' }],
299 })) {
300 chunks.push(chunk)
301 }
302​
303 const doneChunk = chunks.find((c) => c.type === 'RUN_FINISHED')
304 expect(doneChunk).toBeDefined()
305 expect(tokenUsageOf(doneChunk)?.providerUsageDetails).toMatchObject({
306 trafficType: 'ON_DEMAND',
307 })
308 })
309​
310 it('extracts tool use prompt token count', async () => {
311 const mockStream = createMockStream([
312 {
313 candidates: [
314 {
315 content: {
316 parts: [{ text: 'Hello world' }],
317 },
318 finishReason: 'STOP',
319 },
320 ],
321 usageMetadata: {
322 promptTokenCount: 100,
323 candidatesTokenCount: 50,
324 totalTokenCount: 150,
325 toolUsePromptTokenCount: 20,
326 },
327 },
328 ])
329​
330 mocks.generateContentStreamSpy.mockResolvedValueOnce(mockStream)
331​
332 const chunks: Array<AdapterYieldChunk> = []
333 for await (const chunk of chat({
334 threadId: 'thread-1',
335 adapter: createAdapter(),
336 messages: [{ role: 'user', content: 'Hello' }],
337 })) {
338 chunks.push(chunk)
339 }
340​
341 const doneChunk = chunks.find((c) => c.type === 'RUN_FINISHED')
342 expect(doneChunk).toBeDefined()
343 expect(tokenUsageOf(doneChunk)?.providerUsageDetails).toMatchObject({
344 toolUsePromptTokenCount: 20,
345 })
346 })
347​
348 it('handles response with no usage metadata', async () => {
349 const mockStream = createMockStream([
350 {
351 candidates: [
352 {
353 content: {
354 parts: [{ text: 'Hello world' }],
355 },
356 finishReason: 'STOP',
357 },
358 ],
359 // No usageMetadata
360 },
361 ])
362​
363 mocks.generateContentStreamSpy.mockResolvedValueOnce(mockStream)
364​
365 const chunks: Array<AdapterYieldChunk> = []
366 for await (const chunk of chat({
367 threadId: 'thread-1',
368 adapter: createAdapter(),
369 messages: [{ role: 'user', content: 'Hello' }],
370 })) {
371 chunks.push(chunk)
372 }
373​
374 const doneChunk = chunks.find((c) => c.type === 'RUN_FINISHED')
375 expect(doneChunk).toBeDefined()
376 // When no usageMetadata is provided, usage is undefined
377 expect(doneChunk?.usage).toBeUndefined()
378 })
379})