Open History to see the last commit
1import { createFileRoute } from '@tanstack/react-router'
2import {
3 chat,
4 createChatOptions,
5 maxIterations,
6 toServerSentEventsResponse,
7} from '@tanstack/ai'
8import {
9 evictOldest,
10 summarizeOldest,
11 withCompaction,
12} from '@tanstack/ai-compaction'
13import { anthropicText } from '@tanstack/ai-anthropic'
14import { geminiText } from '@tanstack/ai-gemini'
15import { grokText } from '@tanstack/ai-grok'
16import { openaiText } from '@tanstack/ai-openai'
17import { ollamaText } from '@tanstack/ai-ollama'
18import { openRouterText } from '@tanstack/ai-openrouter'
19import { recordCompaction } from '@/lib/compaction-store'
20import type { AnyTextAdapter, ModelMessage } from '@tanstack/ai'
21import type { Provider } from '@/lib/model-selection'
22
23// Provider-agnostic summary: one throwaway chat() turn on the same adapter.
24async function summarizeWith(
25 adapter: AnyTextAdapter,
26 messages: Array<ModelMessage>,
27): Promise<string> {
28 let text = ''
29 for await (const chunk of chat({
30 adapter,
31 messages: [
32 ...messages,
33 {
34 role: 'user',
35 content: 'Summarize the conversation above in 3-4 sentences.',
36 },
37 ],
38 agentLoopStrategy: maxIterations(1),
39 })) {
40 if (chunk.type === 'TEXT_MESSAGE_CONTENT') text += chunk.delta
41 }
42 return text
43}
44
45const SYSTEM_PROMPT = `You are a helpful assistant. Keep answers reasonably long
46(a paragraph or two) so this demo's context fills up quickly.`
47
48/**
49 * Chat endpoint for the `/compaction` demo. Wires `withCompaction` with a small
50 * `maxTokens` so the middleware fires after a couple of turns. Compaction here
51 * evicts the oldest messages (no `summarize` callback), keeping the recent tail
52 * verbatim; each event is recorded so the page can show before/after tokens.
53 *
54 * `threadId` scopes the recorded events; it is demo-only (never trust a
55 * client-supplied identity in production).
56 */
57export const Route = createFileRoute('/api/compaction-chat')({
58 server: {
59 handlers: {
60 POST: async ({ request }) => {
61 const requestSignal = request.signal
62 if (requestSignal.aborted) {
63 return new Response(null, { status: 499 })
64 }
65
66 const abortController = new AbortController()
67 const body = await request.json()
68 const messages = body.messages
69 const data = body.data || {}
70
71 const provider: Provider = data.provider || 'openai'
72 const model: string | undefined = data.model
73 const threadId: string =
74 typeof data.threadId === 'string' && data.threadId.length > 0
75 ? data.threadId
76 : 'panel-default-thread'
77 const maxTokens: number =
78 typeof data.maxTokens === 'number' && data.maxTokens > 0
79 ? data.maxTokens
80 : 400
81 const strategyName: 'evict' | 'summarize' =
82 data.strategy === 'summarize' ? 'summarize' : 'evict'
83
84 try {
85 const adapterConfig = {
86 anthropic: () =>
87 createChatOptions({
88 adapter: anthropicText((model || 'claude-sonnet-4-5') as any),
89 }),
90 gemini: () =>
91 createChatOptions({
92 adapter: geminiText((model || 'gemini-2.5-flash') as any),
93 }),
94 grok: () =>
95 createChatOptions({
96 adapter: grokText((model || 'grok-build-0.1') as any),
97 }),
98 ollama: () =>
99 createChatOptions({
100 adapter: ollamaText((model || 'mistral:7b') as any),
101 }),
102 openai: () =>
103 createChatOptions({
104 adapter: openaiText((model || 'gpt-4o') as any),
105 }),
106 openrouter: () =>
107 createChatOptions({
108 adapter: openRouterText((model || 'openai/gpt-4o') as any),
109 }),
110 }
111
112 const options = adapterConfig[provider]()
113 const { adapter } = options
114
115 const strategy =
116 strategyName === 'summarize'
117 ? summarizeOldest({
118 summarize: (msgs) => summarizeWith(adapter, msgs),
119 })
120 : evictOldest()
121
122 const compaction = withCompaction({
123 maxTokens,
124 strategy,
125 onCompact: (info) => recordCompaction(threadId, info),
126 })
127
128 const stream = chat({
129 ...options,
130 adapter,
131 tools: [],
132 systemPrompts: [SYSTEM_PROMPT],
133 middleware: [compaction],
134 agentLoopStrategy: maxIterations(5),
135 messages,
136 abortController,
137 })
138
139 return toServerSentEventsResponse(stream, { abortController })
140 } catch (error: any) {
141 console.error('[api.compaction-chat] Error:', error?.message)
142 if (error.name === 'AbortError' || abortController.signal.aborted) {
143 return new Response(null, { status: 499 })
144 }
145 return new Response(
146 JSON.stringify({ error: error.message || 'An error occurred' }),
147 {
148 status: 500,
149 headers: { 'Content-Type': 'application/json' },
150 },
151 )
152 }
153 },
154 },
155 },
156})