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 threadId: 'thread-1',
108 adapter: createAdapter(),
109 messages: [{ role: 'user', content: 'Hello' }],
110 })) {
111 chunks.push(chunk)
112 }
113
114 const doneChunk = chunks.find((c) => c.type === 'RUN_FINISHED')
115 expect(doneChunk).toBeDefined()
116 if (doneChunk?.type === 'RUN_FINISHED') {
117 expect(doneChunk.usage).toMatchObject({
118 promptTokens: 100,
119 completionTokens: 50,
120 totalTokens: 150,
121 })
122 }
123 })
124
125 it('extracts prompt tokens details', async () => {
126 const streamChunks = [
127 {
128 id: 'chatcmpl-123',
129 model: 'openai/gpt-4o-mini',
130 choices: [
131 {
132 delta: { content: 'Hello world' },
133 finishReason: null,
134 },
135 ],
136 },
137 {
138 id: 'chatcmpl-123',
139 model: 'openai/gpt-4o-mini',
140 choices: [
141 {
142 delta: {},
143 finishReason: 'stop',
144 },
145 ],
146 usage: {
147 promptTokens: 100,
148 completionTokens: 50,
149 totalTokens: 150,
150 promptTokensDetails: {
151 cachedTokens: 25,
152 },
153 },
154 },
155 ]
156
157 mockSend.mockImplementation((params) => {
158 if (params.chatRequest?.stream) {
159 return Promise.resolve(createAsyncIterable(streamChunks))
160 }
161 return Promise.resolve({})
162 })
163
164 const chunks: Array<AdapterYieldChunk> = []
165 for await (const chunk of chat({
166 threadId: 'thread-1',
167 adapter: createAdapter(),
168 messages: [{ role: 'user', content: 'Hello' }],
169 })) {
170 chunks.push(chunk)
171 }
172
173 const doneChunk = chunks.find((c) => c.type === 'RUN_FINISHED')
174 expect(doneChunk).toBeDefined()
175 if (doneChunk?.type === 'RUN_FINISHED') {
176 expect(tokenUsageOf(doneChunk)?.promptTokensDetails).toEqual({
177 cachedTokens: 25,
178 })
179 }
180 })
181
182 it('extracts completion tokens details with reasoning tokens', async () => {
183 const streamChunks = [
184 {
185 id: 'chatcmpl-123',
186 model: 'openai/gpt-4o-mini',
187 choices: [
188 {
189 delta: { content: 'Hello world' },
190 finishReason: null,
191 },
192 ],
193 },
194 {
195 id: 'chatcmpl-123',
196 model: 'openai/gpt-4o-mini',
197 choices: [
198 {
199 delta: {},
200 finishReason: 'stop',
201 },
202 ],
203 usage: {
204 promptTokens: 100,
205 completionTokens: 50,
206 totalTokens: 150,
207 completionTokensDetails: {
208 reasoningTokens: 30,
209 },
210 },
211 },
212 ]
213
214 mockSend.mockImplementation((params) => {
215 if (params.chatRequest?.stream) {
216 return Promise.resolve(createAsyncIterable(streamChunks))
217 }
218 return Promise.resolve({})
219 })
220
221 const chunks: Array<AdapterYieldChunk> = []
222 for await (const chunk of chat({
223 threadId: 'thread-1',
224 adapter: createAdapter(),
225 messages: [{ role: 'user', content: 'Hello' }],
226 })) {
227 chunks.push(chunk)
228 }
229
230 const doneChunk = chunks.find((c) => c.type === 'RUN_FINISHED')
231 expect(doneChunk).toBeDefined()
232 if (doneChunk?.type === 'RUN_FINISHED') {
233 expect(tokenUsageOf(doneChunk)?.completionTokensDetails).toEqual({
234 reasoningTokens: 30,
235 })
236 }
237 })
238
239 it('extracts completion tokens details with prediction tokens', async () => {
240 const streamChunks = [
241 {
242 id: 'chatcmpl-123',
243 model: 'openai/gpt-4o-mini',
244 choices: [
245 {
246 delta: { content: 'Hello world' },
247 finishReason: null,
248 },
249 ],
250 },
251 {
252 id: 'chatcmpl-123',
253 model: 'openai/gpt-4o-mini',
254 choices: [
255 {
256 delta: {},
257 finishReason: 'stop',
258 },
259 ],
260 usage: {
261 promptTokens: 100,
262 completionTokens: 50,
263 totalTokens: 150,
264 completionTokensDetails: {
265 acceptedPredictionTokens: 20,
266 rejectedPredictionTokens: 5,
267 },
268 },
269 },
270 ]
271
272 mockSend.mockImplementation((params) => {
273 if (params.chatRequest?.stream) {
274 return Promise.resolve(createAsyncIterable(streamChunks))
275 }
276 return Promise.resolve({})
277 })
278
279 const chunks: Array<AdapterYieldChunk> = []
280 for await (const chunk of chat({
281 threadId: 'thread-1',
282 adapter: createAdapter(),
283 messages: [{ role: 'user', content: 'Hello' }],
284 })) {
285 chunks.push(chunk)
286 }
287
288 const doneChunk = chunks.find((c) => c.type === 'RUN_FINISHED')
289 expect(doneChunk).toBeDefined()
290 // Prediction tokens are OpenRouter-specific, so they go in providerUsageDetails
291 if (doneChunk?.type === 'RUN_FINISHED') {
292 expect(tokenUsageOf(doneChunk)?.providerUsageDetails).toEqual({
293 acceptedPredictionTokens: 20,
294 rejectedPredictionTokens: 5,
295 })
296 }
297 })
298
299 it('handles response with no usage data - no done chunk emitted', async () => {
300 const streamChunks = [
301 {
302 id: 'chatcmpl-123',
303 model: 'openai/gpt-4o-mini',
304 choices: [
305 {
306 delta: { content: 'Hello world' },
307 finishReason: null,
308 },
309 ],
310 },
311 {
312 id: 'chatcmpl-123',
313 model: 'openai/gpt-4o-mini',
314 choices: [
315 {
316 delta: {},
317 finishReason: 'stop',
318 },
319 ],
320 // No usage field
321 },
322 ]
323
324 mockSend.mockImplementation((params) => {
325 if (params.chatRequest?.stream) {
326 return Promise.resolve(createAsyncIterable(streamChunks))
327 }
328 return Promise.resolve({})
329 })
330
331 const chunks: Array<AdapterYieldChunk> = []
332 for await (const chunk of chat({
333 threadId: 'thread-1',
334 adapter: createAdapter(),
335 messages: [{ role: 'user', content: 'Hello' }],
336 })) {
337 chunks.push(chunk)
338 }
339
340 // AG-UI RUN_FINISHED is always emitted on successful stream completion,
341 // but its usage field should be undefined when the provider doesn't
342 // include usage data.
343 const doneChunk = chunks.find((c) => c.type === 'RUN_FINISHED')
344 if (doneChunk?.type === 'RUN_FINISHED') {
345 expect(doneChunk.usage).toBeUndefined()
346 }
347 })
348})