slf/gitai/
providers.rs

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
use super::{GitAIConfig, Provider};
use anyhow::{anyhow, Result};
use async_trait::async_trait;
use genai::{
    self,
    chat::{ChatMessage, ChatOptions, ChatRequest},
    resolver::{AuthData, AuthResolver},
    Client, ModelIden,
};
use reqwest;
use serde_json;

pub const XAI_HOST: &str = "https://api.x.ai/v1/chat/completions";
pub const XAI_MODEL: &str = "grok-beta";

pub const OLLAMA_HOST: &str = "http://localhost:11434/api/generate";
pub const OLLAMA_MODEL: &str = "qwen2.5-coder";

pub const SYSTEM_PROMPT: &str =
    "You are a Git Commit Message Generator Assistant. Your role is to help developers create clear, concise, and meaningful commit messages following best practices.

    INPUT EXPECTATIONS:
    - You will receive git diff output or a description of changes made to the code
    - The changes might include multiple files and various types of modifications

    OUTPUT REQUIREMENTS:
    1. Format: Follow the Conventional Commits specification:
       <type>[optional scope]: <description> <random imoji>

       [optional body]

       [optional footer]

    2. Types to use:
       - feat: New feature
       - fix: Bug fix
       - docs: Documentation changes
       - style: Code style changes (formatting, etc.)
       - refactor: Code changes that neither fix bugs nor add features
       - perf: Performance improvements
       - test: Adding or modifying tests
       - chore: Maintenance tasks

    3. Description Guidelines:
       - Use imperative mood ('add' not 'added' or 'adds')
       - Keep first line under 50 characters
       - Don't capitalize first letter
       - No period at the end
       - Be specific but concise

    4. Add Body only:
       - Explain breaking changes
       - Describe complex changes
       - Explain the motivation for changes
       - Document side effects

    EXAMPLE RESPONSES:

    For simple changes:
    feat: add user authentication endpoint

    For complex changes:
    feat(auth): implement OAuth2 social login

    This change adds support for social login via OAuth2 protocol,
    currently supporting Google and GitHub providers.

    BREAKING CHANGE: Authentication header format has changed

    For bug fixes:
    fix(api): prevent race condition in payment processing

    Special Instructions:
    1. If changes affect multiple areas, focus on the primary change
    2. If breaking changes exist, always include them in the footer
    3. Include relevant ticket/issue numbers if provided
    4. Use scope to indicate the component being modified

    Remember: A good commit message should complete this sentence:
    'If applied, this commit will... <your commit message>'";

pub fn create_provider(config: &GitAIConfig) -> Result<Box<dyn Provider>> {
    let provider: Box<dyn Provider> = match config.provider.as_str() {
        "openai" => {
            let api_key = config
                .openai_api_key
                .as_ref()
                .ok_or_else(|| anyhow!("OpenAI API key not configured"))?;
            Box::new(OpenAIProvider::new(api_key))
        }
        "anthropic" => {
            let api_key = config
                .anthropic_api_key
                .as_ref()
                .ok_or_else(|| anyhow!("Anthropic API key not configured"))?;
            Box::new(AnthropicProvider::new(api_key))
        }
        "gemini" => {
            let api_key = config
                .gemini_api_key
                .as_ref()
                .ok_or_else(|| anyhow!("Google Gemini API key not configured"))?;
            Box::new(GeminiProvider::new(api_key))
        }
        "groq" => {
            let api_key = config
                .groq_api_key
                .as_ref()
                .ok_or_else(|| anyhow!("Groq API key not configured"))?;
            Box::new(GroqProvider::new(api_key))
        }
        "xai" => {
            let api_key = config
                .groq_api_key
                .as_ref()
                .ok_or_else(|| anyhow!("XAI API key not configured"))?;
            Box::new(GroqProvider::new(api_key))
        }
        "ollama" => Box::new(OllamaProvider::with_config(
            config.ollama_host.clone(),
            config.ollama_model.clone(),
        )),
        _ => return Err(anyhow!("Unsupported provider: {}", config.provider)),
    };
    Ok(provider)
}

pub struct OpenAIProvider {
    client: Client,
    model: String,
}

impl OpenAIProvider {
    pub fn new(api_key: &str) -> Self {
        let api_key = api_key.to_string();
        let auth_resolver = AuthResolver::from_resolver_fn(
            move |_model_iden: ModelIden| -> Result<Option<AuthData>, genai::resolver::Error> {
                Ok(Some(AuthData::from_single(api_key.clone())))
            },
        );

        Self {
            client: Client::builder().with_auth_resolver(auth_resolver).build(),
            model: "gpt-3.5-turbo".to_string(),
        }
    }
}

#[async_trait]
impl Provider for OpenAIProvider {
    async fn generate_commit_message(&self, diff: &str) -> Result<String> {
        let chat_request = ChatRequest::default()
            .append_message(ChatMessage::system(SYSTEM_PROMPT))
            .append_message(ChatMessage::user(self.prompt(diff)));

        let response = self
            .client
            .exec_chat(&self.model, chat_request, None)
            .await?;

        Ok(response
            .content
            .unwrap()
            .text_as_str()
            .unwrap()
            .trim()
            .to_string())
    }
}

pub struct AnthropicProvider {
    client: Client,
    model: String,
}

impl AnthropicProvider {
    pub fn new(api_key: &str) -> Self {
        let api_key = api_key.to_string();
        let auth_resolver = AuthResolver::from_resolver_fn(
            move |_model_iden: ModelIden| -> Result<Option<AuthData>, genai::resolver::Error> {
                Ok(Some(AuthData::from_single(api_key.clone())))
            },
        );

        Self {
            client: Client::builder().with_auth_resolver(auth_resolver).build(),
            model: "claude-3.5-sonnet".to_string(),
        }
    }
}

#[async_trait]
impl Provider for AnthropicProvider {
    async fn generate_commit_message(&self, diff: &str) -> Result<String> {
        let chat_request = ChatRequest::default()
            .append_message(ChatMessage::system(SYSTEM_PROMPT))
            .append_message(ChatMessage::user(self.prompt(diff)));

        let response = self
            .client
            .exec_chat(&self.model, chat_request, None)
            .await?;

        Ok(response
            .content
            .unwrap()
            .text_as_str()
            .unwrap()
            .trim()
            .to_string())
    }
}

pub struct GeminiProvider {
    client: Client,
    model: String,
}

impl GeminiProvider {
    pub fn new(api_key: &str) -> Self {
        let api_key = api_key.to_string();
        let auth_resolver = AuthResolver::from_resolver_fn(
            move |_model_iden: ModelIden| -> Result<Option<AuthData>, genai::resolver::Error> {
                Ok(Some(AuthData::from_single(api_key.clone())))
            },
        );

        Self {
            client: Client::builder().with_auth_resolver(auth_resolver).build(),
            model: "gemini-1.5-pro".to_string(),
        }
    }
}

#[async_trait]
impl Provider for GeminiProvider {
    async fn generate_commit_message(&self, diff: &str) -> Result<String> {
        let chat_request = ChatRequest::default()
            .append_message(ChatMessage::system(SYSTEM_PROMPT))
            .append_message(ChatMessage::user(self.prompt(diff)));

        let options = ChatOptions::default()
            .with_temperature(0.95)
            .with_top_p(0.6);
        let response = self
            .client
            .exec_chat(&self.model, chat_request, Some(&options))
            .await?;

        Ok(response
            .content
            .unwrap()
            .text_as_str()
            .unwrap()
            .trim()
            .to_string())
    }
}

pub struct GroqProvider {
    client: Client,
    model: String,
}

impl GroqProvider {
    pub fn new(api_key: &str) -> Self {
        let api_key = api_key.to_string();
        let auth_resolver = AuthResolver::from_resolver_fn(
            move |_model_iden: ModelIden| -> Result<Option<AuthData>, genai::resolver::Error> {
                Ok(Some(AuthData::from_single(api_key.clone())))
            },
        );

        Self {
            client: Client::builder().with_auth_resolver(auth_resolver).build(),
            model: "llama-3.1-70b-versatile".to_string(),
        }
    }
}

#[async_trait]
impl Provider for GroqProvider {
    async fn generate_commit_message(&self, diff: &str) -> Result<String> {
        let chat_request = ChatRequest::default()
            .append_message(ChatMessage::system(SYSTEM_PROMPT))
            .append_message(ChatMessage::user(self.prompt(diff)));

        let options = ChatOptions::default()
            .with_temperature(0.95)
            .with_top_p(0.6);
        let response = self
            .client
            .exec_chat(&self.model, chat_request, Some(&options))
            .await?;

        Ok(response
            .content_text_as_str()
            .unwrap_or_default()
            .trim()
            .to_string())
    }
}

pub struct XAIProvider {
    host: String,
    model: String,
}

impl Default for XAIProvider {
    fn default() -> Self {
        Self {
            host: XAI_HOST.to_string(),
            model: XAI_MODEL.to_string(),
        }
    }
}

#[async_trait]
impl Provider for XAIProvider {
    async fn generate_commit_message(&self, diff: &str) -> Result<String> {
        let client = reqwest::Client::new();
        let request = client
            .post(self.host.to_string())
            .json(&serde_json::json!({
                "model": self.model,
                "system": SYSTEM_PROMPT,
                "prompt": self.prompt(diff),
                "stream": false,
                "temperature": 0.3,
                "top_p": 0.1
            }))
            .send()
            .await?;

        let response_json: serde_json::Value = serde_json::from_str(&request.text().await?)?;
        Ok(response_json["response"]
            .as_str()
            .ok_or_else(|| anyhow!("Invalid response from XAI"))?
            .trim()
            .to_string())
    }
}

pub struct OllamaProvider {
    host: String,
    model: String,
}

impl Default for OllamaProvider {
    fn default() -> Self {
        Self {
            host: OLLAMA_HOST.to_string(),
            model: OLLAMA_MODEL.to_string(),
        }
    }
}

impl OllamaProvider {
    pub fn with_config(host: Option<String>, model: Option<String>) -> Self {
        Self {
            host: host.unwrap_or_else(|| OLLAMA_HOST.to_string()),
            model: model.unwrap_or_else(|| OLLAMA_MODEL.to_string()),
        }
    }
}

#[async_trait]
impl Provider for OllamaProvider {
    async fn generate_commit_message(&self, diff: &str) -> Result<String> {
        let client = reqwest::Client::new();
        let request = client
            .post(self.host.to_string())
            .json(&serde_json::json!({
                "model": self.model,
                "system": SYSTEM_PROMPT,
                "prompt": self.prompt(diff),
                "stream": false,
                "temperature": 0.3,
                "top_p": 0.1
            }))
            .send()
            .await?;

        let response_json: serde_json::Value = serde_json::from_str(&request.text().await?)?;
        Ok(response_json["response"]
            .as_str()
            .ok_or_else(|| anyhow!("Invalid response from Ollama"))?
            .trim()
            .to_string())
    }
}