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

api.neon-wire.ts

94 lines3.2 KB

1import { createFileRoute } from '@tanstack/react-router'
2import { chat, summarize, toServerSentEventsResponse } from '@tanstack/ai'
3import { createNeonSummarize, createNeonText } from '@tanstack/ai-neon'
4​
5// Neon's catalog reports Gemini reasoning_tokens at the root of usage.
6// Keep this wire shape independent of aimock's standard OpenAI usage mapper.
7export const Route = createFileRoute('/api/neon-wire')({
8 server: {
9 handlers: {
10 POST: async ({ request }) => {
11 const params = new URL(request.url).searchParams
12 if (params.get('activity') === 'summarize') {
13 const requests: Array<{ url: string; body: unknown }> = []
14 const adapter = createNeonSummarize('gpt-6-1-sol', 'test-token', {
15 api: 'responses',
16 baseURL: process.env.LLMOCK_URL || 'http://127.0.0.1:4010',
17 fetch: async (input, init) => {
18 const outgoing = new Request(input, init)
19 requests.push({
20 url: outgoing.url,
21 body: await outgoing.clone().json(),
22 })
23 return fetch(outgoing)
24 },
25 })
26 const options = {
27 adapter,
28 threadId: 'neon-wire',
29 text: '[summarize] The Fender Stratocaster is a versatile electric guitar',
30 maxLength: 73,
31 modelOptions: { max_output_tokens: 91 },
32 }
33 let summary = ''
34 if (params.get('stream') === 'true') {
35 for await (const chunk of summarize({ ...options, stream: true })) {
36 if (chunk.type === 'RUN_ERROR') throw new Error(chunk.message)
37 if (chunk.type === 'TEXT_MESSAGE_CONTENT') summary += chunk.delta
38 }
39 } else {
40 summary = (await summarize({ ...options, stream: false })).summary
41 }
42 return Response.json({ summary, requests })
43 }
44​
45 const model = 'gemini-3-7-flash'
46 const envelope = {
47 id: null,
48 object: 'chat.completion.chunk',
49 created: 1,
50 model,
51 }
52 const chunks = [
53 {
54 ...envelope,
55 choices: [
56 {
57 index: 0,
58 delta: { content: [{ type: 'text', text: 'Hello' }] },
59 finish_reason: 'stop',
60 },
61 ],
62 },
63 {
64 ...envelope,
65 choices: [],
66 usage: {
67 prompt_tokens: 180,
68 completion_tokens: 7,
69 total_tokens: 459,
70 reasoning_tokens: 272,
71 },
72 },
73 ]
74 const adapter = createNeonText(model, 'test-token', {
75 baseURL: 'https://neon.test',
76 fetch: async () =>
77 new Response(
78 chunks
79 .map((chunk) => `data: ${JSON.stringify(chunk)}\n\n`)
80 .join('') + 'data: [DONE]\n\n',
81 { headers: { 'content-type': 'text/event-stream' } },
82 ),
83 })
84 return toServerSentEventsResponse(
85 chat({
86 adapter,
87 messages: [{ role: 'user', content: 'Hello' }],
88 threadId: 'neon-wire',
89 }),
90 )
91 },
92 },
93 },
94})