Open History to see the last commit
1import type { AdapterYieldChunk } from '@tanstack/ai'
2import { HTTPClient } from '@openrouter/sdk'
3import { describe, expect, it, vi } from 'vitest'
4import { resolveDebugOption } from '@tanstack/ai/adapter-internals'
5import { createOpenRouterText } from '../src/adapters/text'
6import { buildOpenRouterUsage } from '../src/usage'
7
8describe('OpenRouter structured usage', () => {
9 it.each([42, 0, undefined, null])(
10 'preserves reasoning count %s',
11 (reasoningTokens) => {
12 const usage = buildOpenRouterUsage({
13 promptTokens: 10,
14 completionTokens: 50,
15 totalTokens: 60,
16 completionTokensDetails: { reasoningTokens },
17 })
18 expect(usage?.completionTokensDetails).toEqual(
19 reasoningTokens == null ? {} : { reasoningTokens },
20 )
21 },
22 )
23
24 it.each([
25 ['success', '{"answer":"ok"}', 'stop', undefined],
26 ['malformed', '{"answer":', 'stop', 'parse-error'],
27 ['truncated', '{"answer":', 'length', 'max_tokens'],
28 ['empty', '', 'stop', 'empty-response'],
29 ] as const)(
30 'reports received usage once on %s',
31 async (_label, content, finishReason, code) => {
32 const envelope = {
33 id: 'gen-test',
34 model: 'openai/gpt-4o-mini',
35 object: 'chat.completion.chunk',
36 created: 1,
37 }
38 const events = [
39 {
40 ...envelope,
41 choices: [
42 { index: 0, delta: { content }, finish_reason: finishReason },
43 ],
44 },
45 {
46 ...envelope,
47 choices: [],
48 usage: {
49 prompt_tokens: 10,
50 completion_tokens: 50,
51 total_tokens: 60,
52 completion_tokens_details: { reasoning_tokens: 42 },
53 cost: 0.002,
54 },
55 },
56 ]
57 const fetcher = vi.fn(
58 async () =>
59 new Response(
60 `${events.map((event) => `data: ${JSON.stringify(event)}\n\n`).join('')}data: [DONE]\n\n`,
61 { headers: { 'content-type': 'text/event-stream' } },
62 ),
63 )
64 const adapter = createOpenRouterText('openai/gpt-4o-mini', 'test-key', {
65 httpClient: new HTTPClient({ fetcher }),
66 })
67 const chunks: Array<AdapterYieldChunk> = []
68 for await (const chunk of adapter.structuredOutputStream({
69 chatOptions: {
70 model: 'openai/gpt-4o-mini',
71 messages: [{ role: 'user', content: 'Return an answer.' }],
72 logger: resolveDebugOption(false),
73 },
74 outputSchema: {
75 type: 'object',
76 properties: { answer: { type: 'string' } },
77 required: ['answer'],
78 },
79 })) {
80 chunks.push(chunk)
81 }
82 const terminal = chunks.at(-1)
83 expect(terminal?.type).toBe(code ? 'RUN_ERROR' : 'RUN_FINISHED')
84 if (terminal?.type === 'RUN_ERROR') expect(terminal.code).toBe(code)
85 expect(chunks.filter((chunk) => 'usage' in chunk)).toHaveLength(1)
86 expect(terminal).toMatchObject({
87 usage: {
88 promptTokens: 10,
89 completionTokens: 50,
90 totalTokens: 60,
91 completionTokensDetails: { reasoningTokens: 42 },
92 cost: 0.002,
93 },
94 })
95 expect(fetcher).toHaveBeenCalledTimes(1)
96 expect(chunks.filter((chunk) => chunk.type === 'CUSTOM')).toEqual(
97 code
98 ? []
99 : [
100 expect.objectContaining({
101 name: 'structured-output.complete',
102 value: { object: { answer: 'ok' }, raw: content },
103 }),
104 ],
105 )
106 },
107 )
108})