sermo 0.2.0

A Rust client library for interacting with various LLM provider APIs
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
#![allow(warnings)]
// Copyright 2025 Aquila Labs of Alberta, Canada <matt@cicero.sh>
// Licensed under either the Apache License, Version 2.0 OR the MIT License, at your option.
// You may not use this file except in compliance with one of the Licenses.
// Apache License text: https://www.apache.org/licenses/LICENSE-2.0
// MIT License text: https://opensource.org/licenses/MIT

use serde::{Serialize, Deserialize};
use serde::de::DeserializeOwned;
use indexmap::IndexMap;
use atlas_http::{HttpClient, HttpBody, HttpRequest};
use regex::Regex;
use std::io;

#[cfg(feature = "tools")]
pub mod tools;

#[cfg(feature = "tools")]
const MAX_TOOL_CALLS: usize = 20;

// Represents a profile for interacting with an LLM provider's API
#[derive(Default, Clone, Serialize, Deserialize)]
pub struct LlmProfile {
    pub provider: LlmProvider,    // The LLM provider (e.g., OpenAI, Ollama)
    pub api_key: String,          // API key for authentication
    pub model_name: String,       // Name of the specific model to use
    pub temperature: Option<f32>, // Optional temperature setting for generation
    pub max_tokens: Option<usize>, // Optional maximum token limit
    pub api_url: String,          // Custom API URL (if empty, uses provider default)
}

// Enum representing supported LLM providers
#[derive(Default, Clone, Serialize, Deserialize, Eq, PartialEq, Hash)]
pub enum LlmProvider {
    #[default]
    ollama,
    openai,
    anthropic,
    google,
    xai,
    mistral,
    deepseek,
    groq,
    together,
    openrouter,
    other
}

// Represents a single message in a chat conversation
#[derive(Serialize, Deserialize, Clone)]
struct ChatMessage {
    role: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    content: Option<String>,
    #[cfg(feature = "tools")]
    #[serde(skip_serializing_if = "Option::is_none")]
    tool_calls: Option<Vec<tools::ToolCall>>,
    #[cfg(feature = "tools")]
    #[serde(skip_serializing_if = "Option::is_none")]
    tool_call_id: Option<String>,
}

// Standard chat request structure for most providers
#[derive(Serialize, Deserialize)]
struct ChatRequest {
    model: String,           // Model name to use
    messages: Vec<ChatMessage>, // List of messages in the conversation
    temperature: Option<f32>,   // Temperature for generation
    max_tokens: Option<usize>,  // Maximum tokens to generate
    #[cfg(feature = "tools")]
    #[serde(skip_serializing_if = "Option::is_none")]
    tools: Option<Vec<tools::ToolDefinition>>,
}

// Ollama-specific chat request structure
#[derive(Serialize, Deserialize)]
struct ChatRequest_Ollama {
    model: String,           // Model name to use
    messages: Vec<ChatMessage>, // List of messages in the conversation
    stream: bool,            // Whether to stream the response (false for single response)
    temperature: Option<f32>,   // Temperature for generation
    max_tokens: Option<usize>,  // Maximum tokens to generate
    #[cfg(feature = "tools")]
    #[serde(skip_serializing_if = "Option::is_none")]
    tools: Option<Vec<tools::ToolDefinition>>,
}

// Represents a single response choice from the LLM
#[derive(Serialize, Deserialize)]
struct ChatChoice {
    message: ChatMessage,
}

// Standard chat response structure
#[derive(Serialize, Deserialize)]
struct ChatResponse {
    choices: Vec<ChatChoice>, // List of response choices (usually one for single requests)
}

impl LlmProfile {
    // Sends a single message to the LLM and returns the response
    pub fn send_single(&self, message: &str) -> Result<String, io::Error> {
        // Handle Ollama separately due to its unique API
        if self.provider == LlmProvider::ollama {
            return self.send_ollama(message);
        }

        // Construct a standard chat request
        let request = ChatRequest {
            model: self.model_name.clone(),
            messages: vec![ChatMessage {
                role: "user".to_string(),
                content: Some(message.to_string()),
                #[cfg(feature = "tools")]
                tool_calls: None,
                #[cfg(feature = "tools")]
                tool_call_id: None,
            }],
            temperature: self.temperature,
            max_tokens: self.max_tokens,
            #[cfg(feature = "tools")]
            tools: None,
        };

        // Serialize the request to JSON
        let json_str = serde_json::to_string(&request)
            .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e.to_string()))?;
        self.send(&json_str)
    }

    // Sends a single message to Ollama's API and returns the response
    pub fn send_ollama(&self, message: &str) -> Result<String, io::Error> {
        // Construct an Ollama-specific chat request
        let request = ChatRequest_Ollama {
            model: self.model_name.clone(),
            stream: false, // Non-streaming response
            messages: vec![ChatMessage {
                role: "user".to_string(),
                content: Some(message.to_string()),
                #[cfg(feature = "tools")]
                tool_calls: None,
                #[cfg(feature = "tools")]
                tool_call_id: None,
            }],
            temperature: self.temperature,
            max_tokens: self.max_tokens,
            #[cfg(feature = "tools")]
            tools: None,
        };

        // Serialize the request to JSON
        let json_str = serde_json::to_string(&request)
            .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e.to_string()))?;
        self.send(&json_str)
    }

    // Internal method to send an HTTP request to the LLM provider's API
    fn send(&self, json_str: &str) -> Result<String, io::Error> {
        // Prepare the request body
        let body = HttpBody::from_raw_str(json_str);

        let auth_line = format!("Authorization: Bearer {}", self.api_key);
        let auth_header = vec![
            auth_line.as_str(),
            "Content-type: application/json"
        ];

        
        // Determine the API URL (custom or provider default)
        let mut url = if self.api_url.is_empty() {
            self.provider.get_completion_url()
        } else {
            self.api_url.clone()
        };

        // Substitute model name and API key in the URL if present
        url = url.replace("~model~", &self.model_name);
        url = url.replace("~api_key~", &self.api_key);

        // Build and send the HTTP POST request
        let req = HttpRequest::new("POST", &url, &auth_header, &body);
        let mut http = HttpClient::builder().browser().build_sync();
        let res = http.send(&req)
            .map_err(|e| io::Error::new(io::ErrorKind::Other, e.to_string()))?;

        // Check for HTTP success status
        if res.status_code() != 200 {
            return Err(io::Error::new(
                io::ErrorKind::Other,
                format!("HTTP error: {}", res.status_code())
            ));
        }

        // Handle response based on provider
        if self.provider == LlmProvider::ollama {
            // Ollama returns a single ChatChoice directly
            let json_res: ChatChoice = serde_json::from_str(&res.body())
                .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e.to_string()))?;
            Ok(json_res.message.content.clone().unwrap_or_default())
        } else {
            // Other providers return a ChatResponse with choices
            let json_res: ChatResponse = serde_json::from_str(&res.body())
                .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e.to_string()))?;
            if json_res.choices.is_empty() {
                return Err(io::Error::new(
                    io::ErrorKind::Other,
                    "No choices in response"
                ));
            }
            Ok(json_res.choices[0].message.content.clone().unwrap_or_default())
        }
    }

    #[cfg(feature = "tools")]
    /// Sends a message with tool support enabled (web_search and web_fetch)
    pub fn send_with_tools(&self, message: &str, ollama_api_key: &str) -> Result<String, io::Error> {
        use tools::{Tool, web_search::WebSearchTool, web_fetch::WebFetchTool};

        // Initialize tools
        let web_search = WebSearchTool::new(ollama_api_key.to_string());
        let web_fetch = WebFetchTool::new();

        // Build tool descriptions for system message (text-based, works with all models)
        let tools_desc = r#"You have access to tools. When you need current information, use a tool by responding with ONLY a JSON object in this exact format:
{"tool": "<tool_name>", "parameters": {...}}

Available tools:
1. web_search - Search the web for current information
   Parameters: {"query": "search query string"}
   Example: {"tool": "web_search", "parameters": {"query": "latest news"}}

2. web_fetch - Fetch and read a web page
   Parameters: {"url": "https://example.com"}
   Example: {"tool": "web_fetch", "parameters": {"url": "https://example.com/page"}}

IMPORTANT: When using a tool, respond with ONLY the JSON object, nothing else - no explanations, no markdown code fences, just the raw JSON.
After you receive the tool result, you can then provide your final answer to the user."#;

        let system_msg = format!("You are a helpful assistant.\n\n{}", tools_desc);

        // Initialize conversation with system message and user message
        let mut messages = vec![
            ChatMessage {
                role: "system".to_string(),
                content: Some(system_msg),
                #[cfg(feature = "tools")]
                tool_calls: None,
                #[cfg(feature = "tools")]
                tool_call_id: None,
            },
            ChatMessage {
                role: "user".to_string(),
                content: Some(message.to_string()),
                #[cfg(feature = "tools")]
                tool_calls: None,
                #[cfg(feature = "tools")]
                tool_call_id: None,
            }
        ];

        // Tool calling loop
        for iteration in 0..MAX_TOOL_CALLS {
            // Prepare request based on provider (NO tools field - using text-based approach)
            let json_str = if self.provider == LlmProvider::ollama {
                let request = ChatRequest_Ollama {
                    model: self.model_name.clone(),
                    stream: false,
                    messages: messages.clone(),
                    temperature: self.temperature,
                    max_tokens: self.max_tokens,
                    #[cfg(feature = "tools")]
                    tools: None,  // Don't use native tool calling
                };
                serde_json::to_string(&request)
                    .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e.to_string()))?
            } else {
                let request = ChatRequest {
                    model: self.model_name.clone(),
                    messages: messages.clone(),
                    temperature: self.temperature,
                    max_tokens: self.max_tokens,
                    #[cfg(feature = "tools")]
                    tools: None,  // Don't use native tool calling
                };
                serde_json::to_string(&request)
                    .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e.to_string()))?
            };

            // Send request
            let body = HttpBody::from_raw_str(&json_str);
            let auth_line = format!("Authorization: Bearer {}", self.api_key);
            let auth_header = vec![auth_line.as_str(), "Content-type: application/json"];

            let mut url = if self.api_url.is_empty() {
                self.provider.get_completion_url()
            } else {
                self.api_url.clone()
            };
            url = url.replace("~model~", &self.model_name);
            url = url.replace("~api_key~", &self.api_key);

            let req = HttpRequest::new("POST", &url, &auth_header, &body);
            let mut http = HttpClient::builder().browser().build_sync();
            let res = http.send(&req)
                .map_err(|e| io::Error::new(io::ErrorKind::Other, e.to_string()))?;

            if res.status_code() != 200 {
                return Err(io::Error::new(
                    io::ErrorKind::Other,
                    format!("HTTP error: {}", res.status_code())
                ));
            }

            // Parse response
            let assistant_message = if self.provider == LlmProvider::ollama {
                let json_res: ChatChoice = serde_json::from_str(&res.body())
                    .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e.to_string()))?;
                json_res.message
            } else {
                let json_res: ChatResponse = serde_json::from_str(&res.body())
                    .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e.to_string()))?;
                if json_res.choices.is_empty() {
                    return Err(io::Error::new(io::ErrorKind::Other, "No choices in response"));
                }
                json_res.choices[0].message.clone()
            };

            // Get the response content
            let response_text = assistant_message.content.unwrap_or_default();

            // Try to parse as a tool call (JSON format)
            #[derive(serde::Deserialize)]
            struct ToolRequest {
                tool: String,
                parameters: serde_json::Value,
            }

            // Try to extract JSON from response (handles markdown code fences, etc.)
            let tool_request: Option<ToolRequest> = self.extract_json_flexible(&response_text);

            if let Some(tool_req) = tool_request {
                // This is a tool call - execute it
                println!("Tool call detected: {}", tool_req.tool);

                // Add assistant's tool request to conversation
                messages.push(ChatMessage {
                    role: "assistant".to_string(),
                    content: Some(response_text.clone()),
                    #[cfg(feature = "tools")]
                    tool_calls: None,
                    #[cfg(feature = "tools")]
                    tool_call_id: None,
                });

                // Execute the tool
                let params_str = tool_req.parameters.to_string();
                let result = match tool_req.tool.as_str() {
                    "web_search" => web_search.execute(&params_str),
                    "web_fetch" => web_fetch.execute(&params_str),
                    _ => Err(io::Error::new(
                        io::ErrorKind::InvalidInput,
                        format!("Unknown tool: {}", tool_req.tool)
                    )),
                };

                // Add tool result to conversation
                let tool_result_content = match result {
                    Ok(content) => content,
                    Err(e) => format!("Error executing {}: {}", tool_req.tool, e),
                };

                messages.push(ChatMessage {
                    role: "user".to_string(),  // Tool results come back as user messages
                    content: Some(format!("Tool result:\n{}", tool_result_content)),
                    #[cfg(feature = "tools")]
                    tool_calls: None,
                    #[cfg(feature = "tools")]
                    tool_call_id: None,
                });
            } else {
                // No tool call detected, this is the final response
                return Ok(response_text);
            }
        }

        // Max iterations reached
        Err(io::Error::new(
            io::ErrorKind::Other,
            format!("Maximum tool call iterations ({}) reached", MAX_TOOL_CALLS)
        ))
    }

    // Extracts JSON from a string, either an object or array
    pub fn extract_json<T: DeserializeOwned>(&self, input: &str, is_object: bool) -> Option<T> {
        let start_char = if is_object { '{' } else { '[' };
        let start_idx = input.find(start_char)?;
        
        // Track nesting depth to find complete JSON structure
        let mut depth = 0;
        let end_char = if is_object { '}' } else { ']' };
        let mut end_idx = 0;
        
        for (i, c) in input[start_idx..].char_indices() {
            if c == start_char {
                depth += 1;
            } else if c == end_char {
                depth -= 1;
                if depth == 0 {
                    end_idx = start_idx + i + 1;
                    break;
                }
            }
        }
        
        // Return None if no valid JSON structure found
        if end_idx == 0 || depth != 0 {
            return None;
        }
        
        let json_str = &input[start_idx..end_idx];
        
        // Attempt to deserialize the extracted JSON
        serde_json::from_str(json_str).ok()
    }

    // Flexibly extracts JSON (object, array, or scalar) from a string
    pub fn extract_json_flexible<T: DeserializeOwned>(&self, input: &str) -> Option<T> {
        // Try object first
        if let Some(result) = self.extract_json::<T>(input, true) {
            return Some(result);
        }
        
        // Then try array
        if let Some(result) = self.extract_json::<T>(input, false) {
            return Some(result);
        }
        
        // Try string value
        let re_string = Regex::new(r#""([^"\\]|\\[\s\S])*""#).ok()?;
        if let Some(m) = re_string.find(input) {
            if let Ok(value) = serde_json::from_str::<T>(m.as_str()) {
                return Some(value);
            }
        }
        
        // Try scalar value (number, boolean, null)
        let re_scalar = Regex::new(r"\b(true|false|null|-?\d+(\.\d+)?([eE][+-]?\d+)?)\b").ok()?;
        if let Some(m) = re_scalar.find(input) {
            if let Ok(value) = serde_json::from_str::<T>(m.as_str()) {
                return Some(value);
            }
        }
        
        None
    }

    // Creates an LlmProfile from string parameters
    pub fn from_str(
        provider_slug: &str,
        model_name: &str,
        api_key: &str,
        temperature: Option<f32>,
        max_tokens: Option<usize>,
    ) -> Self {
        LlmProfile {
            provider: LlmProvider::from_str(provider_slug),
            api_key: api_key.to_string(),
            model_name: model_name.to_string(),
            temperature,
            max_tokens,
            api_url: String::new(), // Default to empty; filled by provider if needed
        }
    }
}

impl LlmProvider {
    // Converts a numeric index to an LlmProvider
    pub fn from_usize(value: usize) -> Self {
        match value {
            0 => Self::ollama,
            1 => Self::openai,
            2 => Self::anthropic,
            3 => Self::google,
            4 => Self::xai,
            5 => Self::mistral,
            6 => Self::deepseek,
            7 => Self::groq,
            8 => Self::together,
            _ => Self::other
        }
    }

    // Returns a human-readable string representation of the provider
    pub fn to_string(&self) -> String {
        match self {
            Self::ollama => "Ollama".to_string(),
            Self::openai => "OpenAI".to_string(),
            Self::anthropic => "Anthropic".to_string(),
            Self::google => "Google Gemini".to_string(),
            Self::xai => "X.ai".to_string(),
            Self::mistral => "Mistral".to_string(),
            Self::deepseek => "Deepseek".to_string(),
            Self::groq => "Groq".to_string(),
            Self::together => "TogetherAI".to_string(),
            _ => "Other".to_string()
        }
    }

    // Returns a slug (lowercase identifier) for the provider
    pub fn to_slug(&self) -> String {
        match self {
            Self::ollama => "ollama".to_string(),
            Self::openai => "openai".to_string(),
            Self::anthropic => "anthropic".to_string(),
            Self::google => "google".to_string(),
            Self::xai => "xai".to_string(),
            Self::mistral => "mistral".to_string(),
            Self::deepseek => "deepseek".to_string(),
            Self::groq => "groq".to_string(),
            Self::together => "together".to_string(),
            _ => "other".to_string()
        }
    }

    // Returns a map of numeric indices to provider names
    pub fn get_indexmap_options() -> IndexMap<String, String> {
        let mut options = IndexMap::new();
        for x in 1..9 {
            let val = Self::from_usize(x);
            options.insert(format!("{}", x), val.to_string());
        }
        options
    }

    // Returns the default completion URL for the provider
    fn get_completion_url(&self) -> String {
        match self {
            LlmProvider::ollama => "http://localhost:11434/api/chat".to_string(),
            LlmProvider::openai => "https://api.openai.com/v1/chat/completions".to_string(),
            LlmProvider::anthropic => "https://api.anthropic.com/v1/messages".to_string(),
            LlmProvider::google => "https://generativelanguage.googleapis.com/v1beta/models/~model~:generateContent?key=~api_key~".to_string(),
            LlmProvider::xai => "https://api.x.ai/v1/chat/completions".to_string(),
            LlmProvider::mistral => "https://api.mixtral.ai/v1/chat/completions".to_string(),
            LlmProvider::deepseek => "https://api.deepseek.com/v1/chat/completions".to_string(),
            LlmProvider::groq => "https://api.groq.com/openai/v1/chat/completions".to_string(),
            LlmProvider::together => "https://api.together.xyz/v1/chat/completions".to_string(),
            LlmProvider::openrouter => "https://openrouter.ai/api/v1/chat/completions".to_string(),
            LlmProvider::other => "http://localhost:8000/v1/chat/completions".to_string(),
        }
    }

    // Creates an LlmProvider from a slug string
    fn from_str(slug: &str) -> Self {
        match slug.to_lowercase().as_str() {
            "ollama" => LlmProvider::ollama,
            "openai" => LlmProvider::openai,
            "anthropic" => LlmProvider::anthropic,
            "google" => LlmProvider::google,
            "xai" => LlmProvider::xai,
            "mistral" => LlmProvider::mistral,
            "deepseek" => LlmProvider::deepseek,
            "groq" => LlmProvider::groq,
            "together" => LlmProvider::together,
            "openrouter" => Self::openrouter,
            _ => LlmProvider::other,
        }
    }
}