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

summarizer.ts

258 lines9.7 KB

1import { chat } from '@tanstack/ai'
2import { sumUsage } from './usage-count'
3import type {
4 AnyTextAdapter,
5 ChatMiddleware,
6 ModelMessage,
7 TokenUsage,
8} from '@tanstack/ai'
9​
10/** What a summary callback gets with the messages. */
11export interface SummarizeInput {
12 /** The text of an earlier compaction summary at the start of `messages`. */
13 previousSummary?: string
14 /** The details text of that summary, from its `<compaction-details>` tag. */
15 previousDetails?: string
16 /** `true`: `messages` is the first part of a turn that is too large to keep. */
17 turnPrefix?: boolean
18 /**
19 * The first part of the current turn. Only the call that writes the details
20 * gets it, so `details` can see each dropped message. In a history call, a
21 * separate call summarizes these messages. In a turn-prefix call, they are
22 * the same as `messages`, and no history call runs.
23 */
24 turnPrefixMessages?: Array<ModelMessage>
25 /** Aborted when the run is cancelled. */
26 signal?: AbortSignal
28​
29/**
30 * Turns messages into summary text. Return the text, or the text and the
31 * usage of the model call, so the compaction can report the cost.
32 */
33export type Summarizer = (
34 messages: Array<ModelMessage>,
35 input: SummarizeInput,
36) => Promise<string | { summary: string; usage?: TokenUsage }>
37​
38const SUMMARY_OPEN = '<untrusted-conversation-summary>'
39const SUMMARY_CLOSE = '</untrusted-conversation-summary>'
40const DETAILS_OPEN = '<compaction-details>'
41const DETAILS_CLOSE = '</compaction-details>'
42​
43/** The content of a summary message. */
44export const summaryContent = (summary: string) =>
45 `${SUMMARY_OPEN}\n${summary}\n${SUMMARY_CLOSE}`
46​
47/** A summary text with its details in a `<compaction-details>` tag after it. */
48export const summaryBody = (summary: string, details?: string) =>
49 [summary, details ? `${DETAILS_OPEN}\n${details}\n${DETAILS_CLOSE}` : '']
50 .filter((part) => part !== '')
51 .join('\n\n')
52​
53/** The summary text and the details text of a summary body. */
54export function splitDetails(body: string): {
55 summary: string
56 details?: string
57} {
58 const start = body.indexOf(DETAILS_OPEN)
59 const end = body.indexOf(DETAILS_CLOSE, start)
60 if (start < 0 || end < 0) return { summary: body }
61 return {
62 summary:
63 `${body.slice(0, start)}${body.slice(end + DETAILS_CLOSE.length)}`.trim(),
64 details: body.slice(start + DETAILS_OPEN.length, end).trim(),
65 }
67​
68/**
69 * The summary text and the details text of an earlier summary message.
70 * `undefined` when `message` is not a summary message.
71 */
72export function readSummary(
73 message: ModelMessage | undefined,
74): { summary: string; details?: string } | undefined {
75 const content = message?.content
76 if (typeof content !== 'string' || !content.startsWith(SUMMARY_OPEN)) {
77 return undefined
78 }
79 const close = content.lastIndexOf(SUMMARY_CLOSE)
80 return splitDetails(
81 content.slice(SUMMARY_OPEN.length, close < 0 ? undefined : close).trim(),
82 )
84​
85const SECTIONS = `## Goal
86What the user wants to get done. Keep the user's exact words for each requirement.
87​
88## Constraints
89The rules, limits, and preferences that the user or the work set.
90​
91## Progress
92What is done, what is in progress, and what failed. Give the file paths, the commands, and the results.
93​
94## Key decisions
95Each decision, and the reason for it.
96​
97## Next steps
98The next actions, in order.
99​
100## Critical context
101The facts that the assistant must not lose: names, values, error messages, and open questions.`
102​
103const CHECKPOINT_PROMPT = `You write a checkpoint summary of a conversation between a user and an AI assistant. The assistant continues the work from this summary. It does not see the old messages again.
104​
105Write these sections, in this order. Write "None." in a section that has nothing.
106​
107${SECTIONS}
108​
109Be short and exact. Use only facts from the conversation. Do not answer the user. Write only the summary.`
110​
111const UPDATE_PROMPT = `You update a checkpoint summary of a conversation between a user and an AI assistant. The earlier summary is in <previous-summary>. The messages that came after it are in <conversation>. The assistant continues the work from your summary. It does not see the old messages again.
112​
113Merge the new messages into the earlier summary. Keep each fact of the earlier summary that is still true. Change each fact that the new messages changed. Move the finished items from "Next steps" to "Progress".
114​
115Write these sections, in this order. Write "None." in a section that has nothing.
116​
117${SECTIONS}
118​
119Be short and exact. Use only facts from the earlier summary and the conversation. Do not answer the user. Write only the summary.`
120​
121const TURN_PREFIX_PROMPT = `You summarize the first part of the current turn of a conversation between a user and an AI assistant. The last part of the turn stays in the context. The assistant needs your summary to finish the turn.
122​
123Write a short summary of:
124- what the user asked in this turn,
125- what the assistant did in this turn so far: the tool calls and their results,
126- the facts that the rest of the turn needs.
127​
128Be short and exact. Use only facts from the conversation. Write only the summary.`
129​
130function contentText(content: ModelMessage['content']): string {
131 if (typeof content === 'string') return content
132 return (content ?? [])
133 .map((part) => (part.type === 'text' ? part.content : `[${part.type}]`))
134 .join('\n')
136​
137/** The messages as plain text. Each tool result is cut to `maxToolResultChars`. */
138function messagesText(
139 messages: ReadonlyArray<ModelMessage>,
140 maxToolResultChars: number,
141) {
142 return messages
143 .map((message) => {
144 const text = contentText(message.content)
145 if (message.role === 'tool') {
146 const extra = text.length - maxToolResultChars
147 return `[Tool result]: ${extra > 0 ? `${text.slice(0, maxToolResultChars)} [${extra} more characters cut]` : text}`
148 }
149 const calls = (message.toolCalls ?? []).map(
150 (call) =>
151 `[Tool call ${call.function.name}]: ${call.function.arguments}`,
152 )
153 const role = message.role === 'user' ? 'User' : 'Assistant'
154 return [`[${role}]: ${text}`, ...calls].join('\n')
155 })
156 .join('\n\n')
158​
159/**
160 * A {@link Summarizer} that asks a text model for a checkpoint summary with
161 * these sections: goal, constraints, progress, key decisions, next steps, and
162 * critical context. With an earlier summary it merges the new messages into
163 * it. It returns the usage of its model call.
164 *
165 * @example
166 * ```ts
167 * summarizeOldest({ summarize: conversationSummarizer({ adapter }) })
168 * ```
169 */
170export function conversationSummarizer(options: {
171 adapter: AnyTextAdapter
172 modelOptions?: Record<string, unknown>
173 /** Each tool result is cut to this many characters in the text to summarize. Default 2000. */
174 maxToolResultChars?: number
175 /**
176 * Text added after the summary, and passed to the next compaction as
177 * previousDetails. It gets each dropped message, also the first part of a
178 * split turn.
179 */
180 details?: (input: {
181 messages: Array<ModelMessage>
182 previousDetails?: string
183 }) => string | undefined
184}): Summarizer {
185 const maxChars = options.maxToolResultChars ?? 2000
186 return async (messages, input) => {
187 const isUpdate = input.previousSummary !== undefined && !input.turnPrefix
188 // The earlier summary goes in <previous-summary>, not in the conversation.
189 const fresh =
190 isUpdate && readSummary(messages[0]) ? messages.slice(1) : messages
191 const conversation = `<conversation>\n${messagesText(fresh, maxChars)}\n</conversation>`
192 const prompt = input.turnPrefix
193 ? TURN_PREFIX_PROMPT
194 : isUpdate
195 ? UPDATE_PROMPT
196 : CHECKPOINT_PROMPT
197 // An object, so the hook below can write it and TypeScript reads it.
198 const spent: { usage?: TokenUsage } = {}
199 const countUsage: ChatMiddleware = {
200 name: 'compaction:summary-usage',
201 onUsage: (_ctx, usage) => {
202 spent.usage = sumUsage(spent.usage, usage)
203 },
204 }
205 // An aborted run must not give an empty summary, so it throws instead.
206 const throwIfAborted = () => {
207 if (!input.signal?.aborted) return
208 const reason: unknown = input.signal.reason
209 throw reason instanceof Error
210 ? reason
211 : new Error('The summary was aborted.')
212 }
213 throwIfAborted()
214 // chat() takes an AbortController, so this one follows the run's signal.
215 const controller = new AbortController()
216 const stop = () => controller.abort(input.signal?.reason)
217 input.signal?.addEventListener('abort', stop, { once: true })
218 let text: string
219 try {
220 const result = await chat({
221 adapter: options.adapter,
222 messages: [
223 {
224 role: 'user',
225 content: isUpdate
226 ? `<previous-summary>\n${input.previousSummary}\n</previous-summary>\n\n${conversation}`
227 : conversation,
228 },
229 ],
230 systemPrompts: [prompt],
231 modelOptions: options.modelOptions,
232 middleware: [countUsage],
233 abortController: controller,
234 stream: false,
235 })
236 text = result.text
237 } finally {
238 input.signal?.removeEventListener('abort', stop)
239 }
240 // chat() can return an empty text when the run is aborted.
241 throwIfAborted()
242 // The details cover each dropped message. A turn-prefix call writes them
243 // only when it gets turnPrefixMessages: then no history call runs.
244 const covered = input.turnPrefix
245 ? input.turnPrefixMessages
246 : [...fresh, ...(input.turnPrefixMessages ?? [])]
247 const details =
248 covered &&
249 options.details?.({
250 messages: covered,
251 ...(input.previousDetails !== undefined
252 ? { previousDetails: input.previousDetails }
253 : {}),
254 })
255 const summary = summaryBody(text.trim(), details)
256 return spent.usage ? { summary, usage: spent.usage } : { summary }
257 }