oli-server 0.1.4

A simple, blazingly fast AI coding assistant server
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
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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
use crate::apis::api_client::{
    ApiClient, CompletionOptions, Message, ToolCall, ToolDefinition, ToolResult,
};
use crate::app::logger::{format_log_with_color, LogLevel};
use crate::errors::AppError;
use anyhow::Result;
use async_trait::async_trait;
use rand;
use reqwest::header::{HeaderMap, HeaderValue, CONTENT_TYPE};
use reqwest::Client as ReqwestClient;
use serde::{Deserialize, Serialize};
use serde_json::{self, json, Value};
use std::time::Duration;

// Ollama API Types
#[derive(Debug, Clone, Serialize, Deserialize)]
struct OllamaMessage {
    role: String,
    #[serde(default)]
    #[serde(with = "content_string_or_object")]
    content: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    tool_calls: Option<Vec<OllamaToolCall>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    tool_call_id: Option<String>,
}

// Custom serializer to handle content that might be a string or a complex object
mod content_string_or_object {
    use serde::{self, Deserialize, Deserializer, Serializer};
    use serde_json::Value;

    pub fn serialize<S>(content: &str, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(content)
    }

    pub fn deserialize<'de, D>(deserializer: D) -> Result<String, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = Value::deserialize(deserializer)?;
        match value {
            Value::String(s) => Ok(s),
            _ => Ok(value.to_string()),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct OllamaToolCall {
    #[serde(default)]
    id: String,
    function: OllamaFunctionCall,
    #[serde(rename = "type")]
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    tool_type: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct OllamaFunctionCall {
    name: String,
    #[serde(with = "arguments_as_string_or_object")]
    arguments: String,
}

// Custom serde module for function arguments
mod arguments_as_string_or_object {
    use serde::{self, Deserialize, Deserializer, Serializer};
    use serde_json::Value;

    pub fn serialize<S>(arguments: &str, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(arguments)
    }

    pub fn deserialize<'de, D>(deserializer: D) -> Result<String, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = Value::deserialize(deserializer)?;

        match value {
            Value::String(s) => Ok(s),
            _ => {
                // If it's not a string, convert the JSON to a string
                let json_str = serde_json::to_string(&value).unwrap_or_else(|_| "{}".to_string());
                Ok(json_str)
            }
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct OllamaTool {
    #[serde(rename = "type")]
    tool_type: String,
    function: OllamaFunction,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct OllamaFunction {
    name: String,
    description: String,
    parameters: Value,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct OllamaRequest {
    model: String,
    messages: Vec<OllamaMessage>,
    stream: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    temperature: Option<f32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    top_p: Option<f32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    options: Option<Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    format: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    tools: Option<Vec<OllamaTool>>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct OllamaResponse {
    model: String,
    created_at: String,
    message: OllamaMessage,
    done: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    total_duration: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    load_duration: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    prompt_eval_duration: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    eval_count: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    eval_duration: Option<u64>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct OllamaListModelsResponse {
    models: Vec<OllamaModelInfo>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OllamaModelInfo {
    pub name: String,
    pub modified_at: String,
    pub size: u64,
    pub digest: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub details: Option<OllamaModelDetails>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OllamaModelDetails {
    pub parameter_size: Option<String>,
    pub quantization_level: Option<String>,
    pub format: Option<String>,
    pub families: Option<Vec<String>>,
    pub description: Option<String>,
}

pub struct OllamaClient {
    client: ReqwestClient,
    model: String,
    api_base: String,
}

impl OllamaClient {
    pub fn new(model: Option<String>) -> Result<Self> {
        // Default to qwen2.5-coder:14b model if None or empty string
        let model_name = match model {
            Some(m) if !m.trim().is_empty() => m,
            _ => "qwen2.5-coder:14b".to_string(),
        };

        Self::with_base_url(model_name, "http://localhost:11434".to_string())
    }

    pub fn with_base_url(model: String, api_base: String) -> Result<Self> {
        let mut headers = HeaderMap::new();
        headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));

        let client = ReqwestClient::builder()
            .default_headers(headers)
            .timeout(Duration::from_secs(300)) // 5 minutes timeout for operations
            .build()?;

        Ok(Self {
            client,
            model,
            api_base,
        })
    }

    fn convert_messages(&self, messages: Vec<Message>) -> Vec<OllamaMessage> {
        messages
            .into_iter()
            .map(|msg| {
                // Convert standard messages to Ollama format
                OllamaMessage {
                    role: msg.role,
                    content: msg.content,
                    tool_calls: None,
                    tool_call_id: None,
                }
            })
            .collect()
    }

    fn convert_tool_definitions(&self, tools: Vec<ToolDefinition>) -> Vec<OllamaTool> {
        tools
            .into_iter()
            .map(|tool| OllamaTool {
                tool_type: "function".to_string(),
                function: OllamaFunction {
                    name: tool.name,
                    description: tool.description,
                    parameters: tool.parameters,
                },
            })
            .collect()
    }

    pub async fn list_models(&self) -> Result<Vec<OllamaModelInfo>> {
        let url = format!("{}/api/tags", self.api_base);

        eprintln!(
            "{}",
            format_log_with_color(
                LogLevel::Debug,
                &format!("Listing Ollama models from: {}", url)
            )
        );

        let response = self.client.get(&url).send().await.map_err(|e| {
            let error_msg = if e.is_connect() {
                // Connection failed - likely Ollama is not running
                "Failed to connect to Ollama server. Make sure 'ollama serve' is running."
                    .to_string()
            } else {
                format!("Failed to send request to Ollama: {}", e)
            };
            eprintln!("{}", format_log_with_color(LogLevel::Error, &error_msg));
            AppError::NetworkError(error_msg)
        })?;

        if !response.status().is_success() {
            let status = response.status();
            let error_text = response
                .text()
                .await
                .unwrap_or_else(|_| "Unknown error".to_string());
            return Err(AppError::NetworkError(format!(
                "Ollama API error: {} - {}",
                status, error_text
            ))
            .into());
        }

        // Parse response
        let response_text = response.text().await.map_err(|e| {
            let error_msg = format!("Failed to get response text: {}", e);
            eprintln!("{}", format_log_with_color(LogLevel::Error, &error_msg));
            AppError::NetworkError(error_msg)
        })?;

        eprintln!(
            "{}",
            format_log_with_color(
                LogLevel::Debug,
                &format!(
                    "Ollama API response received: {} bytes",
                    response_text.len()
                )
            )
        );

        let models_response: OllamaListModelsResponse = serde_json::from_str(&response_text)
            .map_err(|e| {
                let error_msg = format!("Failed to parse Ollama response: {}", e);
                eprintln!("{}", format_log_with_color(LogLevel::Error, &error_msg));
                AppError::LLMError(error_msg)
            })?;

        Ok(models_response.models)
    }
}

#[async_trait]
impl ApiClient for OllamaClient {
    async fn complete(&self, messages: Vec<Message>, options: CompletionOptions) -> Result<String> {
        let ollama_messages = self.convert_messages(messages);

        // Make sure we have a valid model name
        let model_name = if self.model.is_empty() {
            "qwen2.5-coder:14b".to_string() // Fallback to the default model
        } else {
            self.model.clone()
        };

        let request = OllamaRequest {
            model: model_name,
            messages: ollama_messages,
            stream: false,
            temperature: options.temperature,
            top_p: options.top_p,
            options: None,
            format: if options.json_schema.is_some() {
                Some("json".to_string())
            } else {
                None
            },
            tools: None,
        };

        let url = format!("{}/api/chat", self.api_base);

        eprintln!(
            "{}",
            format_log_with_color(
                LogLevel::Debug,
                &format!("Sending request to Ollama API with model: {}", self.model)
            )
        );

        let response = self
            .client
            .post(&url)
            .json(&request)
            .send()
            .await
            .map_err(|e| {
                if e.is_connect() {
                    // Connection failed - likely Ollama is not running
                    AppError::NetworkError(
                        "Failed to connect to Ollama server. Make sure 'ollama serve' is running."
                            .to_string(),
                    )
                } else {
                    AppError::NetworkError(format!("Failed to send request to Ollama: {}", e))
                }
            })?;

        if !response.status().is_success() {
            let status = response.status();
            let error_text = response
                .text()
                .await
                .unwrap_or_else(|_| "Unknown error".to_string());
            return Err(AppError::NetworkError(format!(
                "Ollama API error: {} - {}",
                status, error_text
            ))
            .into());
        }

        // Parse response
        let response_text = response.text().await.map_err(|e| {
            let error_msg = format!("Failed to get response text: {}", e);
            eprintln!("{}", format_log_with_color(LogLevel::Error, &error_msg));
            AppError::NetworkError(error_msg)
        })?;

        eprintln!(
            "{}",
            format_log_with_color(
                LogLevel::Debug,
                &format!(
                    "Ollama API response received: {} bytes",
                    response_text.len()
                )
            )
        );

        // Try to parse as a direct response
        let ollama_response = match serde_json::from_str::<OllamaResponse>(&response_text) {
            Ok(resp) => resp,
            Err(e) => {
                // Log errors when parsing Ollama API response
                eprintln!(
                    "{}",
                    format_log_with_color(
                        LogLevel::Warning,
                        &format!("Failed to parse standard Ollama response: {}, attempting alternate parsing", e)
                    )
                );

                // Try to parse as a generic JSON value to extract what we need
                let json_value: Result<serde_json::Value, _> = serde_json::from_str(&response_text);
                if let Ok(value) = json_value {
                    if let Some(message) = value.get("message") {
                        let role = message
                            .get("role")
                            .and_then(|r| r.as_str())
                            .unwrap_or("assistant")
                            .to_string();

                        // Extract content, which might be a string or object
                        let content = match message.get("content") {
                            Some(c) if c.is_string() => c.as_str().unwrap_or("").to_string(),
                            Some(c) => c.to_string(),
                            None => "".to_string(),
                        };

                        // Construct a valid OllamaResponse with the extracted data
                        OllamaResponse {
                            model: value
                                .get("model")
                                .and_then(|m| m.as_str())
                                .unwrap_or("unknown")
                                .to_string(),
                            created_at: value
                                .get("created_at")
                                .and_then(|t| t.as_str())
                                .unwrap_or("")
                                .to_string(),
                            message: OllamaMessage {
                                role,
                                content,
                                tool_calls: None,
                                tool_call_id: None,
                            },
                            done: value.get("done").and_then(|d| d.as_bool()).unwrap_or(true),
                            total_duration: None,
                            load_duration: None,
                            prompt_eval_duration: None,
                            eval_count: None,
                            eval_duration: None,
                        }
                    } else {
                        return Err(AppError::Other(format!(
                            "Failed to parse Ollama response: {}",
                            e
                        ))
                        .into());
                    }
                } else {
                    return Err(
                        AppError::Other(format!("Failed to parse Ollama response: {}", e)).into(),
                    );
                }
            }
        };

        Ok(ollama_response.message.content)
    }

    async fn complete_with_tools(
        &self,
        messages: Vec<Message>,
        options: CompletionOptions,
        tool_results: Option<Vec<ToolResult>>,
    ) -> Result<(String, Option<Vec<ToolCall>>)> {
        // Ensure we have a valid model
        if self.model.is_empty() {
            return Err(anyhow::anyhow!(
                "Model name is empty. Please select a valid Ollama model."
            ));
        }

        // Convert messages to Ollama format
        let mut ollama_messages = self.convert_messages(messages);

        // Add tool results if provided
        if let Some(results) = tool_results {
            for result in results {
                ollama_messages.push(OllamaMessage {
                    role: "tool".to_string(),
                    content: result.output,
                    tool_calls: None,
                    tool_call_id: Some(result.tool_call_id),
                });
            }
        }

        // Make sure we have a valid model name
        let model_name = if self.model.is_empty() {
            "qwen2.5-coder:14b".to_string() // Fallback to the default model
        } else {
            self.model.clone()
        };

        // Create the request payload
        let mut request = OllamaRequest {
            model: model_name,
            messages: ollama_messages,
            stream: false,
            temperature: options.temperature,
            top_p: options.top_p,
            options: None,
            format: if options.json_schema.is_some() {
                Some("json".to_string())
            } else {
                None
            },
            tools: None,
        };

        // Add tools if provided
        if let Some(tools) = options.tools {
            let converted_tools = self.convert_tool_definitions(tools);
            request.tools = Some(converted_tools);
        }

        let url = format!("{}/api/chat", self.api_base);

        eprintln!(
            "{}",
            format_log_with_color(
                LogLevel::Debug,
                &format!("Sending request to Ollama API with model: {}", self.model)
            )
        );

        let response = self
            .client
            .post(&url)
            .json(&request)
            .send()
            .await
            .map_err(|e| {
                if e.is_connect() {
                    // Connection failed - likely Ollama is not running
                    AppError::NetworkError(
                        "Failed to connect to Ollama server. Make sure 'ollama serve' is running."
                            .to_string(),
                    )
                } else {
                    AppError::NetworkError(format!("Failed to send request to Ollama: {}", e))
                }
            })?;

        if !response.status().is_success() {
            let status = response.status();
            let error_text = response
                .text()
                .await
                .unwrap_or_else(|_| "Unknown error".to_string());
            return Err(AppError::NetworkError(format!(
                "Ollama API error: {} - {}",
                status, error_text
            ))
            .into());
        }

        // Parse response
        let response_text = response.text().await.map_err(|e| {
            let error_msg = format!("Failed to get response text: {}", e);
            eprintln!("{}", format_log_with_color(LogLevel::Error, &error_msg));
            AppError::NetworkError(error_msg)
        })?;

        eprintln!(
            "{}",
            format_log_with_color(
                LogLevel::Debug,
                &format!(
                    "Ollama API response received: {} bytes",
                    response_text.len()
                )
            )
        );

        // Try to parse as a direct response
        let ollama_response = match serde_json::from_str::<OllamaResponse>(&response_text) {
            Ok(resp) => resp,
            Err(e) => {
                // Log errors when parsing Ollama API response
                eprintln!(
                    "{}",
                    format_log_with_color(
                        LogLevel::Warning,
                        &format!("Failed to parse standard Ollama response: {}, attempting alternate parsing", e)
                    )
                );

                // Try to parse as a generic JSON value to extract what we need
                let json_value: Result<serde_json::Value, _> = serde_json::from_str(&response_text);
                if let Ok(value) = json_value {
                    if let Some(message) = value.get("message") {
                        let role = message
                            .get("role")
                            .and_then(|r| r.as_str())
                            .unwrap_or("assistant")
                            .to_string();

                        // Extract content, which might be a string or object
                        let content = match message.get("content") {
                            Some(c) if c.is_string() => c.as_str().unwrap_or("").to_string(),
                            Some(c) => c.to_string(),
                            None => "".to_string(),
                        };

                        // Construct a valid OllamaResponse with the extracted data
                        OllamaResponse {
                            model: value
                                .get("model")
                                .and_then(|m| m.as_str())
                                .unwrap_or("unknown")
                                .to_string(),
                            created_at: value
                                .get("created_at")
                                .and_then(|t| t.as_str())
                                .unwrap_or("")
                                .to_string(),
                            message: OllamaMessage {
                                role,
                                content,
                                tool_calls: None,
                                tool_call_id: None,
                            },
                            done: value.get("done").and_then(|d| d.as_bool()).unwrap_or(true),
                            total_duration: None,
                            load_duration: None,
                            prompt_eval_duration: None,
                            eval_count: None,
                            eval_duration: None,
                        }
                    } else {
                        return Err(AppError::Other(format!(
                            "Failed to parse Ollama response: {}",
                            e
                        ))
                        .into());
                    }
                } else {
                    return Err(
                        AppError::Other(format!("Failed to parse Ollama response: {}", e)).into(),
                    );
                }
            }
        };

        // Extract the content and tool calls from the response
        let content = ollama_response.message.content.clone();

        // Check for tool calls in the response
        if let Some(ollama_tool_calls) = ollama_response.message.tool_calls {
            if !ollama_tool_calls.is_empty() {
                let tool_calls = ollama_tool_calls
                    .iter()
                    .map(|call| {
                        // Parse arguments as JSON
                        let arguments_result =
                            serde_json::from_str::<Value>(&call.function.arguments);
                        let arguments = match arguments_result {
                            Ok(args) => args,
                            Err(_) => json!({}),
                        };

                        // Generate a random ID if one wasn't provided
                        let id = if call.id.is_empty() {
                            format!("ollama-tool-{}", rand::random::<u64>())
                        } else {
                            call.id.clone()
                        };

                        // Create a tool call
                        ToolCall {
                            id: Some(id),
                            name: call.function.name.clone(),
                            arguments,
                        }
                    })
                    .collect::<Vec<_>>();

                return Ok((String::new(), Some(tool_calls)));
            }
        }

        // Also try to check if the content itself contains a tool call in JSON format
        // This handles cases where Ollama doesn't properly format its tool_calls field
        // but still returns JSON in the content field that looks like a tool call
        let content_str = content.trim();
        if content_str.starts_with('{') && content_str.ends_with('}') {
            if let Ok(json_value) = serde_json::from_str::<Value>(content_str) {
                // Check for OpenAI style tool calls
                if let Some(tool_calls) = json_value.get("tool_calls").and_then(|tc| tc.as_array())
                {
                    if !tool_calls.is_empty() {
                        let calls = tool_calls
                            .iter()
                            .filter_map(|call| {
                                let id = call.get("id").and_then(|id| id.as_str()).unwrap_or("");
                                let function = call.get("function")?;
                                let name = function.get("name")?.as_str()?;
                                let arguments = function.get("arguments")?;

                                let args_str = arguments.as_str().unwrap_or("{}");
                                let args: Value =
                                    serde_json::from_str(args_str).unwrap_or(json!({}));

                                Some(ToolCall {
                                    id: Some(id.to_string()),
                                    name: name.to_string(),
                                    arguments: args,
                                })
                            })
                            .collect::<Vec<_>>();

                        if !calls.is_empty() {
                            return Ok((String::new(), Some(calls)));
                        }
                    }
                }

                // Check for the simpler/custom format that our old implementation expected
                if let (Some(tool_name), Some(tool_args)) = (
                    json_value.get("tool").and_then(|t| t.as_str()),
                    json_value.get("args"),
                ) {
                    let tool_call = ToolCall {
                        id: Some(format!("ollama-tool-{}", rand::random::<u64>())),
                        name: tool_name.to_string(),
                        arguments: tool_args.clone(),
                    };

                    return Ok((String::new(), Some(vec![tool_call])));
                }
            }
        }

        // If no tool calls were found, just return the content
        Ok((content, None))
    }
}