gitai/core/
token_optimizer.rs

1use crate::{config::Config, core::context::CommitContext};
2use log::debug;
3use tiktoken_rs::cl100k_base;
4
5pub struct TokenOptimizer {
6    encoder: tiktoken_rs::CoreBPE,
7    max_tokens: usize,
8    config: Config,
9}
10
11#[derive(Debug)]
12pub enum TokenError {
13    EncoderInit(String),
14    EncodingFailed(String),
15    DecodingFailed(String),
16}
17
18impl std::fmt::Display for TokenError {
19    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
20        match self {
21            TokenError::EncoderInit(e) => write!(f, "Failed to initialize encoder: {e}"),
22            TokenError::EncodingFailed(e) => write!(f, "Encoding failed: {e}"),
23            TokenError::DecodingFailed(e) => write!(f, "Decoding failed: {e}"),
24        }
25    }
26}
27
28impl std::error::Error for TokenError {}
29
30impl TokenOptimizer {
31    pub fn new(max_tokens: usize, config: Config) -> Result<Self, TokenError> {
32        let encoder = cl100k_base().map_err(|e| TokenError::EncoderInit(e.to_string()))?;
33
34        Ok(Self {
35            encoder,
36            max_tokens,
37            config,
38        })
39    }
40
41    /// Create a token optimizer for counting only (no config needed)
42    pub fn for_counting() -> Result<Self, TokenError> {
43        let encoder = cl100k_base().map_err(|e| TokenError::EncoderInit(e.to_string()))?;
44
45        Ok(Self {
46            encoder,
47            max_tokens: 0,             // Not used for counting
48            config: Config::default(), // Not used for counting
49        })
50    }
51
52    pub async fn optimize_context(&self, context: &mut CommitContext) -> Result<(), TokenError> {
53        let mut remaining_tokens = self.max_tokens;
54
55        // Step 1: Process diffs (highest priority)
56        remaining_tokens = self.optimize_diffs(context, remaining_tokens).await?;
57        if remaining_tokens == 0 {
58            debug!("Token budget exhausted after diffs, clearing commits and contents");
59            Self::clear_commits_and_contents(context);
60            return Ok(());
61        }
62
63        // Step 2: Process commits (medium priority)
64        remaining_tokens = self.optimize_commits(context, remaining_tokens)?;
65        if remaining_tokens == 0 {
66            debug!("Token budget exhausted after commits, clearing contents");
67            Self::clear_contents(context);
68            return Ok(());
69        }
70
71        // Step 3: Process file contents (lowest priority)
72        self.optimize_contents(context, remaining_tokens)?;
73
74        debug!("Final token count: {}", self.max_tokens - remaining_tokens);
75
76        Ok(())
77    }
78
79    // Optimize diffs and return remaining tokens
80    async fn optimize_diffs(
81        &self,
82        context: &mut CommitContext,
83        mut remaining: usize,
84    ) -> Result<usize, TokenError> {
85        for file in &mut context.staged_files {
86            let diff_tokens = self.count_tokens(&file.diff);
87
88            if diff_tokens > remaining {
89                debug!(
90                    "Summarizing diff for {} from {} to {} tokens",
91                    file.path, diff_tokens, remaining
92                );
93                file.diff = self.hierarchical_summarize(&file.diff, remaining).await?;
94                return Ok(0);
95            }
96
97            remaining = remaining.saturating_sub(diff_tokens);
98        }
99        Ok(remaining)
100    }
101
102    // Optimize commits and return remaining tokens
103    fn optimize_commits(
104        &self,
105        context: &mut CommitContext,
106        mut remaining: usize,
107    ) -> Result<usize, TokenError> {
108        for commit in &mut context.recent_commits {
109            let commit_tokens = self.count_tokens(&commit.message);
110
111            if commit_tokens > remaining {
112                debug!("Truncating commit message from {commit_tokens} to {remaining} tokens");
113                commit.message = self.truncate_string(&commit.message, remaining)?;
114                return Ok(0);
115            }
116
117            remaining = remaining.saturating_sub(commit_tokens);
118        }
119        Ok(remaining)
120    }
121
122    // Optimize file contents and return remaining tokens
123    fn optimize_contents(
124        &self,
125        context: &mut CommitContext,
126        mut remaining: usize,
127    ) -> Result<usize, TokenError> {
128        for file in &mut context.staged_files {
129            if let Some(content) = &mut file.content {
130                let content_tokens = self.count_tokens(content);
131
132                if content_tokens > remaining {
133                    debug!(
134                        "Truncating file content for {} from {} to {} tokens",
135                        file.path, content_tokens, remaining
136                    );
137                    *content = self.truncate_string(content, remaining)?;
138                    return Ok(0);
139                }
140
141                remaining = remaining.saturating_sub(content_tokens);
142            }
143        }
144        Ok(remaining)
145    }
146
147    pub fn truncate_string(&self, s: &str, max_tokens: usize) -> Result<String, TokenError> {
148        let tokens = self.encoder.encode_ordinary(s);
149
150        if tokens.len() <= max_tokens {
151            return Ok(s.to_string());
152        }
153
154        if max_tokens == 0 {
155            return Ok(String::from("…"));
156        }
157
158        // Reserve space for ellipsis
159        let truncation_limit = max_tokens.saturating_sub(1);
160        let ellipsis_token = self
161            .encoder
162            .encode_ordinary("…")
163            .first()
164            .copied()
165            .ok_or_else(|| TokenError::EncodingFailed("Failed to encode ellipsis".to_string()))?;
166
167        let mut truncated_tokens = Vec::with_capacity(truncation_limit + 1);
168        truncated_tokens.extend_from_slice(&tokens[..truncation_limit]);
169        truncated_tokens.push(ellipsis_token);
170
171        self.encoder
172            .decode(truncated_tokens)
173            .map_err(|e| TokenError::DecodingFailed(e.to_string()))
174    }
175
176    #[inline]
177    fn clear_commits_and_contents(context: &mut CommitContext) {
178        Self::clear_commits(context);
179        Self::clear_contents(context);
180    }
181
182    #[inline]
183    fn clear_commits(context: &mut CommitContext) {
184        context
185            .recent_commits
186            .iter_mut()
187            .for_each(|c| c.message.clear());
188    }
189
190    #[inline]
191    fn clear_contents(context: &mut CommitContext) {
192        context
193            .staged_files
194            .iter_mut()
195            .for_each(|f| f.content = None);
196    }
197
198    #[inline]
199    pub fn count_tokens(&self, s: &str) -> usize {
200        self.encoder.encode_ordinary(s).len()
201    }
202
203    /// Summarize text using LLM
204    async fn summarize_text(&self, text: &str, max_tokens: usize) -> Result<String, TokenError> {
205        let system_prompt = "You are a code diff summarizer. Provide a concise summary of the changes in the given diff, focusing on what was added, modified, or removed.";
206        let user_prompt =
207            format!("Summarize the following diff in {max_tokens} tokens or less:\n\n{text}");
208
209        match crate::core::llm::get_message::<String>(
210            &self.config,
211            &self.config.default_provider,
212            system_prompt,
213            &user_prompt,
214        )
215        .await
216        {
217            Ok(summary) => Ok(summary),
218            Err(e) => Err(TokenError::EncodingFailed(format!(
219                "Summarization failed: {e}"
220            ))),
221        }
222    }
223
224    /// Perform hierarchical summarization (map-reduce) on large text
225    async fn hierarchical_summarize(
226        &self,
227        text: &str,
228        max_tokens: usize,
229    ) -> Result<String, TokenError> {
230        // Try to summarize, but fall back to truncation if LLM fails
231        if let Ok(summary) = self.try_hierarchical_summarize(text, max_tokens).await {
232            Ok(summary)
233        } else {
234            // Fallback to truncation
235            debug!("Summarization failed, falling back to truncation");
236            self.truncate_string(text, max_tokens)
237        }
238    }
239
240    async fn try_hierarchical_summarize(
241        &self,
242        text: &str,
243        max_tokens: usize,
244    ) -> Result<String, TokenError> {
245        // Split text into chunks that fit within LLM context
246        let chunk_size = 4000; // Conservative chunk size for LLM input
247        let chunks: Vec<&str> = text
248            .as_bytes()
249            .chunks(chunk_size)
250            .map(|chunk| std::str::from_utf8(chunk).unwrap_or(""))
251            .filter(|chunk| !chunk.is_empty())
252            .collect();
253
254        if chunks.len() <= 1 {
255            // If only one chunk, summarize directly
256            return self.summarize_text(text, max_tokens).await;
257        }
258
259        // Map: Summarize each chunk
260        let mut chunk_summaries = Vec::new();
261        for chunk in &chunks {
262            let summary = self
263                .summarize_text(chunk, max_tokens / chunks.len())
264                .await?;
265            chunk_summaries.push(summary);
266        }
267
268        // Reduce: Combine summaries
269        let combined = chunk_summaries.join("\n\n");
270        if self.count_tokens(&combined) <= max_tokens {
271            Ok(combined)
272        } else {
273            // If still too large, summarize the combined summaries
274            self.summarize_text(&combined, max_tokens).await
275        }
276    }
277}