Skip to main content

bindings_generat/llm/
docs.rs

1use anyhow::Result;
2use tracing::{info, warn};
3
4use super::client::OllamaClient;
5use super::prompts;
6
7/// Documentation enhancer using LLM
8pub struct DocsEnhancer {
9    client: OllamaClient,
10    model: String,
11}
12
13impl DocsEnhancer {
14    /// Create a new documentation enhancer
15    pub fn new(model: String, cache_dir: Option<std::path::PathBuf>) -> Result<Self> {
16        let client = OllamaClient::new(cache_dir)?;
17        Ok(Self { client, model })
18    }
19
20    /// Create a new documentation enhancer with custom Ollama URL
21    pub fn with_base_url(
22        model: String,
23        base_url: &str,
24        cache_dir: Option<std::path::PathBuf>,
25    ) -> Result<Self> {
26        let client = OllamaClient::with_base_url(base_url, cache_dir)?;
27        Ok(Self { client, model })
28    }
29
30    /// Check if LLM is available
31    pub fn is_available(&self) -> bool {
32        self.client.is_available()
33    }
34
35    /// Enhance documentation for a function
36    pub fn enhance_function_docs(
37        &self,
38        function_name: &str,
39        signature: &str,
40        context: &str,
41    ) -> Result<Option<String>> {
42        if !self.is_available() {
43            info!("LLM not available, skipping documentation enhancement");
44            return Ok(None);
45        }
46
47        let prompt = prompts::documentation_prompt(function_name, signature, context);
48
49        match self.client.generate(&self.model, &prompt) {
50            Ok(docs) => {
51                info!("Generated enhanced documentation for {}", function_name);
52                Ok(Some(docs.trim().to_string()))
53            }
54            Err(e) => {
55                warn!("Failed to generate documentation: {}", e);
56                Ok(None)
57            }
58        }
59    }
60
61    /// Suggest better names for an item
62    pub fn suggest_names(
63        &self,
64        c_name: &str,
65        context: &str,
66        item_type: &str,
67    ) -> Result<Option<Vec<String>>> {
68        if !self.is_available() {
69            return Ok(None);
70        }
71
72        let prompt = prompts::naming_prompt(c_name, context, item_type);
73
74        match self.client.generate(&self.model, &prompt) {
75            Ok(response) => {
76                // Parse JSON array
77                match serde_json::from_str::<Vec<String>>(&response) {
78                    Ok(names) => {
79                        info!("Generated {} name suggestions for {}", names.len(), c_name);
80                        Ok(Some(names))
81                    }
82                    Err(e) => {
83                        warn!("Failed to parse naming suggestions: {}", e);
84                        Ok(None)
85                    }
86                }
87            }
88            Err(e) => {
89                warn!("Failed to generate name suggestions: {}", e);
90                Ok(None)
91            }
92        }
93    }
94
95    /// Generate usage example for a type
96    pub fn generate_example(
97        &self,
98        type_name: &str,
99        methods: &[String],
100        context: &str,
101    ) -> Result<Option<String>> {
102        if !self.is_available() {
103            return Ok(None);
104        }
105
106        let prompt = prompts::example_prompt(type_name, methods, context);
107
108        match self.client.generate(&self.model, &prompt) {
109            Ok(example) => {
110                info!("Generated example for {}", type_name);
111                Ok(Some(example.trim().to_string()))
112            }
113            Err(e) => {
114                warn!("Failed to generate example: {}", e);
115                Ok(None)
116            }
117        }
118    }
119
120    /// Generate better error message
121    pub fn enhance_error_message(&self, error_code: &str, c_name: &str) -> Result<Option<String>> {
122        if !self.is_available() {
123            return Ok(None);
124        }
125
126        let prompt = prompts::error_message_prompt(error_code, c_name);
127
128        match self.client.generate(&self.model, &prompt) {
129            Ok(message) => {
130                info!("Enhanced error message for {}", error_code);
131                Ok(Some(message.trim().to_string()))
132            }
133            Err(e) => {
134                warn!("Failed to enhance error message: {}", e);
135                Ok(None)
136            }
137        }
138    }
139}
140
141#[cfg(test)]
142mod tests {
143    use super::*;
144    use tempfile::TempDir;
145
146    #[test]
147    fn test_docs_enhancer_creation() {
148        let temp_dir = TempDir::new().unwrap();
149        let enhancer = DocsEnhancer::new(
150            "test-model".to_string(),
151            Some(temp_dir.path().to_path_buf()),
152        );
153        assert!(enhancer.is_ok());
154    }
155
156    #[test]
157    fn test_enhancer_handles_unavailable_llm() {
158        let temp_dir = TempDir::new().unwrap();
159        let enhancer = DocsEnhancer::new(
160            "test-model".to_string(),
161            Some(temp_dir.path().to_path_buf()),
162        )
163        .unwrap();
164
165        // Should return None when LLM is not available
166        let result = enhancer.enhance_function_docs("test_func", "fn test_func()", "Test function");
167        assert!(result.is_ok());
168        assert_eq!(result.unwrap(), None);
169    }
170}