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

summarizer.ts

270 lines10.2 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 /**
190 * Middleware for the summary model call, for example a cost ledger or a
191 * trace. It runs after the summarizer's own usage count.
192 */
193 middleware?: ReadonlyArray<ChatMiddleware>
194}): Summarizer {
195 const maxChars = options.maxToolResultChars ?? 2000
196 return async (messages, input) => {
197 const isUpdate = input.previousSummary !== undefined && !input.turnPrefix
198 // The earlier summary goes in <previous-summary>, not in the conversation.
199 const fresh =
200 isUpdate && readSummary(messages[0]) ? messages.slice(1) : messages
201 const conversation = `<conversation>\n${messagesText(fresh, maxChars)}\n</conversation>`
202 const prompt = input.turnPrefix
203 ? TURN_PREFIX_PROMPT
204 : isUpdate
205 ? UPDATE_PROMPT
206 : CHECKPOINT_PROMPT
207 // An object, so the hook below can write it and TypeScript reads it.
208 const spent: { usage?: TokenUsage } = {}
209 const countUsage: ChatMiddleware = {
210 name: 'compaction:summary-usage',
211 onUsage: (_ctx, usage) => {
212 spent.usage = sumUsage(spent.usage, usage)
213 },
214 }
215 // An aborted run must not give an empty summary, so it throws instead.
216 const throwIfAborted = () => {
217 if (!input.signal?.aborted) return
218 const reason: unknown = input.signal.reason
219 throw reason instanceof Error
220 ? reason
221 : new Error('The summary was aborted.')
222 }
223 throwIfAborted()
224 // chat() takes an AbortController, so this one follows the run's signal.
225 const controller = new AbortController()
226 const stop = () => controller.abort(input.signal?.reason)
227 input.signal?.addEventListener('abort', stop, { once: true })
228 let text: string
229 try {
230 const result = await chat({
231 adapter: options.adapter,
232 messages: [
233 {
234 role: 'user',
235 content: isUpdate
236 ? `<previous-summary>\n${input.previousSummary}\n</previous-summary>\n\n${conversation}`
237 : conversation,
238 },
239 ],
240 systemPrompts: [prompt],
241 modelOptions: options.modelOptions,
242 middleware: [countUsage, ...(options.middleware ?? [])],
243 abortController: controller,
244 // A thread of its own: the summary call is not a turn of the conversation.
245 threadId: `${input.threadId}:compaction`,
246 stream: false,
247 })
248 text = result.text
249 } finally {
250 input.signal?.removeEventListener('abort', stop)
251 }
252 // chat() can return an empty text when the run is aborted.
253 throwIfAborted()
254 // The details cover each dropped message. A turn-prefix call writes them
255 // only when it gets turnPrefixMessages: then no history call runs.
256 const covered = input.turnPrefix
257 ? input.turnPrefixMessages
258 : [...fresh, ...(input.turnPrefixMessages ?? [])]
259 const details =
260 covered &&
261 options.details?.({
262 messages: covered,
263 ...(input.previousDetails !== undefined
264 ? { previousDetails: input.previousDetails }
265 : {}),
266 })
267 const summary = summaryBody(text.trim(), details)
268 return spent.usage ? { summary, usage: spent.usage } : { summary }
269 }