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

api.openai-responses-usage.ts

50 lines1.7 KB

1import { createFileRoute } from '@tanstack/react-router'
2import { chat, createChatOptions } from '@tanstack/ai'
3import { createOpenaiChat } from '@tanstack/ai-openai'
4​
5const LLMOCK_DEFAULT_BASE = process.env.LLMOCK_URL || 'http://127.0.0.1:4010'
6const DUMMY_KEY = 'sk-e2e-test-dummy-key'
7​
8/**
9 * Drives the OpenAI Responses adapter against a hand-crafted aimock mount
10 * (`/openai-responses-usage`) whose `response.completed` usage reports
11 * `input_tokens_details.cache_write_tokens`. The companion spec asserts it
12 * reaches `RUN_FINISHED.usage` as `promptTokensDetails.cacheWriteTokens`.
13 */
14export const Route = createFileRoute('/api/openai-responses-usage')({
15 server: {
16 handlers: {
17 POST: async () => {
18 const adapter = createOpenaiChat('gpt-4o', DUMMY_KEY, {
19 baseURL: `${LLMOCK_DEFAULT_BASE}/openai-responses-usage/v1`,
20 })
21​
22 let usage: Record<string, unknown> | undefined
23 try {
24 for await (const chunk of chat({
25 threadId: 'openai-responses-usage',
26 ...createChatOptions({ adapter }),
27 messages: [{ role: 'user', content: 'hi' }],
28 })) {
29 if (chunk.type === 'RUN_FINISHED') {
30 usage = chunk.usage as Record<string, unknown> | undefined
31 }
32 }
33 } catch (error) {
34 return new Response(
35 JSON.stringify({
36 ok: false,
37 error: error instanceof Error ? error.message : String(error),
38 }),
39 { status: 200, headers: { 'Content-Type': 'application/json' } },
40 )
41 }
42​
43 return new Response(JSON.stringify({ ok: true, usage }), {
44 status: 200,
45 headers: { 'Content-Type': 'application/json' },
46 })
47 },
48 },
49 },
50})