ds_api/conversation/summarizer.rs
1//! Conversation summarizer trait and built-in implementations.
2//!
3//! The [`AUTO_SUMMARY_TAG`][crate::raw::request::message::AUTO_SUMMARY_TAG] constant
4//! in [`Message`][crate::raw::request::message::Message] defines the single source of
5//! truth for identifying auto-generated summary messages.
6//!
7//! # Trait
8//!
9//! [`Summarizer`] is an async trait with two methods:
10//! - [`should_summarize`][Summarizer::should_summarize] — synchronous check on the current history.
11//! - [`summarize`][Summarizer::summarize] — async, may perform an API call; mutates history in-place.
12//!
13//! # Built-in implementations
14//!
15//! | Type | Strategy |
16//! |---|---|
17//! | [`LlmSummarizer`] | Calls DeepSeek to produce a semantic summary; **default** for `DeepseekAgent`. |
18//! | [`SlidingWindowSummarizer`] | Keeps the last N messages and silently drops the rest; no API call. |
19
20use std::pin::Pin;
21
22use futures::Future;
23
24use crate::api::{ApiClient, ApiRequest};
25use crate::error::ApiError;
26use crate::raw::request::message::{Message, Role};
27
28// ── Trait ────────────────────────────────────────────────────────────────────
29
30/// Decides when and how to compress conversation history.
31///
32/// Both methods receive an immutable or mutable slice of the current history.
33/// Implementors are free to count tokens, count turns, check wall-clock time,
34/// or use any other heuristic.
35///
36/// The trait is object-safe via `BoxFuture`; you can store it as
37/// `Box<dyn Summarizer>` without `async_trait`.
38///
39/// # Implementing a custom summarizer
40///
41/// ```no_run
42/// use std::pin::Pin;
43/// use ds_api::conversation::Summarizer;
44/// use ds_api::error::ApiError;
45/// use ds_api::raw::request::message::Message;
46///
47/// /// Drops all history older than `max_turns` turns. No API call needed.
48/// struct TurnLimitSummarizer { max_turns: usize }
49///
50/// impl Summarizer for TurnLimitSummarizer {
51/// fn should_summarize(&self, history: &[Message]) -> bool {
52/// history.len() > self.max_turns
53/// }
54///
55/// fn summarize<'a>(
56/// &'a self,
57/// history: &'a mut Vec<Message>,
58/// ) -> Pin<Box<dyn std::future::Future<Output = Result<(), ApiError>> + Send + 'a>> {
59/// Box::pin(async move {
60/// if history.len() > self.max_turns {
61/// let drop_count = history.len() - self.max_turns;
62/// history.drain(0..drop_count);
63/// }
64/// Ok(())
65/// })
66/// }
67/// }
68///
69/// // Use it with an agent:
70/// use ds_api::DeepseekAgent;
71/// let agent = DeepseekAgent::new("sk-...")
72/// .with_summarizer(TurnLimitSummarizer { max_turns: 20 });
73/// ```
74pub trait Summarizer: Send + Sync {
75 /// Return `true` if the history should be summarized before the next API turn.
76 ///
77 /// This is called synchronously on every user-input push; keep it cheap.
78 fn should_summarize(&self, history: &[Message]) -> bool;
79
80 /// Compress `history` in-place, returning an error only for unrecoverable failures.
81 ///
82 /// On success the history must be shorter (or at most the same length) than before.
83 /// Implementations must **not** remove messages whose role is [`Role::System`] and
84 /// whose `name` field is not `Some("[auto-summary]")` — those are user-provided
85 /// system prompts and must be preserved.
86 fn summarize<'a>(
87 &'a self,
88 history: &'a mut Vec<Message>,
89 ) -> Pin<Box<dyn Future<Output = Result<(), ApiError>> + Send + 'a>>;
90}
91
92// ── Helpers ───────────────────────────────────────────────────────────────────
93
94/// Estimate the token count of a slice of messages using a fast character heuristic.
95///
96/// ASCII characters count as 1 char ≈ 0.25 tokens; CJK / multibyte characters are
97/// counted as 4 chars ≈ 1 token. System messages whose `name` is `[auto-summary]`
98/// are included in the estimate; other system messages (user-provided prompts) are
99/// excluded because they are permanent and we cannot remove them anyway.
100pub(crate) fn estimate_tokens(history: &[Message]) -> usize {
101 history
102 .iter()
103 .filter(|m| {
104 // Always exclude permanent system prompts from the token estimate;
105 // we can't remove them so counting them would trigger summarization
106 // that can never actually free those tokens.
107 if matches!(m.role, Role::System) {
108 // auto-summary placeholders are replaceable → count them
109 m.is_auto_summary()
110 } else {
111 true
112 }
113 })
114 .filter_map(|m| m.content.as_deref())
115 .map(|s| {
116 s.chars()
117 .map(|c| if c.is_ascii() { 1usize } else { 4 })
118 .sum::<usize>()
119 })
120 .sum::<usize>()
121 / 4
122}
123
124/// Partition `history` into (system_prompts, rest), where system prompts are
125/// permanent user-provided system messages (role=System, name≠"[auto-summary]").
126///
127/// Returns the indices of permanent system messages so callers can re-inject
128/// them after compressing the rest.
129fn extract_system_prompts(history: &mut Vec<Message>) -> Vec<Message> {
130 let mut prompts = Vec::new();
131 let mut i = 0;
132 while i < history.len() {
133 let m = &history[i];
134 let is_permanent_system = matches!(m.role, Role::System) && !m.is_auto_summary();
135 if is_permanent_system {
136 prompts.push(history.remove(i));
137 // don't increment i — the next element shifted into position i
138 } else {
139 i += 1;
140 }
141 }
142 prompts
143}
144
145// ── LlmSummarizer ─────────────────────────────────────────────────────────────
146
147/// Summarizes older conversation turns by asking DeepSeek to write a concise
148/// prose summary, then replaces the compressed turns with a single
149/// `Role::System` message containing that summary.
150///
151/// # Trigger
152///
153/// Fires when the estimated token count of the **compressible** portion of the
154/// history (everything except permanent system prompts) exceeds `token_threshold`.
155///
156/// # Behavior
157///
158/// 1. Permanent `Role::System` messages (user-provided via `with_system_prompt`)
159/// are extracted and re-prepended after summarization — they are never lost.
160/// 2. Any previous `[auto-summary]` system message is included in the text sent
161/// to the model so the new summary is cumulative.
162/// 3. The `retain_last` most recent non-system turns are kept verbatim; everything
163/// older is replaced by the LLM-generated summary.
164/// 4. If the API call fails the history is left **unchanged** and the error is
165/// returned so the caller can decide whether to abort or continue.
166///
167/// # Example
168///
169/// ```no_run
170/// use ds_api::{DeepseekAgent, ApiClient};
171/// use ds_api::conversation::LlmSummarizer;
172///
173/// let summarizer = LlmSummarizer::new(ApiClient::new("sk-..."));
174/// let agent = DeepseekAgent::new("sk-...")
175/// .with_summarizer(summarizer);
176/// ```
177#[derive(Clone)]
178pub struct LlmSummarizer {
179 /// Client used exclusively for summary API calls (can share the agent's token).
180 client: ApiClient,
181 /// Estimated token count above which summarization is triggered.
182 pub(crate) token_threshold: usize,
183 /// Number of most-recent non-system messages to retain verbatim.
184 pub(crate) retain_last: usize,
185}
186
187impl LlmSummarizer {
188 /// Create with default thresholds: trigger at ~60 000 tokens, retain last 10 turns.
189 pub fn new(client: ApiClient) -> Self {
190 Self {
191 client,
192 token_threshold: 60_000,
193 retain_last: 10,
194 }
195 }
196
197 /// Builder: set a custom token threshold.
198 pub fn token_threshold(mut self, n: usize) -> Self {
199 self.token_threshold = n;
200 self
201 }
202
203 /// Builder: set how many recent messages to keep verbatim.
204 pub fn retain_last(mut self, n: usize) -> Self {
205 self.retain_last = n;
206 self
207 }
208}
209
210impl Summarizer for LlmSummarizer {
211 fn should_summarize(&self, history: &[Message]) -> bool {
212 estimate_tokens(history) >= self.token_threshold
213 }
214
215 fn summarize<'a>(
216 &'a self,
217 history: &'a mut Vec<Message>,
218 ) -> Pin<Box<dyn Future<Output = Result<(), ApiError>> + Send + 'a>> {
219 Box::pin(async move {
220 // ── 1. Extract permanent system prompts ──────────────────────────
221 let system_prompts = extract_system_prompts(history);
222
223 // ── 2. Split off the tail we want to keep verbatim ───────────────
224 let retain = self.retain_last.min(history.len());
225 let split = history.len().saturating_sub(retain);
226 let tail: Vec<Message> = history.drain(split..).collect();
227
228 // history now contains only the "old" turns (including any previous
229 // [auto-summary] message).
230
231 if history.is_empty() {
232 // Nothing old enough to summarize — just restore everything.
233 history.extend(tail);
234 // re-prepend system prompts
235 for (i, p) in system_prompts.into_iter().enumerate() {
236 history.insert(i, p);
237 }
238 return Ok(());
239 }
240
241 // ── 3. Build a prompt asking the model for a summary ─────────────
242 //
243 // We format the old turns as a readable transcript and ask for a
244 // concise summary that preserves the most important facts and decisions.
245 let mut transcript = String::new();
246 for msg in &*history {
247 // skip the old auto-summary header line if present — the content
248 // itself is still useful context for the new summary
249 let role_label = match msg.role {
250 Role::User => "User",
251 Role::Assistant => "Assistant",
252 Role::System => "System",
253 Role::Tool => "Tool",
254 };
255 if let Some(content) = &msg.content {
256 transcript.push_str(&format!("{role_label}: {content}\n"));
257 }
258 }
259
260 let summarize_prompt = format!(
261 "Below is a conversation transcript. Write a concise summary (a few sentences \
262 to a short paragraph) that captures the key context, decisions, and facts \
263 established so far. The summary will replace the original transcript and be \
264 read by the same AI assistant as a memory aid — be precise and neutral.\n\n\
265 Transcript:\n{transcript}"
266 );
267
268 let req = ApiRequest::builder()
269 .add_message(Message::new(Role::User, &summarize_prompt))
270 .max_tokens(512);
271
272 let response = self.client.send(req).await?;
273
274 let summary_text = response
275 .choices
276 .into_iter()
277 .next()
278 .and_then(|c| c.message.content)
279 .unwrap_or_else(|| transcript.clone());
280
281 // ── 4. Replace old turns with the summary message ────────────────
282 history.clear();
283
284 history.push(Message::auto_summary(format!(
285 "Summary of the conversation so far:\n{summary_text}"
286 )));
287
288 // ── 5. Re-attach the verbatim tail and system prompts ────────────
289 history.extend(tail);
290
291 for (i, p) in system_prompts.into_iter().enumerate() {
292 history.insert(i, p);
293 }
294
295 Ok(())
296 })
297 }
298}
299
300// ── SlidingWindowSummarizer ───────────────────────────────────────────────────
301
302/// Keeps only the most recent `window` messages and silently discards everything
303/// older. No API call is made.
304///
305/// Use this when you want predictable, zero-cost context management and are
306/// comfortable with the model losing access to earlier turns.
307///
308/// Permanent `Role::System` messages are always preserved regardless of `window`.
309///
310/// # Example
311///
312/// ```no_run
313/// use ds_api::DeepseekAgent;
314/// use ds_api::conversation::SlidingWindowSummarizer;
315///
316/// // Keep the last 20 non-system messages; trigger summarization above 30.
317/// let agent = DeepseekAgent::new("sk-...")
318/// .with_summarizer(
319/// SlidingWindowSummarizer::new(20)
320/// .trigger_at(30)
321/// );
322/// ```
323#[derive(Debug, Clone)]
324pub struct SlidingWindowSummarizer {
325 /// Maximum number of non-system messages to retain after summarization.
326 pub(crate) window: usize,
327 /// Number of non-system messages above which summarization is triggered.
328 /// Defaults to `window + 1` (trigger as soon as the window is exceeded by one).
329 pub(crate) trigger_at: Option<usize>,
330}
331
332impl SlidingWindowSummarizer {
333 /// Create a summarizer that retains at most `window` non-system messages.
334 ///
335 /// Summarization triggers as soon as the non-system message count exceeds
336 /// `window`. Use [`trigger_at`][Self::trigger_at] to set a larger trigger
337 /// threshold so the window only slides after a certain amount of growth.
338 pub fn new(window: usize) -> Self {
339 Self {
340 window,
341 trigger_at: None,
342 }
343 }
344
345 /// Builder: set the non-system message count that triggers summarization.
346 ///
347 /// Must be greater than `window`; if set to a value ≤ `window` it is
348 /// silently clamped to `window + 1`.
349 ///
350 /// # Example
351 ///
352 /// ```no_run
353 /// use ds_api::conversation::SlidingWindowSummarizer;
354 ///
355 /// // Retain 20 turns but only start trimming after reaching 40.
356 /// let s = SlidingWindowSummarizer::new(20).trigger_at(40);
357 /// ```
358 pub fn trigger_at(mut self, n: usize) -> Self {
359 self.trigger_at = Some(n.max(self.window + 1));
360 self
361 }
362}
363
364impl Summarizer for SlidingWindowSummarizer {
365 fn should_summarize(&self, history: &[Message]) -> bool {
366 let non_system = history
367 .iter()
368 .filter(|m| !matches!(m.role, Role::System))
369 .count();
370 let threshold = self.trigger_at.unwrap_or(self.window + 1);
371 non_system >= threshold
372 }
373
374 fn summarize<'a>(
375 &'a self,
376 history: &'a mut Vec<Message>,
377 ) -> Pin<Box<dyn Future<Output = Result<(), ApiError>> + Send + 'a>> {
378 Box::pin(async move {
379 // Extract and preserve permanent system prompts.
380 let system_prompts = extract_system_prompts(history);
381
382 // Remove any previous auto-summary messages — they're irrelevant
383 // for a pure sliding window.
384 history.retain(|m| !m.is_auto_summary());
385
386 // Keep only the last `window` non-system messages.
387 if history.len() > self.window {
388 let drop = history.len() - self.window;
389 history.drain(0..drop);
390 }
391
392 // Re-prepend the permanent system prompts at the front.
393 for (i, p) in system_prompts.into_iter().enumerate() {
394 history.insert(i, p);
395 }
396
397 Ok(())
398 })
399 }
400}
401
402// ── Tests ─────────────────────────────────────────────────────────────────────
403
404#[cfg(test)]
405mod tests {
406 use super::*;
407
408 fn msg(role: Role, text: &str) -> Message {
409 Message::new(role, text)
410 }
411
412 fn system_prompt(text: &str) -> Message {
413 // A permanent system prompt — no [auto-summary] name tag.
414 Message::new(Role::System, text)
415 }
416
417 // ── estimate_tokens ───────────────────────────────────────────────────────
418
419 #[test]
420 fn estimate_tokens_excludes_permanent_system() {
421 let history = vec![
422 system_prompt("You are a helpful assistant."),
423 msg(Role::User, "Hello"), // 5 chars → 1 token
424 msg(Role::Assistant, "Hi there"), // 8 chars → 2 tokens
425 ];
426 // Only the User + Assistant messages should contribute.
427 let est = estimate_tokens(&history);
428 assert!(est > 0);
429 // "Hello" + "Hi there" = 13 chars / 4 = 3 tokens
430 assert_eq!(est, 3);
431 }
432
433 #[test]
434 fn estimate_tokens_includes_auto_summary() {
435 let summary = Message::auto_summary("Some prior summary text.");
436
437 let history = vec![summary];
438 let est = estimate_tokens(&history);
439 assert!(est > 0);
440 }
441
442 // ── SlidingWindowSummarizer ───────────────────────────────────────────────
443
444 #[tokio::test]
445 async fn sliding_window_trims_to_window() {
446 let mut history = vec![
447 system_prompt("system"),
448 msg(Role::User, "a"),
449 msg(Role::Assistant, "b"),
450 msg(Role::User, "c"),
451 msg(Role::Assistant, "d"),
452 msg(Role::User, "e"),
453 ];
454
455 let s = SlidingWindowSummarizer::new(2);
456 assert!(s.should_summarize(&history));
457 s.summarize(&mut history).await.unwrap();
458
459 // system prompt preserved
460 assert!(
461 history
462 .iter()
463 .any(|m| matches!(m.role, Role::System) && m.content.as_deref() == Some("system"))
464 );
465
466 // at most window non-system messages remain
467 let non_sys: Vec<_> = history
468 .iter()
469 .filter(|m| !matches!(m.role, Role::System))
470 .collect();
471 assert_eq!(non_sys.len(), 2);
472
473 // the retained messages are the most recent ones
474 assert_eq!(non_sys[0].content.as_deref(), Some("d"));
475 assert_eq!(non_sys[1].content.as_deref(), Some("e"));
476 }
477
478 #[tokio::test]
479 async fn sliding_window_preserves_multiple_system_prompts() {
480 let mut p1 = system_prompt("prompt one");
481 let mut p2 = system_prompt("prompt two");
482 // Give them something to distinguish them from auto-summary
483 p1.name = None;
484 p2.name = None;
485
486 let mut history = vec![
487 p1.clone(),
488 p2.clone(),
489 msg(Role::User, "1"),
490 msg(Role::User, "2"),
491 msg(Role::User, "3"),
492 ];
493
494 let s = SlidingWindowSummarizer::new(1);
495 s.summarize(&mut history).await.unwrap();
496
497 let sys_msgs: Vec<_> = history
498 .iter()
499 .filter(|m| matches!(m.role, Role::System))
500 .collect();
501 assert_eq!(sys_msgs.len(), 2);
502 assert_eq!(sys_msgs[0].content.as_deref(), Some("prompt one"));
503 assert_eq!(sys_msgs[1].content.as_deref(), Some("prompt two"));
504 }
505
506 #[tokio::test]
507 async fn sliding_window_removes_old_auto_summary() {
508 let auto = Message::auto_summary("old summary");
509
510 let mut history = vec![
511 system_prompt("permanent"),
512 auto,
513 msg(Role::User, "a"),
514 msg(Role::User, "b"),
515 msg(Role::User, "c"),
516 ];
517
518 let s = SlidingWindowSummarizer::new(2);
519 s.summarize(&mut history).await.unwrap();
520
521 // old auto-summary should be gone
522 assert!(!history.iter().any(|m| m.is_auto_summary()));
523
524 // permanent system prompt preserved
525 assert!(
526 history
527 .iter()
528 .any(|m| m.content.as_deref() == Some("permanent"))
529 );
530 }
531
532 #[tokio::test]
533 async fn sliding_window_noop_when_within_window() {
534 let mut history = vec![msg(Role::User, "a"), msg(Role::Assistant, "b")];
535
536 let s = SlidingWindowSummarizer::new(4);
537 assert!(!s.should_summarize(&history));
538 s.summarize(&mut history).await.unwrap();
539 assert_eq!(history.len(), 2);
540 }
541
542 // ── should_summarize ─────────────────────────────────────────────────────
543
544 #[test]
545 fn should_summarize_triggers_at_window_exceeded() {
546 let history = vec![
547 msg(Role::User, "a"),
548 msg(Role::User, "b"),
549 msg(Role::User, "c"),
550 ];
551 let s = SlidingWindowSummarizer::new(2);
552 assert!(s.should_summarize(&history));
553
554 let short = vec![msg(Role::User, "only")];
555 assert!(!s.should_summarize(&short));
556 }
557}