tofu-llm 0.7.2

A command-line tool for interacting with LLMs
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
//! Tofu - A command-line tool for interacting with LLMs
//!
//! This library provides the core functionality for the Tofu CLI tool.

#![forbid(unsafe_code)]
#![warn(missing_docs)]

use colored::Colorize;
use dialoguer::Editor;
use dialoguer::Input;
use home::home_dir;
use indicatif::{ProgressBar, ProgressStyle};
use reqwest::Client;
use serde::{Deserialize, Serialize};
use std::error::Error;
use std::fs;
use std::io::Write;
use std::path::PathBuf;

mod theme;
use theme::TofuTheme;

/// Configuration loaded from config file
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ConfigFile {
    /// The LLM provider to use
    pub provider: String,
    /// The model to use
    pub model: String,
    /// Whether to JSON stream the response
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stream: Option<bool>,
    /// The system prompt to use
    #[serde(skip_serializing_if = "Option::is_none")]
    pub system_prompt: Option<String>,
}

/// Message in the conversation history
#[derive(Debug, Clone, Serialize, Deserialize)]
struct Message {
    role: String,
    content: String,
}

/// Configuration loaded from keys file
#[derive(Debug, Serialize, Deserialize)]
pub struct KeysFile {
    /// The Google API key
    pub google: Option<String>,
    /// The OpenAI API key
    pub openai: Option<String>,
    /// The Anthropic API key
    pub anthropic: Option<String>,
}

/// The main configuration for the Tofu application.
#[derive(Debug)]
pub struct Config {
    /// Whether to enable verbose output
    pub verbose: bool,
    /// Whether to enable interactive mode
    pub interactive: bool,
    /// Optional message string
    pub message: Option<String>,
    /// Whether to JSON stream the response
    pub stream: Option<bool>,
    /// Configuration loaded from file
    pub file: Option<ConfigFile>,
}

/// Runs the Tofu application with the given configuration.
/// # Arguments
/// * `config` - The configuration for the application
/// # Returns
/// Returns `Ok(())` on success, or an error if something went wrong.
/// Gets the path to the config file.
fn get_config_path() -> Result<PathBuf, Box<dyn Error>> {
    let config_dir = if cfg!(windows) {
        dirs::config_dir()
            .ok_or("Could not determine config directory")?
            .join("tofu")
    } else {
        home_dir()
            .ok_or("Could not determine home directory")?
            .join(".tofu")
    };

    // Create config directory if it doesn't exist
    if !config_dir.exists() {
        std::fs::create_dir_all(&config_dir)?;
    }

    Ok(config_dir.join("config.json"))
}

fn get_keys_path() -> Result<PathBuf, Box<dyn Error>> {
    let config_dir = if cfg!(windows) {
        dirs::config_dir()
            .ok_or("Could not determine config directory")?
            .join("tofu")
    } else {
        home_dir()
            .ok_or("Could not determine home directory")?
            .join(".tofu")
    };

    // Create config directory if it doesn't exist
    if !config_dir.exists() {
        std::fs::create_dir_all(&config_dir)?;
    }

    Ok(config_dir.join("keys.json"))
}

/// Loads the configuration from file.
pub fn load_config(profile: Option<&str>) -> Result<ConfigFile, Box<dyn Error>> {
    let config_path = get_config_path()?;

    if !config_path.exists() {
        // If config file doesn't exist, create it with default values as a multi-profile map
        let default_config = ConfigFile {
            provider: String::from("pollinations"),
            model: String::from("openai"),
            stream: Some(true),
            system_prompt: Some(String::from("You are a helpful assistant named Tofu.")),
        };
        let gemini_config = ConfigFile {
            provider: String::from("google"),
            model: String::from("gemini-2.5-flash"),
            stream: None,
            system_prompt: None,
        };
        let openai_config = ConfigFile {
            provider: String::from("openai"),
            model: String::from("gpt-5-mini"),
            stream: None,
            system_prompt: None,
        };
        let anthropic_config = ConfigFile {
            provider: String::from("anthropic"),
            model: String::from("claude-sonnet-4-6"),
            stream: None,
            system_prompt: None,
        };
        let ollama_config = ConfigFile {
            provider: String::from("ollama"),
            model: String::from("llama3"),
            stream: None,
            system_prompt: None,
        };
        let profiles_json = serde_json::json!({
            "default": &default_config,
            "gemini": &gemini_config,
            "openai": &openai_config,
            "anthropic": &anthropic_config,
            "ollama": &ollama_config
        });
        let config_json = serde_json::to_string_pretty(&profiles_json)?;
        std::fs::write(&config_path, config_json)?;
        return Ok(default_config);
    }

    let config_content = fs::read_to_string(&config_path)?;

    // Try to parse as either legacy single-profile or multi-profile config
    let root_value: serde_json::Value = serde_json::from_str(&config_content)
        .map_err(|e| format!("Failed to parse config file: {}", e))?;

    if let Some(obj) = root_value.as_object() {
        // region deprecated
        // remove: upon 1.0.0 release
        // reason: legacy config files were only used in very early beta versions
        let looks_like_legacy = obj.contains_key("provider")
            || obj.contains_key("model")
            || obj.contains_key("stream")
            || obj.contains_key("system_prompt");

        if looks_like_legacy {
            // Legacy single-profile config
            println!("WARNING: legacy config is deprecated");
            let cfg: ConfigFile = serde_json::from_value(root_value)
                .map_err(|e| format!("Failed to parse legacy config: {}", e))?;
            if cfg.provider.is_empty() || cfg.model.is_empty() {
                return Err("Invalid config: provider and model must not be empty".into());
            }
            return Ok(cfg);
        }
        //endregion deprecated

        // Multi-profile config
        let (selected_name, selected_value) = if let Some(name) = profile {
            match obj.get(name) {
                Some(v) => (name.to_string(), v.clone()),
                None => {
                    let available = obj.keys().cloned().collect::<Vec<_>>().join(", ");
                    return Err(
                        format!("Profile '{}' not found. Available: {}", name, available).into(),
                    );
                }
            }
        } else {
            if let Some(v) = obj.get("default") {
                (String::from("default"), v.clone())
            } else {
                match obj.iter().next() {
                    Some((k, v)) => (k.clone(), v.clone()),
                    None => return Err("Config file contains no profiles".into()),
                }
            }
        };

        let mut cfg: ConfigFile = serde_json::from_value(selected_value).map_err(|e| {
            format!(
                "Failed to parse selected profile '{}': {}",
                selected_name, e
            )
        })?;

        // If selected profile is not the default, fall back to default for None values
        if selected_name != "default" {
            if let Some(default_value) = obj.get("default") {
                let default_cfg: ConfigFile = serde_json::from_value(default_value.clone())
                    .map_err(|e| format!("Failed to parse default profile: {}", e))?;
                if cfg.stream.is_none() {
                    cfg.stream = default_cfg.stream;
                }
                if cfg.system_prompt.is_none() {
                    cfg.system_prompt = default_cfg.system_prompt;
                }
            }
        }

        if cfg.provider.is_empty() || cfg.model.is_empty() {
            return Err("Invalid config: provider and model must not be empty".into());
        }
        return Ok(cfg);
    }

    Err("Invalid config: root must be a JSON object".into())
}

/// Loads the keys file from the default location.
pub fn load_keys() -> Result<KeysFile, Box<dyn Error>> {
    let keys_path = get_keys_path()?;

    if !keys_path.exists() {
        // If keys file doesn't exist, create it with default values as a multi-profile map
        let default_keys = serde_json::json!({
            "google": "",
            "openai": "",
            "anthropic": ""
        });

        let keys_json = serde_json::to_string_pretty(&default_keys)?;
        std::fs::write(&keys_path, keys_json)?;
        return Ok(KeysFile {
            google: None,
            openai: None,
            anthropic: None,
        });
    }

    let keys_content = fs::read_to_string(&keys_path)?;
    let keys_json: serde_json::Value = serde_json::from_str(&keys_content)?;
    let keys: KeysFile = serde_json::from_value(keys_json)?;

    return Ok(keys);
}

/// Opens the config file in the default editor.
///
/// # Returns
/// Returns `Ok(())` on success, or an error if something went wrong.
pub fn open_config() -> Result<(), Box<dyn Error>> {
    println!("Opening config file...");
    let config_path = get_config_path()?;

    // Ensure config file exists by trying to load it or create a default one
    if let Err(e) = load_config(None) {
        eprintln!("Warning: {}", e);
        eprintln!("Opening editor to fix the config file...");
    }

    // Open the config file in the default editor
    let editor = std::env::var("EDITOR").unwrap_or_else(|_| {
        if cfg!(windows) {
            String::from("notepad")
        } else {
            String::from("nano")
        }
    });

    let status = std::process::Command::new(editor)
        .arg(&config_path)
        .status()?;

    if !status.success() {
        return Err(format!("Editor exited with status: {}", status).into());
    }

    // Try to load the config after editing, but don't fail if it's still invalid
    if let Err(e) = load_config(None) {
        eprintln!("Warning: The config file is still invalid: {}", e);
        eprintln!("Please fix the config file and try again.");
    }

    Ok(())
}

/// Gets the currently active profile name.
///
/// # Arguments
/// * `current_config` - The currently loaded configuration to compare against
/// # Returns
/// Returns the name of the active profile as a String, or an error if something went wrong.
fn get_active_profile(current_config: &ConfigFile) -> Result<String, Box<dyn Error>> {
    let config_path = get_config_path()?;
    let config_content = fs::read_to_string(&config_path)?;

    let root_value: serde_json::Value = serde_json::from_str(&config_content)
        .map_err(|e| format!("Failed to parse config file: {}", e))?;

    if let Some(obj) = root_value.as_object() {
        // Check each profile to see which one matches the current config
        for (profile_name, profile_value) in obj.iter() {
            if let Ok(profile_config) = serde_json::from_value::<ConfigFile>(profile_value.clone())
            {
                if profile_config.provider == current_config.provider
                    && profile_config.model == current_config.model
                {
                    return Ok(profile_name.clone());
                }
            }
        }

        // If no exact match found, return "default" as fallback
        Ok("default".to_string())
    } else {
        Err("Invalid config format - expected JSON object".into())
    }
}

/// Lists all available profiles from the config file.
///
/// # Returns
/// Returns `Ok(())` on success, or an error if something went wrong.
fn list_profiles() -> Result<(), Box<dyn Error>> {
    let path = get_config_path()?;
    let config = fs::read_to_string(&path)?;

    // Parse the JSON config to get root keys (profile names)
    let root_value: serde_json::Value =
        serde_json::from_str(&config).map_err(|e| format!("Failed to parse config file: {}", e))?;

    println!("{}", "Available profiles:".bold());
    if let Some(obj) = root_value.as_object() {
        if obj.is_empty() {
            println!("  No profiles found");
        } else {
            for key in obj.keys() {
                println!("  {}", key);
            }
        }
    } else {
        eprintln!("  Invalid config format - expected JSON object");
    }
    Ok(())
}

/// Opens the keys file in the default editor.
pub fn open_keys() -> Result<(), Box<dyn Error>> {
    println!("Opening keys file...");
    let config_path = get_keys_path()?;

    // Ensure keys file exists by trying to load it or create a default one
    if let Err(e) = load_keys() {
        eprintln!("Warning: {}", e);
        eprintln!("Opening editor to fix the keys file...");
    }

    // Open the file in the default editor
    let editor = std::env::var("EDITOR").unwrap_or_else(|_| {
        if cfg!(windows) {
            String::from("notepad")
        } else {
            String::from("nano")
        }
    });

    let status = std::process::Command::new(editor)
        .arg(&config_path)
        .status()?;

    if !status.success() {
        return Err(format!("Editor exited with status: {}", status).into());
    }

    Ok(())
}

/// Runs the Tofu application with the given configuration.
/// # Arguments
/// * `config` - The configuration for the application
/// # Returns
/// Returns `Ok(())` on success, or an error if something went wrong.
/// Runs the Tofu application with the given configuration asynchronously.
/// # Arguments
/// * `config` - The configuration for the application
/// # Returns
/// Returns `Ok(())` on success, or an error if something went wrong.
pub async fn run(config: Config) -> Result<(), Box<dyn Error>> {
    if config.verbose {
        println!(
            "Tofu v{} initialized (verbose mode)",
            env!("CARGO_PKG_VERSION")
        );
        println!("{:#?}", config);
    }

    if config.interactive {
        run_interactive(config).await
    } else {
        let message = config.message.as_ref().unwrap_or(&String::new()).clone();
        send_message(&message, &config, vec![]).await?;
        Ok(())
    }
}

async fn run_interactive(mut config: Config) -> Result<(), Box<dyn Error>> {
    let mut conversation_history = vec![];

    println!(
        "{}",
        format!("Tofu {}", env!("CARGO_PKG_VERSION")).bold().blue()
    );
    println!(
        "{}",
        "Ctrl+C or /q to exit • /? for commands".italic().dimmed()
    );

    loop {
        let input: Result<String, _> = Input::with_theme(&TofuTheme::default()).interact_text();

        match input {
            Ok(mut line) => {
                line = line.trim().to_string();
                if line.is_empty() {
                    continue;
                }

                // Check for commands starting with /
                if line.starts_with('/') || line.starts_with("'''") || line.starts_with("\"\"\"") {
                    let (should_exit, new_config, message_to_send) =
                        handle_command(line.as_str(), &mut conversation_history, &config)?;
                    if let Some(new_file_config) = new_config {
                        config.file = Some(new_file_config);
                    }
                    if should_exit {
                        break; // Exit the loop if command returns true
                    }
                    if let Some(message) = message_to_send {
                        // Process the multiline message like a regular input
                        line = message;
                    } else {
                        continue; // Skip sending to model for commands that don't return a message
                    }
                }

                // Add user message to conversation history
                conversation_history.push(Message {
                    role: "user".to_string(),
                    content: line.to_string(),
                });

                // If length > 100 messages, remove the oldest message (keep system prompt)
                if conversation_history.len() > 100 {
                    conversation_history.remove(1);
                }

                // Send message and get response
                match send_message(line.as_str(), &config, conversation_history.clone()).await {
                    Ok(response_content) => {
                        // Add assistant response to conversation history
                        conversation_history.push(Message {
                            role: "assistant".to_string(),
                            content: response_content.clone(),
                        });
                    }
                    Err(e) => {
                        if e.to_string().contains("localhost:11434") {
                            eprintln!("{}", "Error: Ollama server not running".red());
                        } else {
                            eprintln!("{}", format!("Error: {}", e).red());
                        }
                        // Remove the failed message from history
                        if !conversation_history.is_empty() {
                            conversation_history.pop();
                        }
                        continue;
                    }
                }
            }
            Err(e) => {
                eprintln!("{}", format!("Error reading input: {}", e).red());
                break;
            }
        }
    }

    Ok(())
}

/// Handles special commands starting with /
/// Returns a tuple: (should_exit, new_config_option, message_to_send)
fn handle_command(
    command: &str,
    conversation_history: &mut Vec<Message>,
    config: &Config,
) -> Result<(bool, Option<ConfigFile>, Option<String>), Box<dyn Error>> {
    match command {
        "/exit" | "/quit" | "/q" | "/bye" => Ok((true, None, None)),
        "/help" | "/h" | "/?" | "/commands" | "/cmds" => {
            println!("{}", "Available commands:".bold());
            println!("  /help, /            - Show this help message");
            println!("  /exit, /quit, /q    - Exit the program");
            println!(
                "  /profile [name]     - Switch to a different config profile. If name not provided, lists profiles"
            );
            println!(
                "  /model <name>, /m <name> - Switch to a different model (without changing profile)"
            );
            println!("  /listprofiles, /lsp - List all available profiles");
            println!("  /clear              - Clear conversation history");
            println!("  /keys               - Open the API keys file");
            println!("  /show, /info        - Display profile & model info");
            println!("  /multiline, /ml, // - Enter multiline input mode");
            println!("* Most Ollama commands also work, such as \"\"\" and /bye.");
            Ok((false, None, None))
        }
        "/clear" => {
            conversation_history.clear();
            println!("{}", "Conversation history cleared.".blue());
            Ok((false, None, None))
        }
        "/keys" | "/key" | "/apikeys" | "/apikey" => {
            open_keys()?;
            Ok((false, None, None))
        }
        cmd if cmd.starts_with("/profile") || cmd.starts_with("/p") => {
            let parts: Vec<&str> = command.split_whitespace().collect();
            if parts.len() != 2 {
                if let Err(e) = list_profiles() {
                    eprintln!("{}", format!("Error listing profiles: {}", e).red());
                } else {
                    println!("Usage: /profile [profile_name]");
                }
                return Ok((false, None, None));
            }

            let profile_name = parts[1];
            match load_config(Some(profile_name)) {
                Ok(new_config) => {
                    println!(
                        "{}",
                        format!("Switched to profile '{}'", profile_name).green()
                    );
                    Ok((false, Some(new_config), None))
                }
                Err(e) => {
                    eprintln!(
                        "{}",
                        format!("Failed to switch to profile '{}': {}", profile_name, e).red()
                    );
                    Ok((false, None, None))
                }
            }
        }
        cmd if cmd.starts_with("/model") || cmd.starts_with("/m") => {
            let parts: Vec<&str> = command.split_whitespace().collect();
            if parts.len() != 2 {
                eprintln!("{}", "Usage: /model <model_name>".red());
                return Ok((false, None, None));
            }

            let new_model = parts[1];

            // Get current config and create a new one with updated model
            if let Some(mut current_config) = config.file.clone() {
                current_config.model = new_model.to_string();
                println!("{}", format!("Switched to model '{}'", new_model).green());
                Ok((false, Some(current_config), None))
            } else {
                eprintln!("{}", "No configuration loaded".red());
                Ok((false, None, None))
            }
        }
        "/show" | "/info" | "/s" | "/i" => {
            match config.file.as_ref() {
                Some(current_config) => match get_active_profile(current_config) {
                    Ok(profile) => println!("Profile: {}", profile),
                    Err(_) => println!("Profile: unknown"),
                },
                None => println!("Profile: unknown (no config loaded)"),
            }
            if let Some(current_config) = config.file.as_ref() {
                println!("Model: {}", current_config.model);
            }
            Ok((false, None, None))
        }
        "/listprofiles" | "/lsp" => {
            if let Err(e) = list_profiles() {
                eprintln!("{}", format!("Error listing profiles: {}", e).red());
            }
            Ok((false, None, None))
        }
        "/multiline" | "/ml" | "//" | "'''" | "\"\"\"" => {
            if let Some(multiline_input) = Editor::new().edit("").unwrap() {
                if !multiline_input.trim().is_empty() {
                    println!("{}\n", multiline_input);
                    // Return the multiline input as a message to be processed
                    return Ok((false, None, Some(multiline_input)));
                } else {
                    println!("{}", "Empty input - cancelled".yellow());
                }
            } else {
                eprintln!("{}", "Cancelled".red());
            }
            Ok((false, None, None))
        }
        _ => {
            eprintln!(
                "{}",
                format!(
                    "Unknown command: {}. Type /help for available commands.",
                    command
                )
                .red()
            );
            Ok((false, None, None))
        }
    }
}

async fn send_message(
    _message: &str,
    config: &Config,
    history: Vec<Message>,
) -> Result<String, Box<dyn Error>> {
    let spinner = ProgressBar::new_spinner();
    spinner.enable_steady_tick(std::time::Duration::from_millis(100));
    spinner.set_style(
        ProgressStyle::with_template("{spinner:.blue} {msg} {elapsed:.bold}")
            .unwrap()
            .tick_chars("⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"),
    );
    spinner.set_message("Thinking...");

    // Build messages array with history
    let mut messages = vec![];

    if let Some(file) = &config.file {
        if let Some(system_prompt) = &file.system_prompt {
            messages.push(serde_json::json!({ "role": "system", "content": system_prompt }));
        }
    }

    for msg in history {
        messages.push(serde_json::json!({ "role": msg.role, "content": msg.content }));
    }

    let body = if let Some(file) = &config.file {
        serde_json::json!({
            "model": file.model,
            "messages": messages,
            "stream": config.stream,
        })
    } else {
        return Err("No configuration file found".to_string().into());
    };

    // Send the message
    let client = Client::new();

    if config.verbose {
        dbg!(&body);
    }

    let (url, auth_header) = if let Some(file) = &config.file {
        match file.provider.as_str() {
            "pollinations" => (
                "https://gen.pollinations.ai/v1/chat/completions",
                Some("Bearer pk_y1jVZsGNdFYuc12n".to_string()), // NOTE: public key; in the future, other Pollinations key options will be available.
            ),
            "google" => (
                "https://generativelanguage.googleapis.com/v1beta/openai/chat/completions",
                Some(format!("Bearer {}", load_keys().unwrap().google.unwrap())),
            ),
            "openai" => (
                "https://api.openai.com/v1/chat/completions",
                Some(format!("Bearer {}", load_keys().unwrap().openai.unwrap())),
            ),
            "anthropic" => (
                "https://api.anthropic.com/v1/chat/completions",
                Some(format!(
                    "Bearer {}",
                    load_keys().unwrap().anthropic.unwrap()
                )),
            ),
            "ollama" => (
                "http://localhost:11434/v1/chat/completions",
                None, // Ollama typically doesn't require authentication for local setup
            ),
            provider => {
                return Err(format!("Unsupported provider: {}", provider).into());
            }
        }
    } else {
        return Err("No configuration file found".to_string().into());
    };

    let mut request = client
        .post(url)
        .header("Content-Type", "application/json")
        .body(serde_json::to_string(&body)?);

    if let Some(auth) = auth_header {
        request = request.header("Authorization", auth);
    }

    if config
        .file
        .as_ref()
        .map(|f| f.provider == "anthropic")
        .unwrap_or(false)
    {
        request = request.header("anthropic-version", "2023-06-01");
    }

    let mut response = request.send().await?;

    if !response.status().is_success() {
        let error_msg = format!("Request failed with status: {}", response.status());

        // Provide more helpful error message for Ollama connection issues
        if config
            .file
            .as_ref()
            .map(|f| f.provider == "ollama")
            .unwrap_or(false)
        {
            let status = response.status().as_u16();
            if status == 101 || status == 0 {
                return Err("Ollama server is not running. Please make sure Ollama is installed and running on localhost:11434. You can install Ollama from https://ollama.ai/".into());
            }
        }

        return Err(error_msg.into());
    }

    spinner.finish_and_clear();

    if config.stream == Some(true) {
        spinner.finish_and_clear();
        let mut buffer = String::new();
        let mut response_content = String::new();
        let mut done = false;
        while let Some(chunk) = response.chunk().await? {
            let chunk_str = String::from_utf8_lossy(&chunk);
            buffer.push_str(&chunk_str);

            loop {
                if let Some(newline_idx) = buffer.find('\n') {
                    let line = buffer[..newline_idx].trim_end_matches('\r').to_string();
                    buffer.drain(..=newline_idx);
                    if line.is_empty() {
                        continue;
                    }

                    if line.starts_with("data: ") {
                        let payload = line[6..].trim();
                        if payload == "[DONE]" {
                            done = true;
                            println!(); // Fixes issue on Linux where % sign shows at end
                            break;
                        } else {
                            if let Ok(v) = serde_json::from_str::<serde_json::Value>(payload) {
                                if let Some(choices) = v.get("choices").and_then(|c| c.as_array()) {
                                    for choice in choices {
                                        if let Some(delta) = choice.get("delta") {
                                            if let Some(content) =
                                                delta.get("content").and_then(|c| c.as_str())
                                            {
                                                print!("{}", content);
                                                let _ = std::io::stdout().flush();
                                                response_content.push_str(content);
                                            }
                                        } else if let Some(content) = choice
                                            .get("message")
                                            .and_then(|m| m.get("content"))
                                            .and_then(|c| c.as_str())
                                        {
                                            print!("{}", content);
                                            let _ = std::io::stdout().flush();
                                            response_content.push_str(content);
                                        }
                                    }
                                }
                            }
                        }
                    } else if config.verbose {
                        eprintln!("{}", line);
                    }
                } else {
                    break;
                }
            }

            if done {
                break;
            }
        }
        Ok(response_content)
    } else {
        let response_text = response.text().await?;
        let json: serde_json::Value = serde_json::from_str(&response_text)?;
        let content = json["choices"][0]["message"]["content"]
            .as_str()
            .unwrap_or("")
            .replace("\\n", "\n")
            .trim_matches('"')
            .to_string();
        spinner.finish_and_clear();
        println!("\n{}\n", content);
        Ok(content)
    }
}

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

    #[tokio::test]
    async fn test_run() {
        let config = Config {
            verbose: false,
            interactive: false,
            message: Some(String::from("Hello, world!")),
            stream: Some(false),
            file: Some(ConfigFile {
                provider: String::from("pollinations"),
                model: String::from("openai"),
                stream: Some(false),
                system_prompt: Some(String::from("You are a helpful assistant named Tofu.")),
            }),
        };
        let result = run(config).await;
        assert!(result.is_ok());
    }
}