Open History to see the last commit
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 }
36}
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 ])
64}
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 threadId: 'thread-1',
83 adapter: createAdapter(),
84 messages: [{ role: 'user', content: 'Hello' }],
85 })) {
86 chunks.push(chunk)
87 }
88
89 const doneChunk = chunks.find((c) => c.type === 'RUN_FINISHED')
90 expect(doneChunk).toBeDefined()
91 if (doneChunk?.type === 'RUN_FINISHED') {
92 expect(doneChunk.usage).toMatchObject({
93 promptTokens: 100,
94 completionTokens: 50,
95 totalTokens: 150,
96 })
97 }
98 })
99
100 it('extracts cached prompt and reasoning output token details', async () => {
101 mocks.responsesCreate.mockResolvedValueOnce(
102 responseStreamWithUsage({
103 input_tokens: 100,
104 output_tokens: 80,
105 total_tokens: 180,
106 input_tokens_details: {
107 cached_tokens: 25,
108 },
109 output_tokens_details: {
110 reasoning_tokens: 30,
111 },
112 }),
113 )
114
115 const chunks: Array<AdapterYieldChunk> = []
116 for await (const chunk of chat({
117 threadId: 'thread-1',
118 adapter: createAdapter(),
119 messages: [{ role: 'user', content: 'Hello' }],
120 })) {
121 chunks.push(chunk)
122 }
123
124 const doneChunk = chunks.find((c) => c.type === 'RUN_FINISHED')
125 expect(doneChunk).toBeDefined()
126 if (doneChunk?.type === 'RUN_FINISHED') {
127 expect(doneChunk.usage).toMatchObject({
128 promptTokens: 100,
129 completionTokens: 80,
130 totalTokens: 180,
131 promptTokensDetails: {
132 cachedTokens: 25,
133 },
134 completionTokensDetails: {
135 reasoningTokens: 30,
136 },
137 })
138 }
139 })
140})