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 { createOpenRouterText } from '../src/adapters/text'
5import type { Mock } from 'vitest'
6import type { AdapterYieldChunk } from '@tanstack/ai'
7
8/** `chat()` restores a TokenUsage object on RUN_FINISHED. */
9function tokenUsageOf(chunk: unknown): TokenUsage | undefined {
10 if (typeof chunk !== 'object' || chunk === null || !('usage' in chunk)) {
11 return undefined
12 }
13 const usage = chunk.usage
14 if (
15 typeof usage !== 'object' ||
16 usage === null ||
17 Array.isArray(usage) ||
18 !('promptTokens' in usage)
19 ) {
20 return undefined
21 }
22 return usage as TokenUsage
23}
24
25let mockSend: Mock
26
27// Mock the SDK using a constructor function rather than a `class`.
28// `useDefineForClassFields: true` emits real ES2022 class fields, and vitest's
29// mock-hoister mis-rewrites a field named `chat` because that identifier is
30// also a named import on line 2 (`import { chat } from '@tanstack/ai'`). A plain
31// constructor function with `this.*` assignments sidesteps the collision.
32vi.mock('@openrouter/sdk', () => {
33 function OpenRouter(this: {
34 chat: { send: (...args: Array<unknown>) => unknown }
35 }) {
36 this.chat = {
37 send: (...args: Array<unknown>) => mockSend(...args),
38 }
39 }
40 return { OpenRouter }
41})
42
43const createAdapter = () =>
44 createOpenRouterText('openai/gpt-4o-mini', 'test-key')
45
46function createAsyncIterable<T>(chunks: Array<T>): AsyncIterable<T> {
47 return {
48 [Symbol.asyncIterator]() {
49 let index = 0
50 return {
51 // eslint-disable-next-line @typescript-eslint/require-await
52 async next() {
53 if (index < chunks.length) {
54 return { value: chunks[index++]!, done: false }
55 }
56 return { value: undefined as T, done: true }
57 },
58 }
59 },
60 }
61}
62
63describe('OpenRouter usage extraction', () => {
64 beforeEach(() => {
65 vi.clearAllMocks()
66 mockSend = vi.fn()
67 })
68
69 it('extracts basic token usage from stream', async () => {
70 const streamChunks = [
71 {
72 id: 'chatcmpl-123',
73 model: 'openai/gpt-4o-mini',
74 choices: [
75 {
76 delta: { content: 'Hello world' },
77 finishReason: null,
78 },
79 ],
80 },
81 {
82 id: 'chatcmpl-123',
83 model: 'openai/gpt-4o-mini',
84 choices: [
85 {
86 delta: {},
87 finishReason: 'stop',
88 },
89 ],
90 usage: {
91 promptTokens: 100,
92 completionTokens: 50,
93 totalTokens: 150,
94 },
95 },
96 ]
97
98 mockSend.mockImplementation((params) => {
99 if (params.chatRequest?.stream) {
100 return Promise.resolve(createAsyncIterable(streamChunks))
101 }
102 return Promise.resolve({})
103 })
104
105 const chunks: Array<AdapterYieldChunk> = []
106 for await (const chunk of chat({
107 adapter: createAdapter(),
108 messages: [{ role: 'user', content: 'Hello' }],
109 })) {
110 chunks.push(chunk)
111 }
112
113 const doneChunk = chunks.find((c) => c.type === 'RUN_FINISHED')
114 expect(doneChunk).toBeDefined()
115 if (doneChunk?.type === 'RUN_FINISHED') {
116 expect(doneChunk.usage).toMatchObject({
117 promptTokens: 100,
118 completionTokens: 50,
119 totalTokens: 150,
120 })
121 }
122 })
123
124 it('extracts prompt tokens details', async () => {
125 const streamChunks = [
126 {
127 id: 'chatcmpl-123',
128 model: 'openai/gpt-4o-mini',
129 choices: [
130 {
131 delta: { content: 'Hello world' },
132 finishReason: null,
133 },
134 ],
135 },
136 {
137 id: 'chatcmpl-123',
138 model: 'openai/gpt-4o-mini',
139 choices: [
140 {
141 delta: {},
142 finishReason: 'stop',
143 },
144 ],
145 usage: {
146 promptTokens: 100,
147 completionTokens: 50,
148 totalTokens: 150,
149 promptTokensDetails: {
150 cachedTokens: 25,
151 },
152 },
153 },
154 ]
155
156 mockSend.mockImplementation((params) => {
157 if (params.chatRequest?.stream) {
158 return Promise.resolve(createAsyncIterable(streamChunks))
159 }
160 return Promise.resolve({})
161 })
162
163 const chunks: Array<AdapterYieldChunk> = []
164 for await (const chunk of chat({
165 adapter: createAdapter(),
166 messages: [{ role: 'user', content: 'Hello' }],
167 })) {
168 chunks.push(chunk)
169 }
170
171 const doneChunk = chunks.find((c) => c.type === 'RUN_FINISHED')
172 expect(doneChunk).toBeDefined()
173 if (doneChunk?.type === 'RUN_FINISHED') {
174 expect(tokenUsageOf(doneChunk)?.promptTokensDetails).toEqual({
175 cachedTokens: 25,
176 })
177 }
178 })
179
180 it('extracts completion tokens details with reasoning tokens', async () => {
181 const streamChunks = [
182 {
183 id: 'chatcmpl-123',
184 model: 'openai/gpt-4o-mini',
185 choices: [
186 {
187 delta: { content: 'Hello world' },
188 finishReason: null,
189 },
190 ],
191 },
192 {
193 id: 'chatcmpl-123',
194 model: 'openai/gpt-4o-mini',
195 choices: [
196 {
197 delta: {},
198 finishReason: 'stop',
199 },
200 ],
201 usage: {
202 promptTokens: 100,
203 completionTokens: 50,
204 totalTokens: 150,
205 completionTokensDetails: {
206 reasoningTokens: 30,
207 },
208 },
209 },
210 ]
211
212 mockSend.mockImplementation((params) => {
213 if (params.chatRequest?.stream) {
214 return Promise.resolve(createAsyncIterable(streamChunks))
215 }
216 return Promise.resolve({})
217 })
218
219 const chunks: Array<AdapterYieldChunk> = []
220 for await (const chunk of chat({
221 adapter: createAdapter(),
222 messages: [{ role: 'user', content: 'Hello' }],
223 })) {
224 chunks.push(chunk)
225 }
226
227 const doneChunk = chunks.find((c) => c.type === 'RUN_FINISHED')
228 expect(doneChunk).toBeDefined()
229 if (doneChunk?.type === 'RUN_FINISHED') {
230 expect(tokenUsageOf(doneChunk)?.completionTokensDetails).toEqual({
231 reasoningTokens: 30,
232 })
233 }
234 })
235
236 it('extracts completion tokens details with prediction tokens', async () => {
237 const streamChunks = [
238 {
239 id: 'chatcmpl-123',
240 model: 'openai/gpt-4o-mini',
241 choices: [
242 {
243 delta: { content: 'Hello world' },
244 finishReason: null,
245 },
246 ],
247 },
248 {
249 id: 'chatcmpl-123',
250 model: 'openai/gpt-4o-mini',
251 choices: [
252 {
253 delta: {},
254 finishReason: 'stop',
255 },
256 ],
257 usage: {
258 promptTokens: 100,
259 completionTokens: 50,
260 totalTokens: 150,
261 completionTokensDetails: {
262 acceptedPredictionTokens: 20,
263 rejectedPredictionTokens: 5,
264 },
265 },
266 },
267 ]
268
269 mockSend.mockImplementation((params) => {
270 if (params.chatRequest?.stream) {
271 return Promise.resolve(createAsyncIterable(streamChunks))
272 }
273 return Promise.resolve({})
274 })
275
276 const chunks: Array<AdapterYieldChunk> = []
277 for await (const chunk of chat({
278 adapter: createAdapter(),
279 messages: [{ role: 'user', content: 'Hello' }],
280 })) {
281 chunks.push(chunk)
282 }
283
284 const doneChunk = chunks.find((c) => c.type === 'RUN_FINISHED')
285 expect(doneChunk).toBeDefined()
286 // Prediction tokens are OpenRouter-specific, so they go in providerUsageDetails
287 if (doneChunk?.type === 'RUN_FINISHED') {
288 expect(tokenUsageOf(doneChunk)?.providerUsageDetails).toEqual({
289 acceptedPredictionTokens: 20,
290 rejectedPredictionTokens: 5,
291 })
292 }
293 })
294
295 it('handles response with no usage data - no done chunk emitted', async () => {
296 const streamChunks = [
297 {
298 id: 'chatcmpl-123',
299 model: 'openai/gpt-4o-mini',
300 choices: [
301 {
302 delta: { content: 'Hello world' },
303 finishReason: null,
304 },
305 ],
306 },
307 {
308 id: 'chatcmpl-123',
309 model: 'openai/gpt-4o-mini',
310 choices: [
311 {
312 delta: {},
313 finishReason: 'stop',
314 },
315 ],
316 // No usage field
317 },
318 ]
319
320 mockSend.mockImplementation((params) => {
321 if (params.chatRequest?.stream) {
322 return Promise.resolve(createAsyncIterable(streamChunks))
323 }
324 return Promise.resolve({})
325 })
326
327 const chunks: Array<AdapterYieldChunk> = []
328 for await (const chunk of chat({
329 adapter: createAdapter(),
330 messages: [{ role: 'user', content: 'Hello' }],
331 })) {
332 chunks.push(chunk)
333 }
334
335 // AG-UI RUN_FINISHED is always emitted on successful stream completion,
336 // but its usage field should be undefined when the provider doesn't
337 // include usage data.
338 const doneChunk = chunks.find((c) => c.type === 'RUN_FINISHED')
339 if (doneChunk?.type === 'RUN_FINISHED') {
340 expect(doneChunk.usage).toBeUndefined()
341 }
342 })
343})