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

api.compaction-usage-wire.ts

307 lines9.8 KB

1import { createFileRoute } from '@tanstack/react-router'
2import {
3 LogRecordsCapability,
4 MetadataCapability,
5 chat,
6 createChatOptions,
7 defineChatMiddleware,
8 maxIterations,
9 provideLogRecords,
10 provideMetadata,
11} from '@tanstack/ai'
12import { createOpenaiChat } from '@tanstack/ai-openai'
13import {
14 evictOldest,
15 projectCompaction,
16 summarizeOldest,
17 withCompaction,
18} from '@tanstack/ai-compaction'
19import type { CompactionInfo } from '@tanstack/ai-compaction'
20import type { ChatMiddleware, MetadataStore, ModelMessage } from '@tanstack/ai'
21​
22const DUMMY_KEY = 'sk-e2e-test-dummy-key'
23const THREAD = 'compaction-usage-wire'
24/** Where `withCompaction` keeps a ready background summary. */
25const BACKGROUND_NAMESPACE = '@tanstack/ai-compaction:background'
26​
27/** One OpenAI Responses answer `ok` that reports `inputTokens` of usage. */
28function textStream(callNumber: number, inputTokens: number) {
29 const encoder = new TextEncoder()
30 const id = `resp_usage_${callNumber}`
31 const itemId = `msg_usage_${callNumber}`
32 const events = [
33 {
34 type: 'response.created',
35 response: { id, object: 'response', status: 'in_progress', output: [] },
36 },
37 {
38 type: 'response.output_text.delta',
39 response_id: id,
40 item_id: itemId,
41 output_index: 0,
42 content_index: 0,
43 delta: 'ok',
44 },
45 {
46 type: 'response.completed',
47 response: {
48 id,
49 object: 'response',
50 status: 'completed',
51 output: [
52 {
53 id: itemId,
54 type: 'message',
55 role: 'assistant',
56 status: 'completed',
57 content: [{ type: 'output_text', text: 'ok' }],
58 },
59 ],
60 usage: {
61 input_tokens: inputTokens,
62 output_tokens: 2,
63 total_tokens: inputTokens + 2,
64 },
65 },
66 },
67 ]
68 return new ReadableStream<Uint8Array>({
69 start(controller) {
70 for (const event of events) {
71 controller.enqueue(encoder.encode(`data: ${JSON.stringify(event)}\n\n`))
72 }
73 controller.enqueue(encoder.encode('data: [DONE]\n\n'))
74 controller.close()
75 },
76 })
78​
79// About 15 + 10 + 3 = 28 estimated tokens.
80const shortChat: Array<ModelMessage> = [
81 { role: 'user', content: `SECRET_ALPHA_ONE ${'x'.repeat(40)}` },
82 { role: 'assistant', content: 'x'.repeat(40) },
83 { role: 'user', content: 'KEEP_ME_LAST' },
85// The first run's messages, its answer, and one new question.
86const nextTurn: Array<ModelMessage> = [
87 ...shortChat,
88 { role: 'assistant', content: 'ok' },
89 { role: 'user', content: 'next' },
91​
92// About 41 + 10 + 10 = 61 estimated tokens: over atTokens 50, under maxTokens 100.
93const backgroundChat: Array<ModelMessage> = [
94 { role: 'user', content: `OLD_DETAIL ${'x'.repeat(150)}` },
95 { role: 'assistant', content: 'x'.repeat(40) },
96 { role: 'user', content: 'x'.repeat(40) },
98​
99type Case = 'usage' | 'compact-next' | 'durable' | 'background' | 'overflow'
100​
101function isCase(value: string | null): value is Case {
102 return (
103 value === 'usage' ||
104 value === 'compact-next' ||
105 value === 'durable' ||
106 value === 'background' ||
107 value === 'overflow'
108 )
110​
111/** A metadata store in a Map, so the route can read what compaction wrote. */
112function mapStore(): MetadataStore {
113 const values = new Map<string, unknown>()
114 return {
115 get: async (namespace, key) => values.get(`${namespace}:${key}`) ?? null,
116 set: async (namespace, key, value) => {
117 values.set(`${namespace}:${key}`, value)
118 },
119 delete: async (namespace, key) => {
120 values.delete(`${namespace}:${key}`)
121 },
122 }
124​
125/**
126 * Wire checks for the newer `withCompaction` options. A capturing `fetch`
127 * answers each OpenAI Responses call and records the request body.
128 *
129 * POST `?case=`:
130 * - `usage`: `countTokens: 'usage'`. The first call reports 500 input tokens.
131 * The estimate of the second run is small, but the saved usage is over
132 * `maxTokens`, so the second request is compacted.
133 * - `compact-next`: `auto: false` and a large `maxTokens`. `compactNext`
134 * compacts the first request anyway.
135 * - `durable`: a host middleware provides `LogRecordsCapability`. The
136 * compaction goes into the log, and `projectCompaction` folds it to the
137 * list the model got.
138 * - `background`: `background: { atTokens }`. The first run starts the
139 * summary and does not wait for it. The second run applies it.
140 * - `overflow`: the first call fails with OpenAI's `context_length_exceeded`.
141 * `withCompaction` compacts and calls the model again in the same run.
142 */
143export const Route = createFileRoute('/api/compaction-usage-wire')({
144 server: {
145 handlers: {
146 POST: async ({ request }) => {
147 const which = new URL(request.url).searchParams.get('case')
148 if (!isCase(which)) {
149 return Response.json({ ok: false, error: 'unknown case' })
150 }
151​
152 const bodies: Array<unknown> = []
153 const fetchMock: typeof fetch = async (input, init) => {
154 const req =
155 input instanceof Request ? input : new Request(input, init)
156 bodies.push(JSON.parse(await req.text()))
157 if (which === 'overflow' && bodies.length === 1) {
158 return Response.json(
159 {
160 error: {
161 message:
162 "This model's maximum context length is 128000 tokens.",
163 type: 'invalid_request_error',
164 code: 'context_length_exceeded',
165 },
166 },
167 { status: 400 },
168 )
169 }
170 return new Response(
171 textStream(bodies.length, bodies.length === 1 ? 500 : 20),
172 { headers: { 'Content-Type': 'text/event-stream' } },
173 )
174 }
175 const adapter = createOpenaiChat('gpt-5.2', DUMMY_KEY, {
176 fetch: fetchMock,
177 })
178​
179 const compacted: Array<CompactionInfo> = []
180 const onCompact = (info: CompactionInfo) => {
181 compacted.push(info)
182 }
183 const records: Array<{ type: string } & Record<string, unknown>> = []
184 const errors: Array<string | undefined> = []
185 const store = mapStore()
186 const host = defineChatMiddleware({
187 name: 'e2e-host',
188 provides: [LogRecordsCapability, MetadataCapability],
189 setup(ctx) {
190 provideLogRecords(ctx, {
191 append: async (batch) => {
192 records.push(...batch)
193 },
194 })
195 provideMetadata(ctx, store)
196 },
197 })
198​
199 const run = async (
200 messages: Array<ModelMessage>,
201 runId: string,
202 middleware: Array<ChatMiddleware>,
203 ) => {
204 for await (const chunk of chat({
205 ...createChatOptions({ adapter }),
206 messages,
207 threadId: THREAD,
208 runId,
209 middleware,
210 agentLoopStrategy: maxIterations(1),
211 })) {
212 if (chunk.type === 'RUN_ERROR') errors.push(chunk.code)
213 }
214 }
215​
216 try {
217 if (which === 'usage') {
218 const compaction = withCompaction({
219 maxTokens: 100,
220 countTokens: 'usage',
221 strategy: evictOldest({ keepRecentTokens: 15 }),
222 onCompact,
223 })
224 await run(shortChat, 'usage-1', [compaction])
225 await run(nextTurn, 'usage-2', [compaction])
226 }
227​
228 if (which === 'compact-next') {
229 const compaction = withCompaction({
230 maxTokens: 100_000,
231 auto: false,
232 strategy: evictOldest({ keepRecentTokens: 15 }),
233 onCompact,
234 })
235 compaction.compactNext(THREAD)
236 await run(shortChat, 'compact-next-1', [compaction])
237 }
238​
239 if (which === 'overflow') {
240 const compaction = withCompaction({
241 maxTokens: 100_000,
242 strategy: evictOldest({ keepRecentTokens: 15 }),
243 onCompact,
244 })
245 await run(shortChat, 'overflow-1', [compaction])
246 }
247​
248 if (which === 'durable') {
249 const compaction = withCompaction({
250 maxTokens: 20,
251 durable: true,
252 strategy: evictOldest({ keepRecentTokens: 15 }),
253 onCompact,
254 })
255 await run(shortChat, 'durable-1', [host, compaction])
256 }
257​
258 if (which === 'background') {
259 const compaction = withCompaction({
260 maxTokens: 100,
261 background: { atTokens: 50 },
262 strategy: summarizeOldest({
263 summarize: async () => 'EARLIER_SUMMARY',
264 keepRecentTokens: 25,
265 }),
266 onCompact,
267 })
268 await run(backgroundChat, 'background-1', [host, compaction])
269 // The summary runs beside the first run. Wait until it is ready.
270 for (let tries = 0; tries < 100; tries++) {
271 if ((await store.get(BACKGROUND_NAMESPACE, THREAD)) !== null) {
272 break
273 }
274 await new Promise((resolve) => setTimeout(resolve, 20))
275 }
276 await run(
277 [
278 ...backgroundChat,
279 { role: 'assistant', content: 'ok' },
280 { role: 'user', content: 'next' },
281 ],
282 'background-2',
283 [host, compaction],
284 )
285 }
286 } catch (error) {
287 return Response.json({
288 ok: false,
289 error: error instanceof Error ? error.message : String(error),
290 })
291 }
292​
293 const [record] = records
294 return Response.json({
295 ok: true,
296 bodies,
297 reasons: compacted.map((info) => info.reason),
298 errors,
299 records,
300 folded: record
301 ? projectCompaction({ messages: shortChat, record })
302 : undefined,
303 })
304 },
305 },
306 },
307})