Open History to see the last commit
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
22}
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 }
66}
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 adapter: createAdapter(),
97 messages: [{ role: 'user', content: 'Hello' }],
98 })) {
99 chunks.push(chunk)
100 }
101
102 const doneChunk = chunks.find((c) => c.type === 'RUN_FINISHED')
103 expect(doneChunk).toBeDefined()
104 expect(doneChunk?.usage).toMatchObject({
105 promptTokens: 100,
106 completionTokens: 50,
107 totalTokens: 150,
108 })
109 })
110
111 it('extracts cached content token count', async () => {
112 const mockStream = createMockStream([
113 {
114 candidates: [
115 {
116 content: {
117 parts: [{ text: 'Hello world' }],
118 },
119 finishReason: 'STOP',
120 },
121 ],
122 usageMetadata: {
123 promptTokenCount: 100,
124 candidatesTokenCount: 50,
125 totalTokenCount: 150,
126 cachedContentTokenCount: 25,
127 },
128 },
129 ])
130
131 mocks.generateContentStreamSpy.mockResolvedValueOnce(mockStream)
132
133 const chunks: Array<AdapterYieldChunk> = []
134 for await (const chunk of chat({
135 adapter: createAdapter(),
136 messages: [{ role: 'user', content: 'Hello' }],
137 })) {
138 chunks.push(chunk)
139 }
140
141 const doneChunk = chunks.find((c) => c.type === 'RUN_FINISHED')
142 expect(doneChunk).toBeDefined()
143 expect(tokenUsageOf(doneChunk)?.promptTokensDetails).toMatchObject({
144 cachedTokens: 25,
145 })
146 })
147
148 it('extracts thoughts/reasoning tokens', async () => {
149 const mockStream = createMockStream([
150 {
151 candidates: [
152 {
153 content: {
154 parts: [{ text: 'Hello world' }],
155 },
156 finishReason: 'STOP',
157 },
158 ],
159 usageMetadata: {
160 promptTokenCount: 100,
161 candidatesTokenCount: 50,
162 totalTokenCount: 150,
163 thoughtsTokenCount: 30,
164 },
165 },
166 ])
167
168 mocks.generateContentStreamSpy.mockResolvedValueOnce(mockStream)
169
170 const chunks: Array<AdapterYieldChunk> = []
171 for await (const chunk of chat({
172 adapter: createAdapter(),
173 messages: [{ role: 'user', content: 'Hello' }],
174 })) {
175 chunks.push(chunk)
176 }
177
178 const doneChunk = chunks.find((c) => c.type === 'RUN_FINISHED')
179 expect(doneChunk).toBeDefined()
180 expect(tokenUsageOf(doneChunk)?.completionTokensDetails).toMatchObject({
181 reasoningTokens: 30,
182 })
183 })
184
185 it('extracts modality token breakdown for prompt', async () => {
186 const mockStream = createMockStream([
187 {
188 candidates: [
189 {
190 content: {
191 parts: [{ text: 'Hello world' }],
192 },
193 finishReason: 'STOP',
194 },
195 ],
196 usageMetadata: {
197 promptTokenCount: 150,
198 candidatesTokenCount: 50,
199 totalTokenCount: 200,
200 promptTokensDetails: [
201 { modality: 'TEXT', tokenCount: 100 },
202 { modality: 'IMAGE', tokenCount: 50 },
203 ],
204 },
205 },
206 ])
207
208 mocks.generateContentStreamSpy.mockResolvedValueOnce(mockStream)
209
210 const chunks: Array<AdapterYieldChunk> = []
211 for await (const chunk of chat({
212 adapter: createAdapter(),
213 messages: [{ role: 'user', content: 'Hello' }],
214 })) {
215 chunks.push(chunk)
216 }
217
218 const doneChunk = chunks.find((c) => c.type === 'RUN_FINISHED')
219 expect(doneChunk).toBeDefined()
220 expect(tokenUsageOf(doneChunk)?.promptTokensDetails).toMatchObject({
221 textTokens: 100,
222 imageTokens: 50,
223 })
224 })
225
226 it('extracts modality token breakdown for completion', async () => {
227 const mockStream = createMockStream([
228 {
229 candidates: [
230 {
231 content: {
232 parts: [{ text: 'Hello world' }],
233 },
234 finishReason: 'STOP',
235 },
236 ],
237 usageMetadata: {
238 promptTokenCount: 100,
239 candidatesTokenCount: 80,
240 totalTokenCount: 180,
241 candidatesTokensDetails: [
242 { modality: 'TEXT', tokenCount: 50 },
243 { modality: 'AUDIO', tokenCount: 30 },
244 ],
245 },
246 },
247 ])
248
249 mocks.generateContentStreamSpy.mockResolvedValueOnce(mockStream)
250
251 const chunks: Array<AdapterYieldChunk> = []
252 for await (const chunk of chat({
253 adapter: createAdapter(),
254 messages: [{ role: 'user', content: 'Hello' }],
255 })) {
256 chunks.push(chunk)
257 }
258
259 const doneChunk = chunks.find((c) => c.type === 'RUN_FINISHED')
260 expect(doneChunk).toBeDefined()
261 expect(tokenUsageOf(doneChunk)?.completionTokensDetails).toMatchObject({
262 textTokens: 50,
263 audioTokens: 30,
264 })
265 })
266
267 it('extracts provider-specific traffic type', async () => {
268 const mockStream = createMockStream([
269 {
270 candidates: [
271 {
272 content: {
273 parts: [{ text: 'Hello world' }],
274 },
275 finishReason: 'STOP',
276 },
277 ],
278 usageMetadata: {
279 promptTokenCount: 100,
280 candidatesTokenCount: 50,
281 totalTokenCount: 150,
282 trafficType: 'ON_DEMAND',
283 },
284 },
285 ])
286
287 mocks.generateContentStreamSpy.mockResolvedValueOnce(mockStream)
288
289 const chunks: Array<AdapterYieldChunk> = []
290 for await (const chunk of chat({
291 adapter: createAdapter(),
292 messages: [{ role: 'user', content: 'Hello' }],
293 })) {
294 chunks.push(chunk)
295 }
296
297 const doneChunk = chunks.find((c) => c.type === 'RUN_FINISHED')
298 expect(doneChunk).toBeDefined()
299 expect(tokenUsageOf(doneChunk)?.providerUsageDetails).toMatchObject({
300 trafficType: 'ON_DEMAND',
301 })
302 })
303
304 it('extracts tool use prompt token count', async () => {
305 const mockStream = createMockStream([
306 {
307 candidates: [
308 {
309 content: {
310 parts: [{ text: 'Hello world' }],
311 },
312 finishReason: 'STOP',
313 },
314 ],
315 usageMetadata: {
316 promptTokenCount: 100,
317 candidatesTokenCount: 50,
318 totalTokenCount: 150,
319 toolUsePromptTokenCount: 20,
320 },
321 },
322 ])
323
324 mocks.generateContentStreamSpy.mockResolvedValueOnce(mockStream)
325
326 const chunks: Array<AdapterYieldChunk> = []
327 for await (const chunk of chat({
328 adapter: createAdapter(),
329 messages: [{ role: 'user', content: 'Hello' }],
330 })) {
331 chunks.push(chunk)
332 }
333
334 const doneChunk = chunks.find((c) => c.type === 'RUN_FINISHED')
335 expect(doneChunk).toBeDefined()
336 expect(tokenUsageOf(doneChunk)?.providerUsageDetails).toMatchObject({
337 toolUsePromptTokenCount: 20,
338 })
339 })
340
341 it('handles response with no usage metadata', async () => {
342 const mockStream = createMockStream([
343 {
344 candidates: [
345 {
346 content: {
347 parts: [{ text: 'Hello world' }],
348 },
349 finishReason: 'STOP',
350 },
351 ],
352 // No usageMetadata
353 },
354 ])
355
356 mocks.generateContentStreamSpy.mockResolvedValueOnce(mockStream)
357
358 const chunks: Array<AdapterYieldChunk> = []
359 for await (const chunk of chat({
360 adapter: createAdapter(),
361 messages: [{ role: 'user', content: 'Hello' }],
362 })) {
363 chunks.push(chunk)
364 }
365
366 const doneChunk = chunks.find((c) => c.type === 'RUN_FINISHED')
367 expect(doneChunk).toBeDefined()
368 // When no usageMetadata is provided, usage is undefined
369 expect(doneChunk?.usage).toBeUndefined()
370 })
371})