bigtext 0.19.1

Free editor for huge text and log files (1-50+ GB): opens them without loading them into memory, 4 GB/s search, atomic save
Documentation
//! The AI assistant's core. A model never reads the file: it turns a request ("find all the
//! errors") into calls of BigText's own tools, BigText runs them on this computer and gives the
//! model only short, bounded results. Nothing is sent anywhere until the user sets up a
//! provider and asks something.
//!
//! - [`chat`]: a conversation, the same for every provider;
//! - [`anthropic`] and [`openai`]: the two protocols, which cover the popular cloud providers
//!   and the servers that run models on this computer (Ollama, LM Studio, llama.cpp, vLLM);
//! - [`http`]: requests, errors, retries and streamed answers;
//! - [`fake`]: a scripted server for tests and the self-test.

pub mod agent;
pub mod anthropic;
pub mod chat;
pub mod config;
pub mod fake;
pub mod http;
pub mod keys;
pub mod openai;
pub mod privacy;
pub mod profile;
pub mod prompt;
pub mod tools;

use crate::jobs::CancelToken;
use chat::{Event, Reply, Request};
pub use http::AiError;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Protocol {
    /// Anthropic's Messages API.
    Anthropic,
    /// The chat completions API that OpenAI made and most other providers and local servers
    /// speak too.
    OpenAi,
}

/// A provider BigText knows: its protocol, address, key variable and (for Anthropic) model.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Preset {
    pub id: &'static str,
    pub name: &'static str,
    pub protocol: Protocol,
    pub url: &'static str,
    /// The model chosen until the user picks one (empty: pick from the provider's list).
    pub model: &'static str,
    /// The environment variable that holds the key (empty: none).
    pub env: &'static str,
    /// A key is needed (servers on this computer need none).
    pub needs_key: bool,
}

const fn cloud(
    id: &'static str,
    name: &'static str,
    protocol: Protocol,
    url: &'static str,
    model: &'static str,
    env: &'static str,
) -> Preset {
    Preset {
        id,
        name,
        protocol,
        url,
        model,
        env,
        needs_key: true,
    }
}

const fn local(id: &'static str, name: &'static str, url: &'static str) -> Preset {
    Preset {
        id,
        name,
        protocol: Protocol::OpenAi,
        url,
        model: "",
        env: "",
        needs_key: false,
    }
}

/// The providers in the settings, cloud first. Model names other than Anthropic's default
/// come from each provider's model list, so they never go stale in the code.
pub const PRESETS: &[Preset] = &[
    cloud(
        "anthropic",
        "Anthropic (Claude)",
        Protocol::Anthropic,
        "https://api.anthropic.com/v1",
        "claude-opus-5-5",
        "ANTHROPIC_API_KEY",
    ),
    cloud(
        "openai",
        "OpenAI",
        Protocol::OpenAi,
        "https://api.openai.com/v1",
        "",
        "OPENAI_API_KEY",
    ),
    cloud(
        "gemini",
        "Google Gemini",
        Protocol::OpenAi,
        "https://generativelanguage.googleapis.com/v1beta/openai",
        "",
        "GEMINI_API_KEY",
    ),
    cloud(
        "mistral",
        "Mistral",
        Protocol::OpenAi,
        "https://api.mistral.ai/v1",
        "",
        "MISTRAL_API_KEY",
    ),
    cloud(
        "deepseek",
        "DeepSeek",
        Protocol::OpenAi,
        "https://api.deepseek.com",
        "",
        "DEEPSEEK_API_KEY",
    ),
    cloud(
        "xai",
        "xAI (Grok)",
        Protocol::OpenAi,
        "https://api.x.ai/v1",
        "",
        "XAI_API_KEY",
    ),
    cloud(
        "groq",
        "Groq",
        Protocol::OpenAi,
        "https://api.groq.com/openai/v1",
        "",
        "GROQ_API_KEY",
    ),
    cloud(
        "openrouter",
        "OpenRouter",
        Protocol::OpenAi,
        "https://openrouter.ai/api/v1",
        "",
        "OPENROUTER_API_KEY",
    ),
    cloud(
        "qwen",
        "Qwen (DashScope)",
        Protocol::OpenAi,
        "https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
        "",
        "DASHSCOPE_API_KEY",
    ),
    cloud(
        "moonshot",
        "Kimi (Moonshot)",
        Protocol::OpenAi,
        "https://api.moonshot.cn/v1",
        "",
        "MOONSHOT_API_KEY",
    ),
    cloud(
        "zhipu",
        "GLM (Zhipu)",
        Protocol::OpenAi,
        "https://open.bigmodel.cn/api/paas/v4",
        "",
        "ZHIPUAI_API_KEY",
    ),
    local("ollama", "Ollama (local)", "http://localhost:11434/v1"),
    local("lmstudio", "LM Studio (local)", "http://localhost:1234/v1"),
    local("llamacpp", "llama.cpp (local)", "http://localhost:8080/v1"),
    local("vllm", "vLLM (local)", "http://localhost:8000/v1"),
    // Any other OpenAI-compatible server; a key is used when one is given.
    Preset {
        id: "custom",
        name: "Other (OpenAI-compatible)",
        protocol: Protocol::OpenAi,
        url: "",
        model: "",
        env: "",
        needs_key: false,
    },
];

pub fn preset(id: &str) -> Option<&'static Preset> {
    PRESETS.iter().find(|p| p.id == id)
}

/// A provider as set up: address, model and key.
#[derive(Clone, PartialEq)]
pub struct Provider {
    /// The preset it started from.
    pub id: String,
    pub protocol: Protocol,
    pub url: String,
    pub model: String,
    pub key: Option<String>,
    /// The workspace an Anthropic organization key works in (empty: none, or
    /// ANTHROPIC_WORKSPACE_ID); see [`Provider::workspace`].
    pub workspace: String,
}

impl std::fmt::Debug for Provider {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // Never the key.
        f.debug_struct("Provider")
            .field("id", &self.id)
            .field("protocol", &self.protocol)
            .field("url", &self.url)
            .field("model", &self.model)
            .field("key", &self.key.as_ref().map(|_| "…"))
            .field("workspace", &self.workspace)
            .finish()
    }
}

impl Provider {
    pub fn from_preset(p: &Preset) -> Provider {
        Provider {
            id: p.id.into(),
            protocol: p.protocol,
            url: p.url.into(),
            model: p.model.into(),
            key: None,
            workspace: String::new(),
        }
    }

    /// A server on this computer: no proxy, and nothing leaves the computer.
    pub fn is_local(&self) -> bool {
        http::is_local(&self.url)
    }

    /// The address without a trailing slash.
    pub fn base(&self) -> &str {
        self.url.trim().trim_end_matches('/')
    }

    fn key(&self) -> Option<&str> {
        self.key.as_deref().map(str::trim).filter(|k| !k.is_empty())
    }

    /// The workspace to name in each request, for an Anthropic API key that belongs to the
    /// organization rather than to one workspace (Anthropic answers 400 without it): the one set
    /// up, else ANTHROPIC_WORKSPACE_ID, as Anthropic's own tools read it.
    pub fn workspace(&self) -> Option<String> {
        if self.protocol != Protocol::Anthropic {
            return None;
        }
        workspace_or(
            &self.workspace,
            std::env::var("ANTHROPIC_WORKSPACE_ID").ok(),
        )
    }

    /// Why requests cannot be sent yet, if they cannot.
    pub fn check(&self) -> Result<(), AiError> {
        if self.base().is_empty() {
            return Err(AiError::Setup("Enter the provider's address.".into()));
        }
        if !self.base().starts_with("http://") && !self.base().starts_with("https://") {
            return Err(AiError::Setup(
                "The address must start with http:// or https://.".into(),
            ));
        }
        if self.model.trim().is_empty() {
            return Err(AiError::Setup("Choose a model.".into()));
        }
        let needs_key = preset(&self.id).is_some_and(|p| p.needs_key) && !self.is_local();
        if needs_key && self.key().is_none() {
            return Err(AiError::Setup("Enter the provider's API key.".into()));
        }
        Ok(())
    }

    /// Sends `req` (with `req.model` replaced by this provider's model when empty) and streams
    /// the answer to `on_event`. Busy providers are tried again; see [`http::with_retries`].
    pub fn send(
        &self,
        req: &Request,
        cancel: &CancelToken,
        on_event: &mut dyn FnMut(Event),
    ) -> Result<Reply, AiError> {
        self.check()?;
        let mut req = *req;
        if req.model.is_empty() {
            req.model = self.model.trim();
        }
        let workspace = self.workspace();
        http::with_retries(cancel, || match self.protocol {
            Protocol::Anthropic => anthropic::send(
                self.base(),
                self.key(),
                workspace.as_deref(),
                &req,
                cancel,
                on_event,
            ),
            Protocol::OpenAi => openai::send(self.base(), self.key(), &req, cancel, on_event),
        })
    }

    /// The provider's models, sorted.
    pub fn models(&self) -> Result<Vec<String>, AiError> {
        if self.base().is_empty() {
            return Err(AiError::Setup("Enter the provider's address.".into()));
        }
        match self.protocol {
            Protocol::Anthropic => {
                anthropic::models(self.base(), self.key(), self.workspace().as_deref())
            }
            Protocol::OpenAi => openai::models(self.base(), self.key()),
        }
    }
}

/// `set` when it is not blank, else `env` when that is not.
fn workspace_or(set: &str, env: Option<String>) -> Option<String> {
    let set = set.trim();
    if !set.is_empty() {
        return Some(set.to_string());
    }
    env.map(|w| w.trim().to_string()).filter(|w| !w.is_empty())
}

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

    #[test]
    fn the_workspace_set_up_wins_over_the_environment() {
        assert_eq!(workspace_or(" w1 ", Some("w2".into())), Some("w1".into()));
        assert_eq!(workspace_or("", Some(" w2 ".into())), Some("w2".into()));
        assert_eq!(workspace_or(" ", Some(" ".into())), None);
        assert_eq!(workspace_or("", None), None);
        let mut o = Provider::from_preset(preset("ollama").unwrap());
        o.workspace = "w1".into();
        assert_eq!(o.workspace(), None);
        let mut a = Provider::from_preset(preset("anthropic").unwrap());
        a.workspace = "w1".into();
        assert_eq!(a.workspace(), Some("w1".into()));
    }

    #[test]
    fn presets_are_unique_and_complete() {
        let mut ids = std::collections::HashSet::new();
        for p in PRESETS {
            assert!(ids.insert(p.id), "{} twice", p.id);
            assert!(!p.name.is_empty());
            if p.id != "custom" {
                assert!(p.url.starts_with("http"), "{}", p.id);
                assert_eq!(!p.needs_key, http::is_local(p.url), "{}", p.id);
            }
        }
        assert_eq!(preset("anthropic").unwrap().model, "claude-opus-5-5");
    }

    #[test]
    fn setup_is_checked_before_sending() {
        let mut p = Provider::from_preset(preset("anthropic").unwrap());
        assert!(matches!(p.check(), Err(AiError::Setup(_))));
        p.key = Some("sk-test".into());
        assert_eq!(p.check(), Ok(()));
        let mut o = Provider::from_preset(preset("ollama").unwrap());
        assert!(matches!(o.check(), Err(AiError::Setup(_))));
        o.model = "llama".into();
        assert_eq!(o.check(), Ok(()));
        o.url = "localhost:11434".into();
        assert!(matches!(o.check(), Err(AiError::Setup(_))));
        assert!(!format!("{p:?}").contains("sk-test"));
    }
}