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

structured-usage.test.ts

109 lines3.5 KB

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 threadId: 'thread-1',
71 model: 'openai/gpt-4o-mini',
72 messages: [{ role: 'user', content: 'Return an answer.' }],
73 logger: resolveDebugOption(false),
74 },
75 outputSchema: {
76 type: 'object',
77 properties: { answer: { type: 'string' } },
78 required: ['answer'],
79 },
80 })) {
81 chunks.push(chunk)
82 }
83 const terminal = chunks.at(-1)
84 expect(terminal?.type).toBe(code ? 'RUN_ERROR' : 'RUN_FINISHED')
85 if (terminal?.type === 'RUN_ERROR') expect(terminal.code).toBe(code)
86 expect(chunks.filter((chunk) => 'usage' in chunk)).toHaveLength(1)
87 expect(terminal).toMatchObject({
88 usage: {
89 promptTokens: 10,
90 completionTokens: 50,
91 totalTokens: 60,
92 completionTokensDetails: { reasoningTokens: 42 },
93 cost: 0.002,
94 },
95 })
96 expect(fetcher).toHaveBeenCalledTimes(1)
97 expect(chunks.filter((chunk) => chunk.type === 'CUSTOM')).toEqual(
98 code
99 ? []
100 : [
101 expect.objectContaining({
102 name: 'structured-output.complete',
103 value: { object: { answer: 'ok' }, raw: content },
104 }),
105 ],
106 )
107 },
108 )
109})