sermo 0.2.5

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
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
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
#![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,
    openai_responses, // OpenAI GPT-5.6+ via the Responses API (/v1/responses)
    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>>,
}

// OpenAI Responses API request structure (GPT-5.6+ / reasoning models)
// Differences from ChatRequest:
//  - `messages` -> `input`
//  - `max_tokens` -> `max_output_tokens` (omitted entirely when None; null is rejected)
//  - `temperature` is never sent; reasoning models only accept the default of 1
#[derive(Serialize, Deserialize)]
struct ChatRequest_OpenAIResponses {
    model: String,              // Model name to use
    input: Vec<ChatMessage>,    // List of messages in the conversation
    #[serde(skip_serializing_if = "Option::is_none")]
    max_output_tokens: Option<usize>, // Upper bound on output tokens, INCLUDING reasoning tokens
    store: bool,                // Whether OpenAI stores the response server-side (false = stateless)
}

// Anthropic Messages API request structure
// Differences from ChatRequest:
//  - `max_tokens` is REQUIRED and must be an integer (null / missing is rejected with a 400)
//  - `temperature` is never sent; it is deprecated on the latest Claude models and rejected with a 400
//  - system prompt is a top-level `system` field; `messages` only accepts `user` / `assistant` roles
#[derive(Serialize)]
struct ChatRequest_Anthropic {
    model: String,              // Model name to use
    max_tokens: usize,          // Maximum tokens to generate (required by Anthropic)
    messages: Vec<ChatMessage>, // List of user / assistant messages in the conversation
    #[serde(skip_serializing_if = "Option::is_none")]
    system: Option<String>,     // Top-level system prompt
}

// Anthropic Messages API response structure
#[derive(Deserialize)]
struct AnthropicResponse {
    #[serde(default)]
    content: Vec<AnthropicContent>,
}

// A single content block of an Anthropic response (e.g. "text", "thinking", "tool_use")
#[derive(Deserialize)]
struct AnthropicContent {
    #[serde(rename = "type")]
    content_type: String,
    #[serde(default)]
    text: Option<String>,
}

// Default max_tokens sent to Anthropic when the profile does not specify one, as the API requires it
const ANTHROPIC_DEFAULT_MAX_TOKENS: usize = 4096;

// Value of the required `anthropic-version` header
const ANTHROPIC_VERSION: &str = "2023-06-01";

// OpenAI Responses API response structure
#[derive(Deserialize)]
struct ResponsesApiResponse {
    #[serde(default)]
    status: Option<String>,
    #[serde(default)]
    output: Vec<ResponsesOutputItem>,
    #[serde(default)]
    error: Option<ResponsesError>,
    #[serde(default)]
    incomplete_details: Option<ResponsesIncompleteDetails>,
}

// A single item in the `output` array (e.g. "message", "reasoning", "function_call")
#[derive(Deserialize)]
struct ResponsesOutputItem {
    #[serde(rename = "type")]
    item_type: String,
    #[serde(default)]
    content: Option<Vec<ResponsesContent>>,
}

// A content part of an output item (e.g. "output_text", "refusal")
#[derive(Deserialize)]
struct ResponsesContent {
    #[serde(rename = "type")]
    content_type: String,
    #[serde(default)]
    text: Option<String>,
    #[serde(default)]
    refusal: Option<String>,
}

#[derive(Deserialize)]
struct ResponsesError {
    #[serde(default)]
    code: Option<String>,
    #[serde(default)]
    message: Option<String>,
}

#[derive(Deserialize)]
struct ResponsesIncompleteDetails {
    #[serde(default)]
    reason: Option<String>,
}

// 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);
        }

        // Handle OpenAI 5.6+ separately due to the Responses API protocol
        if self.provider == LlmProvider::openai_responses {
            return self.send_openai_responses(message);
        }

        // Handle Anthropic separately due to its unique Messages API protocol
        if self.provider == LlmProvider::anthropic {
            return self.send_anthropic(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)
    }

    // Sends a single message to OpenAI's Responses API (GPT-5.6+) and returns the response
    pub fn send_openai_responses(&self, message: &str) -> Result<String, io::Error> {
        let 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,
        }];

        let json_str = self.build_openai_responses_request(messages)?;
        self.send(&json_str)
    }

    // Sends a single message to Anthropic's Messages API and returns the response
    pub fn send_anthropic(&self, message: &str) -> Result<String, io::Error> {
        let 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,
        }];

        let json_str = self.build_anthropic_request(messages)?;
        self.send(&json_str)
    }

    // Builds the JSON body for an Anthropic Messages API request.  Any `system` role messages are lifted out of `messages` into the top-level `system` field.
    fn build_anthropic_request(&self, messages: Vec<ChatMessage>) -> Result<String, io::Error> {
        let (system_msgs, chat_msgs): (Vec<ChatMessage>, Vec<ChatMessage>) = messages.into_iter().partition(|m| m.role == "system");
        let system_text = system_msgs.iter().filter_map(|m| m.content.as_deref()).collect::<Vec<&str>>().join("\n\n");

        let request = ChatRequest_Anthropic {
            model: self.model_name.clone(),
            max_tokens: self.max_tokens.unwrap_or(ANTHROPIC_DEFAULT_MAX_TOKENS),
            messages: chat_msgs,
            system: if system_text.is_empty() { None } else { Some(system_text) },
        };

        serde_json::to_string(&request)
            .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e.to_string()))
    }

    // Extracts the assistant text from an Anthropic Messages API response body
    fn parse_anthropic(body: &str) -> Result<String, io::Error> {
        let res: AnthropicResponse = serde_json::from_str(body)
            .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e.to_string()))?;

        // Concatenate all text blocks (skip thinking blocks, etc.)
        let text: String = res.content.iter().filter(|c| c.content_type == "text").map(|c| c.text.as_deref().unwrap_or_default()).collect();
        if text.is_empty() {
            return Err(io::Error::new(io::ErrorKind::Other, "No text content in response"));
        }

        Ok(text)
    }

    // Returns the HTTP headers for a request, as each provider authenticates differently
    fn build_headers(&self) -> Vec<String> {
        if self.provider == LlmProvider::anthropic {
            return vec![
                format!("x-api-key: {}", self.api_key),
                format!("anthropic-version: {}", ANTHROPIC_VERSION),
                "Content-type: application/json".to_string(),
            ];
        }

        vec![
            format!("Authorization: Bearer {}", self.api_key),
            "Content-type: application/json".to_string(),
        ]
    }

    // Builds the error returned on a non-200 response.  Anthropic's error body names the offending field, so it is included for that provider.
    fn http_error(&self, status_code: u16, body: &str) -> io::Error {
        if self.provider == LlmProvider::anthropic {
            return io::Error::new(io::ErrorKind::Other, format!("HTTP error: {} - {}", status_code, body));
        }

        io::Error::new(io::ErrorKind::Other, format!("HTTP error: {}", status_code))
    }

    // Builds the JSON body for an OpenAI Responses API request
    fn build_openai_responses_request(&self, messages: Vec<ChatMessage>) -> Result<String, io::Error> {
        let request = ChatRequest_OpenAIResponses {
            model: self.model_name.clone(),
            input: messages,
            max_output_tokens: self.max_tokens,
            store: false,
        };

        serde_json::to_string(&request)
            .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e.to_string()))
    }

    // Extracts the assistant text from an OpenAI Responses API response body
    fn parse_openai_responses(body: &str) -> Result<String, io::Error> {
        let res: ResponsesApiResponse = serde_json::from_str(body)
            .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e.to_string()))?;

        if let Some(err) = res.error {
            return Err(io::Error::new(
                io::ErrorKind::Other,
                format!(
                    "OpenAI error ({}): {}",
                    err.code.unwrap_or_default(),
                    err.message.unwrap_or_default()
                ),
            ));
        }

        // Concatenate all output_text parts from all message items (skip reasoning items, etc.)
        let mut text = String::new();
        let mut refusal: Option<String> = None;
        for item in res.output.iter().filter(|i| i.item_type == "message") {
            for part in item.content.iter().flatten() {
                match part.content_type.as_str() {
                    "output_text" => text.push_str(part.text.as_deref().unwrap_or_default()),
                    "refusal" => refusal = part.refusal.clone(),
                    _ => {}
                }
            }
        }

        if !text.is_empty() {
            return Ok(text);
        }

        if let Some(r) = refusal {
            return Err(io::Error::new(io::ErrorKind::Other, format!("Model refused: {}", r)));
        }

        // No text: most commonly max_output_tokens was consumed entirely by reasoning
        if res.status.as_deref() == Some("incomplete") {
            let reason = res.incomplete_details
                .and_then(|d| d.reason)
                .unwrap_or_else(|| "unknown".to_string());
            return Err(io::Error::new(
                io::ErrorKind::Other,
                format!("Incomplete response with no output text (reason: {})", reason),
            ));
        }

        Err(io::Error::new(io::ErrorKind::Other, "No output text in response"))
    }

    // 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 header_lines = self.build_headers();
        let auth_header: Vec<&str> = header_lines.iter().map(|s| s.as_str()).collect();


        // 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(self.http_error(res.status_code(), &res.body()));
        }

        // Handle response based on provider
        if self.provider == LlmProvider::anthropic {
            // Anthropic returns a `content` array of typed blocks
            Self::parse_anthropic(&res.body())
        } else 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 if self.provider == LlmProvider::openai_responses {
            // OpenAI Responses API returns an `output` array of typed items
            Self::parse_openai_responses(&res.body())
        } 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> {
        self.send_with_tools_inner(message, ollama_api_key, None)
    }

    #[cfg(feature = "tools")]
    /// Same as `send_with_tools`, but gives up after `timeout` overall (all LLM requests and tool calls combined).
    ///
    /// The work runs on a worker thread, so the caller is released at the deadline even if a socket read stalls (the underlying HTTP client only enforces a connect timeout), and a panic inside the HTTP stack is returned as an `Err` instead of unwinding into the caller.  Returns `ErrorKind::TimedOut` on timeout.  The worker stops at its next iteration boundary, but a read that is genuinely hung will leave that thread blocked until the socket closes.
    pub fn send_with_tools_timeout(&self, message: &str, ollama_api_key: &str, timeout: std::time::Duration) -> Result<String, io::Error> {
        let deadline = std::time::Instant::now() + timeout;
        let (profile, message, api_key) = (self.clone(), message.to_string(), ollama_api_key.to_string());
        let (tx, rx) = std::sync::mpsc::channel();

        std::thread::Builder::new().name("sermo-llm".to_string()).spawn(move || {
            let _ = tx.send(profile.send_with_tools_inner(&message, &api_key, Some(deadline)));
        })?;

        match rx.recv_timeout(timeout) {
            Ok(res) => res,
            Err(std::sync::mpsc::RecvTimeoutError::Timeout) => Err(io::Error::new(io::ErrorKind::TimedOut, format!("LLM request timed out after {}s", timeout.as_secs_f32()))),
            Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => Err(io::Error::new(io::ErrorKind::Other, "LLM worker thread panicked")),
        }
    }

    #[cfg(feature = "tools")]
    fn send_with_tools_inner(&self, message: &str, ollama_api_key: &str, deadline: Option<std::time::Instant>) -> 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 {
            if deadline.map_or(false, |d| std::time::Instant::now() >= d) {
                return Err(io::Error::new(io::ErrorKind::TimedOut, "LLM request deadline reached"));
            }

            // 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 if self.provider == LlmProvider::openai_responses {
                self.build_openai_responses_request(messages.clone())?
            } else if self.provider == LlmProvider::anthropic {
                self.build_anthropic_request(messages.clone())?
            } 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 header_lines = self.build_headers();
            let auth_header: Vec<&str> = header_lines.iter().map(|s| s.as_str()).collect();

            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);
            // Bound each socket read by the time remaining, so the worker thread exits shortly after the deadline instead of hanging on a stalled server
            let mut http = match deadline {
                Some(d) => HttpClient::builder().browser().read_timeout(d.saturating_duration_since(std::time::Instant::now()).as_secs_f32().ceil() as u64).build_sync(),
                None => 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(self.http_error(res.status_code(), &res.body()));
            }

            // Parse response
            let assistant_message = if self.provider == LlmProvider::anthropic {
                ChatMessage {
                    role: "assistant".to_string(),
                    content: Some(Self::parse_anthropic(&res.body())?),
                    #[cfg(feature = "tools")]
                    tool_calls: None,
                    #[cfg(feature = "tools")]
                    tool_call_id: None,
                }
            } else 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 if self.provider == LlmProvider::openai_responses {
                ChatMessage {
                    role: "assistant".to_string(),
                    content: Some(Self::parse_openai_responses(&res.body())?),
                    #[cfg(feature = "tools")]
                    tool_calls: None,
                    #[cfg(feature = "tools")]
                    tool_call_id: None,
                }
            } 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();
                // Tools do network I/O through an HTTP client that can panic (eg. DNS failure), so contain it and hand the error back to the model
                let result = match tool_req.tool.as_str() {
                    "web_search" => std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| web_search.execute(&params_str))).unwrap_or_else(|_| Err(io::Error::new(io::ErrorKind::Other, "web_search failed unexpectedly (network unavailable?)"))),
                    "web_fetch" => std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| web_fetch.execute(&params_str))).unwrap_or_else(|_| Err(io::Error::new(io::ErrorKind::Other, "web_fetch failed unexpectedly (network unavailable?)"))),
                    _ => 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,
            9 => Self::openai_responses,
            _ => 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(),
            Self::openai_responses => "OpenAI 5.6+".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(),
            Self::openai_responses => "openai_responses".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..10 {
            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/openai/chat/completions".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::openai_responses => "https://api.openai.com/v1/responses".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,
            "openai_responses" => Self::openai_responses,
            _ => LlmProvider::other,
        }
    }
}


#[cfg(test)]
mod tests {
    use super::*;

    fn msg(role: &str, content: &str) -> ChatMessage {
        ChatMessage {
            role: role.to_string(),
            content: Some(content.to_string()),
            #[cfg(feature = "tools")]
            tool_calls: None,
            #[cfg(feature = "tools")]
            tool_call_id: None,
        }
    }

    #[test]
    fn anthropic_request_defaults_and_omits_nulls() {
        let profile = LlmProfile::from_str("anthropic", "claude-sonnet-4-5", "key", None, None);
        let v: serde_json::Value = serde_json::from_str(&profile.build_anthropic_request(vec![msg("user", "hi")]).unwrap()).unwrap();
        assert_eq!(v["max_tokens"], ANTHROPIC_DEFAULT_MAX_TOKENS);
        assert!(v.get("temperature").is_none());
        assert!(v.get("system").is_none());
        assert_eq!(v["messages"][0]["role"], "user");
    }

    #[test]
    fn anthropic_request_lifts_system_and_never_sends_temperature() {
        let profile = LlmProfile::from_str("anthropic", "claude-sonnet-4-5", "key", Some(1.7), Some(256));
        let v: serde_json::Value = serde_json::from_str(&profile.build_anthropic_request(vec![msg("system", "be nice"), msg("user", "hi")]).unwrap()).unwrap();
        assert_eq!(v["system"], "be nice");
        assert_eq!(v["max_tokens"], 256);
        assert!(v.get("temperature").is_none());
        assert_eq!(v["messages"].as_array().unwrap().len(), 1);
        assert_eq!(v["messages"][0]["role"], "user");
    }

    #[test]
    fn anthropic_headers() {
        let h = LlmProfile::from_str("anthropic", "m", "secret", None, None).build_headers();
        assert!(h.contains(&"x-api-key: secret".to_string()));
        assert!(h.contains(&format!("anthropic-version: {}", ANTHROPIC_VERSION)));
        assert!(!h.iter().any(|l| l.starts_with("Authorization")));
    }

    #[test]
    fn other_providers_headers_unchanged() {
        for p in ["openai", "ollama", "google", "xai", "groq", "openai_responses"] {
            let h = LlmProfile::from_str(p, "m", "secret", None, None).build_headers();
            assert_eq!(h, vec!["Authorization: Bearer secret".to_string(), "Content-type: application/json".to_string()]);
        }
    }

    #[test]
    fn anthropic_response_parsing() {
        let body = r#"{"id":"msg_1","type":"message","role":"assistant","content":[{"type":"thinking","thinking":"..."},{"type":"text","text":"Hello "},{"type":"text","text":"world"}],"stop_reason":"end_turn"}"#;
        assert_eq!(LlmProfile::parse_anthropic(body).unwrap(), "Hello world");
        assert!(LlmProfile::parse_anthropic(r#"{"content":[]}"#).is_err());
    }
}