gigi-cli 1.0.0

Gigi — A Claude Code-like AI coding assistant CLI in Rust
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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
use anyhow::{Context, Result};
use async_trait::async_trait;
use reqwest::Client;
use serde::{Deserialize, Serialize};

use super::provider::ModelProvider;
use super::types::*;

// =============================================================================
// Groq Provider — Uses OpenAI-compatible API with Groq's endpoint
// =============================================================================

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

impl GroqProvider {
    pub fn new(api_key: String, model: Option<String>, base_url: Option<String>) -> Self {
        Self {
            client: Client::new(),
            api_key,
            model: model.unwrap_or_else(|| "llama-3.3-70b-versatile".to_string()),
            base_url: base_url.unwrap_or_else(|| "https://api.groq.com/openai".to_string()),
        }
    }
}

#[async_trait]
impl ModelProvider for GroqProvider {
    async fn complete(&self, request: CompletionRequest) -> Result<CompletionResponse> {
        let url = format!("{}/v1/chat/completions", self.base_url);

        let messages = build_openai_messages(&request);
        let tools = build_openai_tools(&request);

        let mut body = serde_json::json!({
            "model": self.model,
            "messages": messages,
            "max_tokens": request.max_tokens,
        });

        if !tools.is_empty() {
            body["tools"] = serde_json::json!(tools);
        }

        let response = self
            .client
            .post(&url)
            .header("Authorization", format!("Bearer {}", self.api_key))
            .header("Content-Type", "application/json")
            .json(&body)
            .send()
            .await
            .context("Failed to send request to Groq API")?;

        if !response.status().is_success() {
            let status = response.status();
            let error_text = response.text().await.unwrap_or_default();
            anyhow::bail!("Groq API error ({}): {}", status, error_text);
        }

        let api_response: OpenAIResponse = response
            .json()
            .await
            .context("Failed to parse Groq API response")?;

        parse_openai_response(api_response)
    }

    fn name(&self) -> &str {
        "groq"
    }

    fn model_id(&self) -> &str {
        &self.model
    }

    fn supports_tools(&self) -> bool {
        true
    }
}

// =============================================================================
// Google AI Studio (Gemini) Provider
// =============================================================================

pub struct GoogleProvider {
    client: Client,
    api_key: String,
    model: String,
    base_url: String,
}

impl GoogleProvider {
    pub fn new(api_key: String, model: Option<String>, base_url: Option<String>) -> Self {
        Self {
            client: Client::new(),
            api_key,
            model: model.unwrap_or_else(|| "gemini-2.5-flash".to_string()),
            base_url: base_url
                .unwrap_or_else(|| "https://generativelanguage.googleapis.com".to_string()),
        }
    }
}

#[async_trait]
impl ModelProvider for GoogleProvider {
    async fn complete(&self, request: CompletionRequest) -> Result<CompletionResponse> {
        // Google Gemini uses its own API format
        let url = format!(
            "{}/v1beta/models/{}:generateContent?key={}",
            self.base_url, self.model, self.api_key
        );

        let mut parts: Vec<serde_json::Value> = Vec::new();

        // Add system instruction
        let system_instruction = if !request.system.is_empty() {
            Some(serde_json::json!({
                "parts": [{ "text": request.system }]
            }))
        } else {
            None
        };

        // Build contents array from messages
        let contents: Vec<serde_json::Value> = request
            .messages
            .iter()
            .filter_map(|msg| {
                let role = match msg.role {
                    Role::User => "user",
                    Role::Assistant => "model",
                    Role::System => return None, // Handled via systemInstruction
                };

                let parts: Vec<serde_json::Value> = msg
                    .content
                    .iter()
                    .filter_map(|block| match block {
                        ContentBlock::Text { text } => {
                            Some(serde_json::json!({ "text": text }))
                        }
                        ContentBlock::ToolUse { id, name, input } => {
                            Some(serde_json::json!({
                                "functionCall": {
                                    "name": name,
                                    "args": input
                                }
                            }))
                        }
                        ContentBlock::ToolResult {
                            tool_use_id: _,
                            content,
                            ..
                        } => Some(serde_json::json!({
                            "functionResponse": {
                                "name": "tool",
                                "response": { "result": content }
                            }
                        })),
                    })
                    .collect();

                Some(serde_json::json!({
                    "role": role,
                    "parts": parts
                }))
            })
            .collect();

        let mut body = serde_json::json!({
            "contents": contents,
            "generationConfig": {
                "maxOutputTokens": request.max_tokens,
            }
        });

        if let Some(si) = system_instruction {
            body["systemInstruction"] = si;
        }

        // Add tool declarations if any
        if !request.tools.is_empty() {
            let function_declarations: Vec<serde_json::Value> = request
                .tools
                .iter()
                .map(|t| {
                    serde_json::json!({
                        "name": t.name,
                        "description": t.description,
                        "parameters": t.input_schema
                    })
                })
                .collect();

            body["tools"] = serde_json::json!([{
                "functionDeclarations": function_declarations
            }]);
        }

        let response = self
            .client
            .post(&url)
            .header("Content-Type", "application/json")
            .json(&body)
            .send()
            .await
            .context("Failed to send request to Google AI Studio")?;

        if !response.status().is_success() {
            let status = response.status();
            let error_text = response.text().await.unwrap_or_default();
            anyhow::bail!("Google AI Studio error ({}): {}", status, error_text);
        }

        let api_response: serde_json::Value = response
            .json()
            .await
            .context("Failed to parse Google AI Studio response")?;

        // Parse Gemini response format
        let candidates = api_response["candidates"]
            .as_array()
            .context("No candidates in Google response")?;

        let first_candidate = candidates.first().context("Empty candidates array")?;
        let resp_parts = first_candidate["content"]["parts"]
            .as_array()
            .context("No parts in candidate")?;

        let mut content_blocks: Vec<ContentBlock> = Vec::new();
        let mut has_tool_use = false;

        for part in resp_parts {
            if let Some(text) = part["text"].as_str() {
                content_blocks.push(ContentBlock::Text {
                    text: text.to_string(),
                });
            }
            if let Some(fc) = part.get("functionCall") {
                has_tool_use = true;
                let name = fc["name"].as_str().unwrap_or("unknown").to_string();
                let args = fc.get("args").cloned().unwrap_or(serde_json::json!({}));
                content_blocks.push(ContentBlock::ToolUse {
                    id: format!("toolu_{}", uuid::Uuid::new_v4()),
                    name,
                    input: args,
                });
            }
        }

        let stop_reason = if has_tool_use {
            StopReason::ToolUse
        } else {
            match first_candidate["finishReason"].as_str() {
                Some("MAX_TOKENS") => StopReason::MaxTokens,
                _ => StopReason::EndTurn,
            }
        };

        Ok(CompletionResponse {
            content: content_blocks,
            stop_reason,
            usage: None, // Gemini usage parsing is different; skip for now
        })
    }

    fn name(&self) -> &str {
        "google"
    }

    fn model_id(&self) -> &str {
        &self.model
    }

    fn supports_tools(&self) -> bool {
        true
    }
}

// =============================================================================
// Shared OpenAI-compatible helpers (used by Groq and local providers)
// =============================================================================

/// Build OpenAI-format messages from our internal types.
pub fn build_openai_messages(request: &CompletionRequest) -> Vec<serde_json::Value> {
    let mut messages = Vec::new();

    // Add system message
    if !request.system.is_empty() {
        messages.push(serde_json::json!({
            "role": "system",
            "content": request.system,
        }));
    }

    for msg in &request.messages {
        let role = match msg.role {
            Role::User => "user",
            Role::Assistant => "assistant",
            Role::System => "system",
        };

        // Check if this message has tool calls (assistant) or tool results (user)
        let has_tool_use = msg.content.iter().any(|b| matches!(b, ContentBlock::ToolUse { .. }));
        let tool_results: Vec<_> = msg
            .content
            .iter()
            .filter_map(|b| match b {
                ContentBlock::ToolResult { tool_use_id, content, is_error } => {
                    Some((tool_use_id, content, is_error))
                }
                _ => None,
            })
            .collect();

        if has_tool_use {
            // Assistant message with tool calls
            let text_content: String = msg
                .content
                .iter()
                .filter_map(|b| match b {
                    ContentBlock::Text { text } => Some(text.as_str()),
                    _ => None,
                })
                .collect::<Vec<_>>()
                .join("");

            let tool_calls: Vec<serde_json::Value> = msg
                .content
                .iter()
                .filter_map(|b| match b {
                    ContentBlock::ToolUse { id, name, input } => Some(serde_json::json!({
                        "id": id,
                        "type": "function",
                        "function": {
                            "name": name,
                            "arguments": input.to_string(),
                        }
                    })),
                    _ => None,
                })
                .collect();

            let mut msg_json = serde_json::json!({
                "role": "assistant",
                "tool_calls": tool_calls,
            });
            if !text_content.is_empty() {
                msg_json["content"] = serde_json::json!(text_content);
            }
            messages.push(msg_json);
        } else if !tool_results.is_empty() {
            // Tool result messages
            for (tool_use_id, content, _is_error) in tool_results {
                messages.push(serde_json::json!({
                    "role": "tool",
                    "tool_call_id": tool_use_id,
                    "content": content,
                }));
            }
        } else {
            // Regular text message
            let text: String = msg
                .content
                .iter()
                .filter_map(|b| match b {
                    ContentBlock::Text { text } => Some(text.as_str()),
                    _ => None,
                })
                .collect::<Vec<_>>()
                .join("");

            messages.push(serde_json::json!({
                "role": role,
                "content": text,
            }));
        }
    }

    messages
}

/// Build OpenAI-format tool definitions.
pub fn build_openai_tools(request: &CompletionRequest) -> Vec<serde_json::Value> {
    request
        .tools
        .iter()
        .map(|t| {
            serde_json::json!({
                "type": "function",
                "function": {
                    "name": t.name,
                    "description": t.description,
                    "parameters": t.input_schema,
                }
            })
        })
        .collect()
}

/// Parse an OpenAI-compatible response into our internal types.
pub fn parse_openai_response(response: OpenAIResponse) -> Result<CompletionResponse> {
    let choice = response
        .choices
        .into_iter()
        .next()
        .context("No choices in API response")?;

    let mut content_blocks: Vec<ContentBlock> = Vec::new();
    let mut has_tool_calls = false;

    // Add text content if present
    if let Some(text) = &choice.message.content {
        if !text.is_empty() {
            content_blocks.push(ContentBlock::Text { text: text.clone() });
        }
    }

    // Add tool calls if present
    if let Some(tool_calls) = &choice.message.tool_calls {
        has_tool_calls = !tool_calls.is_empty();
        for tc in tool_calls {
            let input: serde_json::Value =
                serde_json::from_str(&tc.function.arguments).unwrap_or(serde_json::json!({}));
            content_blocks.push(ContentBlock::ToolUse {
                id: tc.id.clone(),
                name: tc.function.name.clone(),
                input,
            });
        }
    }

    let stop_reason = if has_tool_calls {
        StopReason::ToolUse
    } else {
        match choice.finish_reason.as_deref() {
            Some("length") => StopReason::MaxTokens,
            Some("stop") => StopReason::EndTurn,
            Some("tool_calls") => StopReason::ToolUse,
            _ => StopReason::EndTurn,
        }
    };

    let usage = response.usage.map(|u| Usage {
        input_tokens: u.prompt_tokens,
        output_tokens: u.completion_tokens,
    });

    Ok(CompletionResponse {
        content: content_blocks,
        stop_reason,
        usage,
    })
}

// =============================================================================
// OpenAI-compatible wire types (shared by Groq and local providers)
// =============================================================================

#[derive(Deserialize)]
pub struct OpenAIResponse {
    pub choices: Vec<OpenAIChoice>,
    pub usage: Option<OpenAIUsage>,
}

#[derive(Deserialize)]
pub struct OpenAIChoice {
    pub message: OpenAIMessage,
    pub finish_reason: Option<String>,
}

#[derive(Deserialize)]
pub struct OpenAIMessage {
    pub content: Option<String>,
    pub tool_calls: Option<Vec<OpenAIToolCall>>,
}

#[derive(Deserialize)]
pub struct OpenAIToolCall {
    pub id: String,
    pub function: OpenAIFunction,
}

#[derive(Deserialize)]
pub struct OpenAIFunction {
    pub name: String,
    pub arguments: String,
}

#[derive(Deserialize)]
pub struct OpenAIUsage {
    pub prompt_tokens: u32,
    pub completion_tokens: u32,
}