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

usage-extraction.test.ts

138 lines3.3 KB

1import { beforeEach, describe, expect, it, vi } from 'vitest'
2import { chat } from '@tanstack/ai'
3import { GrokTextAdapter } from '../src/adapters/text'
4import type { AdapterYieldChunk } from '@tanstack/ai'
5​
6const mocks = vi.hoisted(() => {
7 const responsesCreate = vi.fn()
8 return { responsesCreate }
9})
10​
11vi.mock('openai', () => {
12 const { responsesCreate } = mocks
13​
14 function MockOpenAI(this: { responses: { create: typeof responsesCreate } }) {
15 this.responses = {
16 create: responsesCreate,
17 }
18 }
19​
20 return { default: MockOpenAI }
21})
22​
23const createAdapter = () =>
24 new GrokTextAdapter({ apiKey: 'test-key' }, 'grok-4.3')
25​
26function createMockStream(
27 chunks: Array<Record<string, unknown>>,
28): AsyncIterable<Record<string, unknown>> {
29 return {
30 async *[Symbol.asyncIterator]() {
31 for (const chunk of chunks) {
32 yield chunk
33 }
34 },
35 }
37​
38function responseStreamWithUsage(usage: Record<string, unknown>) {
39 return createMockStream([
40 {
41 type: 'response.created',
42 response: { id: 'resp_123', model: 'grok-4.3' },
43 },
44 {
45 type: 'response.output_text.delta',
46 delta: 'Hello world',
47 },
48 {
49 type: 'response.completed',
50 response: {
51 id: 'resp_123',
52 model: 'grok-4.3',
53 output: [
54 {
55 type: 'message',
56 role: 'assistant',
57 content: [{ type: 'output_text', text: 'Hello world' }],
58 },
59 ],
60 usage,
61 },
62 },
63 ])
65​
66describe('Grok usage extraction', () => {
67 beforeEach(() => {
68 vi.clearAllMocks()
69 })
70​
71 it('extracts basic token usage from Responses API streams', async () => {
72 mocks.responsesCreate.mockResolvedValueOnce(
73 responseStreamWithUsage({
74 input_tokens: 100,
75 output_tokens: 50,
76 total_tokens: 150,
77 }),
78 )
79​
80 const chunks: Array<AdapterYieldChunk> = []
81 for await (const chunk of chat({
82 adapter: createAdapter(),
83 messages: [{ role: 'user', content: 'Hello' }],
84 })) {
85 chunks.push(chunk)
86 }
87​
88 const doneChunk = chunks.find((c) => c.type === 'RUN_FINISHED')
89 expect(doneChunk).toBeDefined()
90 if (doneChunk?.type === 'RUN_FINISHED') {
91 expect(doneChunk.usage).toMatchObject({
92 promptTokens: 100,
93 completionTokens: 50,
94 totalTokens: 150,
95 })
96 }
97 })
98​
99 it('extracts cached prompt and reasoning output token details', async () => {
100 mocks.responsesCreate.mockResolvedValueOnce(
101 responseStreamWithUsage({
102 input_tokens: 100,
103 output_tokens: 80,
104 total_tokens: 180,
105 input_tokens_details: {
106 cached_tokens: 25,
107 },
108 output_tokens_details: {
109 reasoning_tokens: 30,
110 },
111 }),
112 )
113​
114 const chunks: Array<AdapterYieldChunk> = []
115 for await (const chunk of chat({
116 adapter: createAdapter(),
117 messages: [{ role: 'user', content: 'Hello' }],
118 })) {
119 chunks.push(chunk)
120 }
121​
122 const doneChunk = chunks.find((c) => c.type === 'RUN_FINISHED')
123 expect(doneChunk).toBeDefined()
124 if (doneChunk?.type === 'RUN_FINISHED') {
125 expect(doneChunk.usage).toMatchObject({
126 promptTokens: 100,
127 completionTokens: 80,
128 totalTokens: 180,
129 promptTokensDetails: {
130 cachedTokens: 25,
131 },
132 completionTokensDetails: {
133 reasoningTokens: 30,
134 },
135 })
136 }
137 })
138})