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

api.moonshot-usage-details.ts

51 lines1.7 KB

1import { createFileRoute } from '@tanstack/react-router'
2import { chat, createChatOptions } from '@tanstack/ai'
3import { openaiCompatibleText } from '@tanstack/ai-openai/compatible'
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-compatible chat adapter against the
10 * `/moonshot-usage-details` aimock mount, whose last chunk carries Moonshot's
11 * usage shape (`cached_tokens` at the root, `cache_write_tokens` under
12 * `prompt_tokens_details`). Returns `RUN_FINISHED.usage`.
13 */
14export const Route = createFileRoute('/api/moonshot-usage-details')({
15 server: {
16 handlers: {
17 POST: async () => {
18 const adapter = openaiCompatibleText('kimi-k3', {
19 baseURL: `${LLMOCK_DEFAULT_BASE}/moonshot-usage-details/v1`,
20 apiKey: DUMMY_KEY,
21 })
22​
23 let usage: Record<string, unknown> | undefined
24 try {
25 for await (const chunk of chat({
26 threadId: 'moonshot-usage-details',
27 ...createChatOptions({ adapter }),
28 messages: [{ role: 'user', content: 'hi' }],
29 })) {
30 if (chunk.type === 'RUN_FINISHED') {
31 usage = chunk.usage as Record<string, unknown> | undefined
32 }
33 }
34 } catch (error) {
35 return new Response(
36 JSON.stringify({
37 ok: false,
38 error: error instanceof Error ? error.message : String(error),
39 }),
40 { status: 200, headers: { 'Content-Type': 'application/json' } },
41 )
42 }
43​
44 return new Response(JSON.stringify({ ok: true, usage }), {
45 status: 200,
46 headers: { 'Content-Type': 'application/json' },
47 })
48 },
49 },
50 },
51})