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

api.openai-usage-details.ts

50 lines1.8 KB

1import { createFileRoute } from '@tanstack/react-router'
2import { chat, createChatOptions } from '@tanstack/ai'
3import { createOpenaiChatCompletions } 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 chat-completions adapter against a hand-crafted aimock mount
10 * (`/openai-usage-details`) whose stream ends with a usage-only chunk carrying
11 * `prompt_tokens_details` / `completion_tokens_details`. The companion spec
12 * asserts those reach `RUN_FINISHED.usage` as the canonical detail breakdowns —
13 * proving detailed token usage survives end-to-end through the chat pipeline.
14 */
15export const Route = createFileRoute('/api/openai-usage-details')({
16 server: {
17 handlers: {
18 POST: async () => {
19 const adapter = createOpenaiChatCompletions('gpt-4o', DUMMY_KEY, {
20 baseURL: `${LLMOCK_DEFAULT_BASE}/openai-usage-details/v1`,
21 })
22​
23 let usage: Record<string, unknown> | undefined
24 try {
25 for await (const chunk of chat({
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})