liteforge 0.2.5

Rust SDK for LiteForge - LLM completions via OpenAI-compatible API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
//! Compacting conversation that auto-summarizes when approaching limits.

use super::config::{ConversationConfig, SummarizationStrategy};
use super::managed::{ManagedConversation, TrackedMessage};
use crate::types::Message;
use serde::{Deserialize, Serialize};

/// Result of a compaction operation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CompactionResult {
    /// Number of messages removed.
    pub messages_removed: usize,
    /// Tokens before compaction.
    pub tokens_before: usize,
    /// Tokens after compaction.
    pub tokens_after: usize,
    /// Summary generated (if any).
    pub summary: Option<String>,
}

/// A conversation that automatically compacts when approaching token limits.
///
/// This wraps a ManagedConversation and adds automatic summarization.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CompactingConversation {
    /// The underlying conversation.
    conversation: ManagedConversation,
    /// Configuration.
    config: ConversationConfig,
    /// Summaries of compacted messages.
    summaries: Vec<String>,
    /// Total messages ever added (before compaction).
    total_messages_added: usize,
    /// Number of compactions performed.
    compaction_count: usize,
}

impl Default for CompactingConversation {
    fn default() -> Self {
        Self::new(ConversationConfig::default())
    }
}

impl CompactingConversation {
    /// Create a new compacting conversation with config.
    pub fn new(config: ConversationConfig) -> Self {
        Self {
            conversation: ManagedConversation::new(),
            config,
            summaries: Vec::new(),
            total_messages_added: 0,
            compaction_count: 0,
        }
    }

    /// Create with default config.
    pub fn with_defaults() -> Self {
        Self::default()
    }

    /// Create with a system message.
    pub fn with_system(system: impl Into<String>, config: ConversationConfig) -> Self {
        let mut conv = Self::new(config);
        conv.conversation.set_system(system);
        conv
    }

    /// Set or replace the system message.
    pub fn set_system(&mut self, content: impl Into<String>) {
        self.conversation.set_system(content);
    }

    /// Get the system message.
    pub fn system_message(&self) -> Option<&Message> {
        self.conversation.system_message()
    }

    /// Add a user message.
    pub fn add_user_message(&mut self, content: impl Into<String>) {
        self.conversation.add_user_message(content);
        self.total_messages_added += 1;
    }

    /// Add an assistant message.
    pub fn add_assistant_message(&mut self, content: impl Into<String>) {
        self.conversation.add_assistant_message(content);
        self.total_messages_added += 1;
    }

    /// Add any message.
    pub fn add_message(&mut self, message: Message) {
        self.conversation.add_message(message);
        self.total_messages_added += 1;
    }

    /// Check if compaction is needed.
    pub fn needs_compaction(&self) -> bool {
        self.conversation.estimated_tokens() > self.config.max_tokens
    }

    /// Compact the conversation using the configured strategy.
    /// Returns None if no compaction was needed.
    pub fn compact(&mut self) -> Option<CompactionResult> {
        if !self.needs_compaction() {
            return None;
        }

        let tokens_before = self.conversation.estimated_tokens();
        let messages_before = self.conversation.len();

        let summary = match self.config.strategy {
            SummarizationStrategy::KeepRecent => self.compact_keep_recent(),
            SummarizationStrategy::Summarize => self.compact_with_summary(),
            SummarizationStrategy::ChunkedSummary => self.compact_chunked(),
            SummarizationStrategy::PreserveSystem => self.compact_preserve_system(),
        };

        let tokens_after = self.conversation.estimated_tokens();
        let messages_after = self.conversation.len();

        self.compaction_count += 1;

        Some(CompactionResult {
            messages_removed: messages_before - messages_after,
            tokens_before,
            tokens_after,
            summary,
        })
    }

    /// Compact by keeping only recent messages.
    fn compact_keep_recent(&mut self) -> Option<String> {
        let preserve = self.config.preserve_recent;
        if self.conversation.len() > preserve {
            let to_remove = self.conversation.len() - preserve;
            self.conversation.remove_first(to_remove);
        }
        None
    }

    /// Compact by creating a summary of older messages.
    fn compact_with_summary(&mut self) -> Option<String> {
        let preserve = self.config.preserve_recent;
        if self.conversation.len() <= preserve {
            return None;
        }

        // Get messages to summarize
        let to_remove = self.conversation.len() - preserve;
        let tracked = self.conversation.tracked_messages();
        let messages_to_summarize: Vec<&TrackedMessage> = tracked.iter().take(to_remove).collect();

        // Create a simple text summary (in production, this would call an LLM)
        let summary = self.create_summary_text(&messages_to_summarize);
        self.summaries.push(summary.clone());

        // Remove old messages
        self.conversation.remove_first(to_remove);

        Some(summary)
    }

    /// Compact in chunks, creating multiple summary levels.
    fn compact_chunked(&mut self) -> Option<String> {
        // For now, same as regular summarize but could be extended
        self.compact_with_summary()
    }

    /// Compact while preserving system messages.
    fn compact_preserve_system(&mut self) -> Option<String> {
        // Same as summarize but system is already preserved by default
        self.compact_with_summary()
    }

    /// Create a text representation of messages for summarization.
    fn create_summary_text(&self, messages: &[&TrackedMessage]) -> String {
        let mut text = String::from("[Previous conversation summary]\n");
        for tracked in messages {
            let role = match tracked.message.role.as_str() {
                "user" => "User",
                "assistant" => "Assistant",
                other => other,
            };
            if let Some(content) = &tracked.message.content {
                // Truncate very long messages
                let content = if content.len() > 200 {
                    format!("{}...", &content[..200])
                } else {
                    content.clone()
                };
                text.push_str(&format!("- {}: {}\n", role, content));
            }
        }
        text
    }

    /// Get all messages (including system).
    pub fn messages(&self) -> Vec<Message> {
        let mut messages = Vec::new();

        // Add summary as a system message if there are summaries
        if !self.summaries.is_empty() {
            let combined_summary = self.summaries.join("\n\n");
            messages.push(Message::system(format!(
                "Previous conversation context:\n{}",
                combined_summary
            )));
        }

        // Add current messages
        messages.extend(self.conversation.messages());
        messages
    }

    /// Get messages for API call (optimized format).
    pub fn messages_for_api(&self) -> Vec<Message> {
        self.messages()
    }

    /// Get current message count (excluding compacted).
    pub fn len(&self) -> usize {
        self.conversation.len()
    }

    /// Check if empty.
    pub fn is_empty(&self) -> bool {
        self.conversation.is_empty()
    }

    /// Get estimated tokens.
    pub fn estimated_tokens(&self) -> usize {
        self.conversation.estimated_tokens()
    }

    /// Get configuration.
    pub fn config(&self) -> &ConversationConfig {
        &self.config
    }

    /// Update configuration.
    pub fn set_config(&mut self, config: ConversationConfig) {
        self.config = config;
    }

    /// Get total messages ever added.
    pub fn total_messages_added(&self) -> usize {
        self.total_messages_added
    }

    /// Get number of compactions performed.
    pub fn compaction_count(&self) -> usize {
        self.compaction_count
    }

    /// Get all summaries.
    pub fn summaries(&self) -> &[String] {
        &self.summaries
    }

    /// Clear the conversation.
    pub fn clear(&mut self, keep_system: bool) {
        self.conversation.clear(keep_system);
        self.summaries.clear();
    }

    /// Get the underlying managed conversation.
    pub fn inner(&self) -> &ManagedConversation {
        &self.conversation
    }

    /// Get mutable access to underlying conversation.
    pub fn inner_mut(&mut self) -> &mut ManagedConversation {
        &mut self.conversation
    }

    /// Set metadata.
    pub fn set_metadata(&mut self, key: impl Into<String>, value: impl Into<String>) {
        self.conversation.set_metadata(key, value);
    }

    /// Get metadata.
    pub fn get_metadata(&self, key: &str) -> Option<&str> {
        self.conversation.get_metadata(key)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn small_config() -> ConversationConfig {
        ConversationConfig {
            max_tokens: 100,
            target_tokens: 50,
            preserve_recent: 2,
            preserve_system: true,
            strategy: SummarizationStrategy::KeepRecent,
            summarization_model: None,
            summarization_prompt: String::new(),
        }
    }

    #[test]
    fn test_compacting_conversation_new() {
        let conv = CompactingConversation::with_defaults();
        assert!(conv.is_empty());
        assert_eq!(conv.compaction_count(), 0);
    }

    #[test]
    fn test_compacting_add_messages() {
        let mut conv = CompactingConversation::with_defaults();
        conv.add_user_message("Hello");
        conv.add_assistant_message("Hi!");

        assert_eq!(conv.len(), 2);
        assert_eq!(conv.total_messages_added(), 2);
    }

    #[test]
    fn test_compacting_needs_compaction() {
        let mut conv = CompactingConversation::new(small_config());
        conv.add_user_message("Short");
        assert!(!conv.needs_compaction());

        // Add many messages to exceed limit
        for i in 0..20 {
            conv.add_user_message(format!("Message number {} with some content", i));
        }
        assert!(conv.needs_compaction());
    }

    #[test]
    fn test_compact_keep_recent() {
        let mut conv = CompactingConversation::new(small_config());

        // Add enough messages to trigger compaction
        for i in 0..10 {
            conv.add_user_message(format!("Message {}", i));
        }

        if conv.needs_compaction() {
            let result = conv.compact();
            assert!(result.is_some());

            let result = result.unwrap();
            assert!(result.messages_removed > 0);
            assert_eq!(conv.len(), 2); // preserve_recent = 2
        }
    }

    #[test]
    fn test_compact_with_summary() {
        let config = ConversationConfig {
            max_tokens: 100,
            target_tokens: 50,
            preserve_recent: 2,
            preserve_system: true,
            strategy: SummarizationStrategy::Summarize,
            summarization_model: None,
            summarization_prompt: String::new(),
        };
        let mut conv = CompactingConversation::new(config);

        for i in 0..10 {
            conv.add_user_message(format!("Message {}", i));
        }

        if conv.needs_compaction() {
            let result = conv.compact();
            assert!(result.is_some());

            let result = result.unwrap();
            assert!(result.summary.is_some());
            assert_eq!(conv.summaries().len(), 1);
        }
    }

    #[test]
    fn test_messages_include_summary() {
        let config = ConversationConfig {
            max_tokens: 100,
            target_tokens: 50,
            preserve_recent: 2,
            preserve_system: true,
            strategy: SummarizationStrategy::Summarize,
            summarization_model: None,
            summarization_prompt: String::new(),
        };
        let mut conv = CompactingConversation::new(config);

        for i in 0..10 {
            conv.add_user_message(format!("Message {}", i));
        }

        // Force compaction
        while conv.needs_compaction() {
            conv.compact();
        }

        // Messages should include summary context
        let messages = conv.messages();
        if !conv.summaries().is_empty() {
            assert!(messages.iter().any(|m| m.role == "system"));
        }
    }

    #[test]
    fn test_with_system_message() {
        let config = small_config();
        let mut conv = CompactingConversation::with_system("You are helpful.", config);

        assert!(conv.system_message().is_some());
        conv.add_user_message("Hello");

        let messages = conv.messages();
        assert!(messages.iter().any(|m| m.role == "system"));
    }

    #[test]
    fn test_compaction_count() {
        let mut conv = CompactingConversation::new(small_config());

        for i in 0..10 {
            conv.add_user_message(format!("Message {}", i));
        }

        let mut count = 0;
        while conv.needs_compaction() {
            conv.compact();
            count += 1;
        }

        assert_eq!(conv.compaction_count(), count);
    }

    #[test]
    fn test_clear() {
        let mut conv = CompactingConversation::with_system("System", small_config());
        conv.add_user_message("Hello");

        // Force some summaries
        for i in 0..10 {
            conv.add_user_message(format!("Msg {}", i));
        }
        while conv.needs_compaction() {
            conv.compact();
        }

        conv.clear(true);
        assert!(conv.is_empty());
        assert!(conv.summaries().is_empty());
        assert!(conv.system_message().is_some());
    }

    #[test]
    fn test_metadata() {
        let mut conv = CompactingConversation::with_defaults();
        conv.set_metadata("key", "value");
        assert_eq!(conv.get_metadata("key"), Some("value"));
    }
}