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

summarizer.ts

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