Skip to main content

oxirs_chat/
context_window.rs

1//! Context window management for LLM interactions.
2//!
3//! Provides token counting, sliding window, priority-based truncation,
4//! context compression, message importance scoring, reserved space management,
5//! overflow detection, and multi-turn conversation windowing.
6
7use std::collections::VecDeque;
8
9// ---------------------------------------------------------------------------
10// Public types
11// ---------------------------------------------------------------------------
12
13/// Role of a message in the conversation.
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
15pub enum Role {
16    /// System instruction (highest priority).
17    System,
18    /// User message.
19    User,
20    /// Assistant response.
21    Assistant,
22    /// Tool/function result.
23    Tool,
24}
25
26impl Role {
27    /// Default importance weight for this role.
28    pub fn default_importance(&self) -> f64 {
29        match self {
30            Role::System => 1.0,
31            Role::User => 0.8,
32            Role::Tool => 0.6,
33            Role::Assistant => 0.5,
34        }
35    }
36}
37
38/// A message in the context window.
39#[derive(Debug, Clone)]
40pub struct ContextMessage {
41    /// Role of the sender.
42    pub role: Role,
43    /// Text content.
44    pub content: String,
45    /// Estimated token count.
46    pub token_count: usize,
47    /// Turn number (0-based).
48    pub turn: usize,
49    /// Whether this message is pinned (never truncated).
50    pub pinned: bool,
51}
52
53impl ContextMessage {
54    /// Create a new message with auto-estimated token count.
55    pub fn new(role: Role, content: impl Into<String>, turn: usize) -> Self {
56        let content = content.into();
57        let token_count = estimate_tokens(&content);
58        Self {
59            role,
60            content,
61            token_count,
62            turn,
63            pinned: false,
64        }
65    }
66
67    /// Create a pinned message (will not be truncated).
68    pub fn pinned(role: Role, content: impl Into<String>, turn: usize) -> Self {
69        let mut msg = Self::new(role, content, turn);
70        msg.pinned = true;
71        msg
72    }
73
74    /// Importance score: role weight * recency bonus.
75    pub fn importance(&self, max_turn: usize) -> f64 {
76        let role_weight = self.role.default_importance();
77        let recency = if max_turn == 0 {
78            1.0
79        } else {
80            0.5 + 0.5 * (self.turn as f64 / max_turn as f64)
81        };
82        role_weight * recency
83    }
84}
85
86/// Configuration for the context window manager.
87#[derive(Debug, Clone)]
88pub struct WindowConfig {
89    /// Maximum number of tokens allowed in the context.
90    pub max_tokens: usize,
91    /// Tokens reserved for the model's response.
92    pub reserved_for_response: usize,
93    /// Truncation strategy when the window overflows.
94    pub truncation_strategy: TruncationStrategy,
95}
96
97impl Default for WindowConfig {
98    fn default() -> Self {
99        Self {
100            max_tokens: 4096,
101            reserved_for_response: 512,
102            truncation_strategy: TruncationStrategy::SlidingWindow,
103        }
104    }
105}
106
107/// Strategy for truncating messages when the context overflows.
108#[derive(Debug, Clone, Copy, PartialEq, Eq)]
109pub enum TruncationStrategy {
110    /// Drop oldest messages first (sliding window).
111    SlidingWindow,
112    /// Drop lowest-importance messages first.
113    PriorityBased,
114    /// Compress old messages into a summary.
115    Compress,
116}
117
118/// Summary produced by context compression.
119#[derive(Debug, Clone)]
120pub struct ContextSummary {
121    /// Compressed text.
122    pub text: String,
123    /// Estimated token count of the summary.
124    pub token_count: usize,
125    /// Number of original messages that were compressed.
126    pub messages_compressed: usize,
127    /// Total tokens of the original messages.
128    pub original_tokens: usize,
129}
130
131/// Snapshot of the current window state.
132#[derive(Debug, Clone)]
133pub struct WindowState {
134    /// Current total token usage (excluding reserved).
135    pub total_tokens: usize,
136    /// Available tokens (max - reserved - current).
137    pub available_tokens: usize,
138    /// Number of messages in the window.
139    pub message_count: usize,
140    /// Whether the window is overflowing.
141    pub is_overflowing: bool,
142    /// Fill ratio [0, 1].
143    pub fill_ratio: f64,
144}
145
146// ---------------------------------------------------------------------------
147// ContextWindow
148// ---------------------------------------------------------------------------
149
150/// Context window manager for LLM interactions.
151pub struct ContextWindow {
152    config: WindowConfig,
153    messages: VecDeque<ContextMessage>,
154    summaries: Vec<ContextSummary>,
155    next_turn: usize,
156}
157
158impl ContextWindow {
159    /// Create a new context window with the given configuration.
160    pub fn new(config: WindowConfig) -> Self {
161        Self {
162            config,
163            messages: VecDeque::new(),
164            summaries: Vec::new(),
165            next_turn: 0,
166        }
167    }
168
169    /// Add a message to the context window.
170    ///
171    /// If the window overflows after adding, the configured truncation strategy
172    /// is applied automatically.
173    pub fn add_message(&mut self, role: Role, content: impl Into<String>) {
174        let msg = ContextMessage::new(role, content, self.next_turn);
175        self.next_turn += 1;
176        self.messages.push_back(msg);
177
178        if self.is_overflowing() {
179            self.apply_truncation();
180        }
181    }
182
183    /// Add a pinned message that will never be truncated.
184    pub fn add_pinned(&mut self, role: Role, content: impl Into<String>) {
185        let msg = ContextMessage::pinned(role, content, self.next_turn);
186        self.next_turn += 1;
187        self.messages.push_back(msg);
188    }
189
190    /// Current total tokens used by messages + summaries.
191    pub fn total_tokens(&self) -> usize {
192        let msg_tokens: usize = self.messages.iter().map(|m| m.token_count).sum();
193        let summary_tokens: usize = self.summaries.iter().map(|s| s.token_count).sum();
194        msg_tokens + summary_tokens
195    }
196
197    /// Available tokens for new content (excluding reserved space).
198    pub fn available_tokens(&self) -> usize {
199        let usable = self
200            .config
201            .max_tokens
202            .saturating_sub(self.config.reserved_for_response);
203        usable.saturating_sub(self.total_tokens())
204    }
205
206    /// Whether the current context exceeds the available budget.
207    pub fn is_overflowing(&self) -> bool {
208        let usable = self
209            .config
210            .max_tokens
211            .saturating_sub(self.config.reserved_for_response);
212        self.total_tokens() > usable
213    }
214
215    /// Fill ratio [0, 1] of the usable token budget.
216    pub fn fill_ratio(&self) -> f64 {
217        let usable = self
218            .config
219            .max_tokens
220            .saturating_sub(self.config.reserved_for_response) as f64;
221        if usable == 0.0 {
222            return 1.0;
223        }
224        (self.total_tokens() as f64 / usable).min(1.0)
225    }
226
227    /// Get a snapshot of the current window state.
228    pub fn state(&self) -> WindowState {
229        WindowState {
230            total_tokens: self.total_tokens(),
231            available_tokens: self.available_tokens(),
232            message_count: self.messages.len(),
233            is_overflowing: self.is_overflowing(),
234            fill_ratio: self.fill_ratio(),
235        }
236    }
237
238    /// Number of messages currently in the window.
239    pub fn message_count(&self) -> usize {
240        self.messages.len()
241    }
242
243    /// Access messages as a slice (deque iteration).
244    pub fn messages(&self) -> impl Iterator<Item = &ContextMessage> {
245        self.messages.iter()
246    }
247
248    /// Access summaries.
249    pub fn summaries(&self) -> &[ContextSummary] {
250        &self.summaries
251    }
252
253    /// Build the final context string for sending to the LLM.
254    pub fn build_context(&self) -> String {
255        let mut parts: Vec<String> = Vec::new();
256
257        // Summaries first (compressed history).
258        for summary in &self.summaries {
259            parts.push(format!("[Summary] {}", summary.text));
260        }
261
262        // Then messages in order.
263        for msg in &self.messages {
264            let role_str = match msg.role {
265                Role::System => "system",
266                Role::User => "user",
267                Role::Assistant => "assistant",
268                Role::Tool => "tool",
269            };
270            parts.push(format!("[{}] {}", role_str, msg.content));
271        }
272
273        parts.join("\n")
274    }
275
276    /// Manually trigger truncation.
277    pub fn truncate(&mut self) {
278        self.apply_truncation();
279    }
280
281    /// Clear all messages and summaries.
282    pub fn clear(&mut self) {
283        self.messages.clear();
284        self.summaries.clear();
285        self.next_turn = 0;
286    }
287
288    /// Return the current configuration.
289    pub fn config(&self) -> &WindowConfig {
290        &self.config
291    }
292
293    // --- private helpers ---
294
295    fn apply_truncation(&mut self) {
296        match self.config.truncation_strategy {
297            TruncationStrategy::SlidingWindow => self.truncate_sliding(),
298            TruncationStrategy::PriorityBased => self.truncate_priority(),
299            TruncationStrategy::Compress => self.truncate_compress(),
300        }
301    }
302
303    /// Drop oldest non-pinned messages until within budget.
304    fn truncate_sliding(&mut self) {
305        while self.is_overflowing() && !self.messages.is_empty() {
306            // Find the first non-pinned message from the front.
307            let idx = self.messages.iter().position(|m| !m.pinned);
308            match idx {
309                Some(i) => {
310                    self.messages.remove(i);
311                }
312                None => break, // all pinned, cannot truncate
313            }
314        }
315    }
316
317    /// Drop lowest-importance non-pinned messages until within budget.
318    fn truncate_priority(&mut self) {
319        let max_turn = self.next_turn.saturating_sub(1);
320
321        while self.is_overflowing() && !self.messages.is_empty() {
322            // Find the non-pinned message with lowest importance.
323            let mut min_idx: Option<usize> = None;
324            let mut min_importance = f64::MAX;
325
326            for (i, msg) in self.messages.iter().enumerate() {
327                if msg.pinned {
328                    continue;
329                }
330                let imp = msg.importance(max_turn);
331                if imp < min_importance {
332                    min_importance = imp;
333                    min_idx = Some(i);
334                }
335            }
336
337            match min_idx {
338                Some(i) => {
339                    self.messages.remove(i);
340                }
341                None => break,
342            }
343        }
344    }
345
346    /// Compress the oldest half of non-pinned messages into a summary.
347    fn truncate_compress(&mut self) {
348        // Gather non-pinned messages from the front.
349        let total_non_pinned = self.messages.iter().filter(|m| !m.pinned).count();
350        if total_non_pinned <= 1 {
351            // Fall back to sliding if nothing to compress.
352            self.truncate_sliding();
353            return;
354        }
355
356        let to_compress = total_non_pinned / 2;
357        let mut compressed_texts: Vec<String> = Vec::new();
358        let mut compressed_tokens: usize = 0;
359        let mut compressed_count: usize = 0;
360        let mut indices_to_remove: Vec<usize> = Vec::new();
361
362        for (i, msg) in self.messages.iter().enumerate() {
363            if compressed_count >= to_compress {
364                break;
365            }
366            if !msg.pinned {
367                compressed_texts.push(msg.content.clone());
368                compressed_tokens += msg.token_count;
369                compressed_count += 1;
370                indices_to_remove.push(i);
371            }
372        }
373
374        // Remove in reverse order to preserve indices.
375        for &i in indices_to_remove.iter().rev() {
376            self.messages.remove(i);
377        }
378
379        if !compressed_texts.is_empty() {
380            // Build a simple summary (in production this would call an LLM).
381            let summary_text = format!(
382                "Previous conversation ({} messages): {}",
383                compressed_count,
384                compressed_texts.join(" | ")
385            );
386            let summary_token_count = estimate_tokens(&summary_text);
387
388            self.summaries.push(ContextSummary {
389                text: summary_text,
390                token_count: summary_token_count,
391                messages_compressed: compressed_count,
392                original_tokens: compressed_tokens,
393            });
394        }
395    }
396}
397
398// ---------------------------------------------------------------------------
399// Free functions
400// ---------------------------------------------------------------------------
401
402/// Approximate token count: ~4 characters per token (GPT-style heuristic).
403pub fn estimate_tokens(text: &str) -> usize {
404    let chars = text.len();
405    // Rough estimate: 1 token per 4 characters, minimum 1 token for non-empty.
406    if chars == 0 {
407        0
408    } else {
409        (chars / 4).max(1)
410    }
411}
412
413/// Estimate tokens for a list of strings.
414pub fn estimate_tokens_batch(texts: &[&str]) -> Vec<usize> {
415    texts.iter().map(|t| estimate_tokens(t)).collect()
416}
417
418// ---------------------------------------------------------------------------
419// Tests
420// ---------------------------------------------------------------------------
421
422#[cfg(test)]
423mod tests {
424    use super::*;
425
426    fn default_window() -> ContextWindow {
427        ContextWindow::new(WindowConfig::default())
428    }
429
430    fn small_window() -> ContextWindow {
431        ContextWindow::new(WindowConfig {
432            max_tokens: 100,
433            reserved_for_response: 20,
434            truncation_strategy: TruncationStrategy::SlidingWindow,
435        })
436    }
437
438    fn priority_window() -> ContextWindow {
439        ContextWindow::new(WindowConfig {
440            max_tokens: 100,
441            reserved_for_response: 20,
442            truncation_strategy: TruncationStrategy::PriorityBased,
443        })
444    }
445
446    fn compress_window() -> ContextWindow {
447        ContextWindow::new(WindowConfig {
448            max_tokens: 100,
449            reserved_for_response: 20,
450            truncation_strategy: TruncationStrategy::Compress,
451        })
452    }
453
454    // --- estimate_tokens ---
455
456    #[test]
457    fn test_estimate_tokens_empty() {
458        assert_eq!(estimate_tokens(""), 0);
459    }
460
461    #[test]
462    fn test_estimate_tokens_short() {
463        // "Hi" = 2 chars → max(2/4, 1) = 1
464        assert_eq!(estimate_tokens("Hi"), 1);
465    }
466
467    #[test]
468    fn test_estimate_tokens_longer() {
469        // 20 chars → 5 tokens
470        let text = "a]".repeat(10); // 20 chars
471        assert_eq!(estimate_tokens(&text), 5);
472    }
473
474    #[test]
475    fn test_estimate_tokens_batch_length() {
476        let result = estimate_tokens_batch(&["hello", "world", "foo"]);
477        assert_eq!(result.len(), 3);
478    }
479
480    // --- Role importance ---
481
482    #[test]
483    fn test_system_highest_importance() {
484        assert!(Role::System.default_importance() > Role::User.default_importance());
485        assert!(Role::System.default_importance() > Role::Assistant.default_importance());
486    }
487
488    #[test]
489    fn test_user_higher_than_assistant() {
490        assert!(Role::User.default_importance() > Role::Assistant.default_importance());
491    }
492
493    // --- ContextMessage ---
494
495    #[test]
496    fn test_message_auto_token_count() {
497        let msg = ContextMessage::new(Role::User, "Hello world, this is a test!", 0);
498        assert!(msg.token_count > 0);
499    }
500
501    #[test]
502    fn test_pinned_message_flag() {
503        let msg = ContextMessage::pinned(Role::System, "You are a helpful assistant.", 0);
504        assert!(msg.pinned);
505    }
506
507    #[test]
508    fn test_message_importance_increases_with_turn() {
509        let early = ContextMessage::new(Role::User, "early", 0);
510        let late = ContextMessage::new(Role::User, "late", 10);
511        assert!(late.importance(10) > early.importance(10));
512    }
513
514    #[test]
515    fn test_message_importance_system_higher_than_assistant() {
516        let sys = ContextMessage::new(Role::System, "sys", 5);
517        let asst = ContextMessage::new(Role::Assistant, "asst", 5);
518        assert!(sys.importance(10) > asst.importance(10));
519    }
520
521    // --- ContextWindow basics ---
522
523    #[test]
524    fn test_empty_window_state() {
525        let w = default_window();
526        assert_eq!(w.total_tokens(), 0);
527        assert_eq!(w.message_count(), 0);
528        assert!(!w.is_overflowing());
529    }
530
531    #[test]
532    fn test_add_message_increments_count() {
533        let mut w = default_window();
534        w.add_message(Role::User, "Hello");
535        assert_eq!(w.message_count(), 1);
536    }
537
538    #[test]
539    fn test_add_message_increases_tokens() {
540        let mut w = default_window();
541        w.add_message(Role::User, "Hello there");
542        assert!(w.total_tokens() > 0);
543    }
544
545    #[test]
546    fn test_clear_resets_window() {
547        let mut w = default_window();
548        w.add_message(Role::User, "test");
549        w.clear();
550        assert_eq!(w.total_tokens(), 0);
551        assert_eq!(w.message_count(), 0);
552    }
553
554    // --- overflow detection ---
555
556    #[test]
557    fn test_overflow_detected() {
558        let mut w = small_window(); // max=100, reserved=20, usable=80
559                                    // Add enough tokens to exceed 80
560        for _ in 0..50 {
561            w.add_message(
562                Role::User,
563                "This is a somewhat long message for testing overflow detection.",
564            );
565        }
566        // After truncation, it should no longer overflow (sliding window)
567        assert!(!w.is_overflowing());
568    }
569
570    #[test]
571    fn test_available_tokens_decreases() {
572        let mut w = small_window();
573        let before = w.available_tokens();
574        w.add_message(Role::User, "Some content here");
575        let after = w.available_tokens();
576        assert!(after < before);
577    }
578
579    // --- sliding window truncation ---
580
581    #[test]
582    fn test_sliding_window_removes_oldest() {
583        let mut w = small_window();
584        w.add_message(Role::User, "First message with some content");
585        w.add_message(Role::User, "Second message with some content");
586        // Add many to trigger overflow
587        for i in 0..30 {
588            w.add_message(Role::User, format!("Message number {} with content", i));
589        }
590        // After truncation, should not overflow
591        assert!(!w.is_overflowing());
592        // Oldest messages should have been dropped
593        assert!(w.message_count() < 32);
594    }
595
596    #[test]
597    fn test_sliding_window_preserves_pinned() {
598        let mut w = small_window();
599        w.add_pinned(Role::System, "Pinned system prompt that must stay");
600        for i in 0..30 {
601            w.add_message(Role::User, format!("Overflow message {}", i));
602        }
603        // The pinned message should still be present.
604        let has_pinned = w.messages().any(|m| m.pinned);
605        assert!(has_pinned, "pinned messages should survive truncation");
606    }
607
608    // --- priority-based truncation ---
609
610    #[test]
611    fn test_priority_truncation_removes_low_importance() {
612        let mut w = priority_window();
613        w.add_message(
614            Role::Assistant,
615            "Low importance assistant response from early turn",
616        );
617        w.add_message(Role::System, "High importance system message");
618        // Fill up
619        for i in 0..30 {
620            w.add_message(Role::User, format!("User message {}", i));
621        }
622        assert!(!w.is_overflowing());
623    }
624
625    #[test]
626    fn test_priority_preserves_pinned() {
627        let mut w = priority_window();
628        w.add_pinned(Role::System, "Pinned instruction");
629        for i in 0..30 {
630            w.add_message(Role::User, format!("Filler message {}", i));
631        }
632        let has_pinned = w.messages().any(|m| m.pinned);
633        assert!(has_pinned);
634    }
635
636    // --- compress truncation ---
637
638    #[test]
639    fn test_compress_creates_summary() {
640        let mut w = compress_window();
641        for i in 0..30 {
642            w.add_message(Role::User, format!("Message about topic {}", i));
643        }
644        // After compression, there should be at least one summary.
645        assert!(
646            !w.summaries().is_empty() || w.message_count() < 30,
647            "compression should either create summaries or reduce messages"
648        );
649    }
650
651    #[test]
652    fn test_compress_summary_has_metadata() {
653        let mut w = compress_window();
654        for i in 0..30 {
655            w.add_message(Role::User, format!("Message about topic {}", i));
656        }
657        if let Some(summary) = w.summaries().first() {
658            assert!(summary.messages_compressed > 0);
659            assert!(summary.original_tokens > 0);
660            assert!(summary.token_count > 0);
661        }
662    }
663
664    // --- build_context ---
665
666    #[test]
667    fn test_build_context_includes_messages() {
668        let mut w = default_window();
669        w.add_message(Role::User, "Hello AI");
670        let ctx = w.build_context();
671        assert!(ctx.contains("Hello AI"));
672        assert!(ctx.contains("[user]"));
673    }
674
675    #[test]
676    fn test_build_context_includes_summaries() {
677        let mut w = compress_window();
678        for i in 0..30 {
679            w.add_message(Role::User, format!("Message {}", i));
680        }
681        let ctx = w.build_context();
682        if !w.summaries().is_empty() {
683            assert!(ctx.contains("[Summary]"));
684        }
685    }
686
687    #[test]
688    fn test_build_context_empty_window() {
689        let w = default_window();
690        let ctx = w.build_context();
691        assert!(ctx.is_empty());
692    }
693
694    // --- fill_ratio ---
695
696    #[test]
697    fn test_fill_ratio_empty_is_zero() {
698        let w = default_window();
699        assert!((w.fill_ratio() - 0.0).abs() < 1e-10);
700    }
701
702    #[test]
703    fn test_fill_ratio_increases_with_messages() {
704        let mut w = default_window();
705        let before = w.fill_ratio();
706        w.add_message(Role::User, "Some content to fill the window");
707        let after = w.fill_ratio();
708        assert!(after > before);
709    }
710
711    #[test]
712    fn test_fill_ratio_capped_at_one() {
713        let mut w = small_window();
714        for _ in 0..100 {
715            w.add_pinned(Role::User, "lots of pinned content that cannot be removed");
716        }
717        assert!(w.fill_ratio() <= 1.0);
718    }
719
720    // --- state snapshot ---
721
722    #[test]
723    fn test_state_snapshot_fields() {
724        let mut w = default_window();
725        w.add_message(Role::User, "test");
726        let state = w.state();
727        assert!(state.total_tokens > 0);
728        assert_eq!(state.message_count, 1);
729        assert!(!state.is_overflowing);
730    }
731
732    // --- config access ---
733
734    #[test]
735    fn test_config_accessor() {
736        let w = default_window();
737        assert_eq!(w.config().max_tokens, 4096);
738        assert_eq!(w.config().reserved_for_response, 512);
739    }
740
741    // --- WindowConfig default ---
742
743    #[test]
744    fn test_window_config_default() {
745        let config = WindowConfig::default();
746        assert_eq!(config.max_tokens, 4096);
747        assert_eq!(config.reserved_for_response, 512);
748        assert_eq!(
749            config.truncation_strategy,
750            TruncationStrategy::SlidingWindow
751        );
752    }
753
754    // --- multi-turn windowing ---
755
756    #[test]
757    fn test_multi_turn_conversation() {
758        let mut w = default_window();
759        for i in 0..5 {
760            w.add_message(Role::User, format!("User turn {}", i));
761            w.add_message(Role::Assistant, format!("Assistant turn {}", i));
762        }
763        assert_eq!(w.message_count(), 10);
764    }
765
766    #[test]
767    fn test_turn_numbers_are_sequential() {
768        let mut w = default_window();
769        w.add_message(Role::User, "First");
770        w.add_message(Role::Assistant, "Second");
771        w.add_message(Role::User, "Third");
772        let turns: Vec<usize> = w.messages().map(|m| m.turn).collect();
773        assert_eq!(turns, vec![0, 1, 2]);
774    }
775
776    // --- edge cases ---
777
778    #[test]
779    fn test_zero_max_tokens_always_overflows() {
780        let mut w = ContextWindow::new(WindowConfig {
781            max_tokens: 0,
782            reserved_for_response: 0,
783            truncation_strategy: TruncationStrategy::SlidingWindow,
784        });
785        w.add_message(Role::User, "Hello");
786        assert_eq!(
787            w.message_count(),
788            0,
789            "should truncate everything with 0 budget"
790        );
791    }
792
793    #[test]
794    fn test_reserved_larger_than_max() {
795        let w = ContextWindow::new(WindowConfig {
796            max_tokens: 10,
797            reserved_for_response: 20,
798            truncation_strategy: TruncationStrategy::SlidingWindow,
799        });
800        assert_eq!(w.available_tokens(), 0);
801    }
802}