Open History to see the last commit
1import { createFileRoute } from '@tanstack/react-router'
2import { chat, createChatOptions } from '@tanstack/ai'
3import { createOpenRouterText } from '@tanstack/ai-openrouter'
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 OpenRouter chat-completions adapter against a hand-crafted aimock
10 * mount (`/openrouter-cost`) whose stream ends with a usage-only chunk carrying
11 * `cost` / `cost_details`. The companion spec asserts that those values reach
12 * `RUN_FINISHED.usage` — proving the adapter forwards OpenRouter's
13 * provider-reported per-request cost.
14 */
15export const Route = createFileRoute('/api/openrouter-cost')({
16 server: {
17 handlers: {
18 POST: async () => {
19 const adapter = createOpenRouterText('openai/gpt-4o', DUMMY_KEY, {
20 serverURL: `${LLMOCK_DEFAULT_BASE}/openrouter-cost/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})