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 threadId: string,
28): Promise<string> {
29 let text = ''
30 for await (const chunk of chat({
31 adapter,
32 threadId,
33 messages: [
34 ...messages,
35 {
36 role: 'user',
37 content: 'Summarize the conversation above in 3-4 sentences.',
38 },
39 ],
40 agentLoopStrategy: maxIterations(1),
41 })) {
42 if (chunk.type === 'TEXT_MESSAGE_CONTENT') text += chunk.delta
43 }
44 return text
45}
46
47const SYSTEM_PROMPT = `You are a helpful assistant. Keep answers reasonably long
48(a paragraph or two) so this demo's context fills up quickly.`
49
50/**
51 * Chat endpoint for the `/compaction` demo. Wires `withCompaction` with a small
52 * `maxTokens` so the middleware fires after a couple of turns. Compaction here
53 * evicts the oldest messages (no `summarize` callback), keeping the recent tail
54 * verbatim; each event is recorded so the page can show before/after tokens.
55 *
56 * `threadId` scopes the recorded events; it is demo-only (never trust a
57 * client-supplied identity in production).
58 */
59export const Route = createFileRoute('/api/compaction-chat')({
60 server: {
61 handlers: {
62 POST: async ({ request }) => {
63 const requestSignal = request.signal
64 if (requestSignal.aborted) {
65 return new Response(null, { status: 499 })
66 }
67
68 const abortController = new AbortController()
69 const body = await request.json()
70 const messages = body.messages
71 const data = body.forwardedProps || {}
72
73 const provider: Provider = data.provider || 'openai'
74 const model: string | undefined = data.model
75 const threadId: string = body.threadId
76 const maxTokens: number =
77 typeof data.maxTokens === 'number' && data.maxTokens > 0
78 ? data.maxTokens
79 : 400
80 const strategyName: 'evict' | 'summarize' =
81 data.strategy === 'summarize' ? 'summarize' : 'evict'
82
83 try {
84 const adapterConfig = {
85 anthropic: () =>
86 createChatOptions({
87 adapter: anthropicText((model || 'claude-sonnet-4-5') as any),
88 }),
89 gemini: () =>
90 createChatOptions({
91 adapter: geminiText((model || 'gemini-2.5-flash') as any),
92 }),
93 grok: () =>
94 createChatOptions({
95 adapter: grokText((model || 'grok-build-0.1') as any),
96 }),
97 ollama: () =>
98 createChatOptions({
99 adapter: ollamaText((model || 'mistral:7b') as any),
100 }),
101 openai: () =>
102 createChatOptions({
103 adapter: openaiText((model || 'gpt-4o') as any),
104 }),
105 openrouter: () =>
106 createChatOptions({
107 adapter: openRouterText((model || 'openai/gpt-4o') as any),
108 }),
109 }
110
111 const options = adapterConfig[provider]()
112 const { adapter } = options
113
114 const strategy =
115 strategyName === 'summarize'
116 ? summarizeOldest({
117 summarize: (msgs) => summarizeWith(adapter, msgs, threadId),
118 })
119 : evictOldest()
120
121 const compaction = withCompaction({
122 maxTokens,
123 strategy,
124 onCompact: (info) => recordCompaction(threadId, info),
125 })
126
127 const stream = chat({
128 ...options,
129 adapter,
130 tools: [],
131 systemPrompts: [SYSTEM_PROMPT],
132 middleware: [compaction],
133 agentLoopStrategy: maxIterations(5),
134 messages,
135 threadId,
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})