bigtext 0.19.0

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
//! A conversation with a model, the same for every provider: messages made of blocks (text,
//! tool calls and their results), the request BigText sends and the reply it gets back. The
//! protocol modules turn these into each provider's JSON and back.

use serde_json::Value;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Role {
    User,
    Assistant,
}

#[derive(Clone, Debug, PartialEq)]
pub enum Block {
    Text(String),
    /// The model asks BigText to run a tool.
    ToolUse {
        id: String,
        name: String,
        input: Value,
    },
    /// What a tool gave back, for the model.
    ToolResult {
        id: String,
        content: String,
        is_error: bool,
    },
    /// A block the provider wants back exactly as it came: Anthropic's thinking blocks, which
    /// are signed and must be sent back unchanged with the rest of the conversation.
    Opaque(Value),
}

#[derive(Clone, Debug, PartialEq)]
pub struct Message {
    pub role: Role,
    pub blocks: Vec<Block>,
}

impl Message {
    pub fn user(text: impl Into<String>) -> Message {
        Message {
            role: Role::User,
            blocks: vec![Block::Text(text.into())],
        }
    }

    pub fn assistant(text: impl Into<String>) -> Message {
        Message {
            role: Role::Assistant,
            blocks: vec![Block::Text(text.into())],
        }
    }

    /// The text blocks, joined.
    pub fn text(&self) -> String {
        let mut out = String::new();
        for b in &self.blocks {
            if let Block::Text(t) = b {
                if !out.is_empty() && !t.is_empty() {
                    out.push('\n');
                }
                out.push_str(t);
            }
        }
        out
    }

    /// The tool calls in this message: (id, name, input).
    pub fn tool_uses(&self) -> Vec<(&str, &str, &Value)> {
        self.blocks
            .iter()
            .filter_map(|b| match b {
                Block::ToolUse { id, name, input } => Some((id.as_str(), name.as_str(), input)),
                _ => None,
            })
            .collect()
    }
}

/// A tool the model may call: its name, what it does, and its arguments as a JSON schema.
#[derive(Clone, Debug, PartialEq)]
pub struct ToolSpec {
    pub name: String,
    pub description: String,
    pub schema: Value,
}

/// How long the model may think before it answers (Anthropic's `effort`; other protocols leave
/// it to the model).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Effort {
    Low,
    Medium,
    High,
}

impl Effort {
    pub const ALL: [Effort; 3] = [Effort::Low, Effort::Medium, Effort::High];

    pub fn id(self) -> &'static str {
        match self {
            Effort::Low => "low",
            Effort::Medium => "medium",
            Effort::High => "high",
        }
    }

    pub fn from_id(s: &str) -> Option<Effort> {
        Effort::ALL.into_iter().find(|e| e.id() == s)
    }
}

/// One request to the model.
#[derive(Clone, Copy, Debug)]
pub struct Request<'a> {
    pub model: &'a str,
    pub system: &'a str,
    pub messages: &'a [Message],
    /// The tools the model may call (empty: none, the model answers in text).
    pub tools: &'a [ToolSpec],
    pub max_tokens: u32,
    /// Ask for one JSON object as the answer, following this schema.
    pub json: Option<&'a Value>,
    pub effort: Option<Effort>,
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Usage {
    pub input: u64,
    pub output: u64,
    /// Input tokens read from the provider's prompt cache, and written to it.
    pub cache_read: u64,
    pub cache_write: u64,
}

impl Usage {
    pub fn add(&mut self, o: &Usage) {
        self.input += o.input;
        self.output += o.output;
        self.cache_read += o.cache_read;
        self.cache_write += o.cache_write;
    }

    /// Every input token, cached or not.
    pub fn total_input(&self) -> u64 {
        self.input + self.cache_read + self.cache_write
    }
}

/// Why the model stopped.
#[derive(Clone, Debug, PartialEq)]
pub enum Stop {
    EndTurn,
    ToolUse,
    MaxTokens,
    /// The provider's safety checks declined the request.
    Refusal,
    Other(String),
}

/// The model's answer: the assistant message to add to the conversation, and its cost.
#[derive(Clone, Debug, PartialEq)]
pub struct Reply {
    pub blocks: Vec<Block>,
    pub stop: Stop,
    pub usage: Usage,
    pub model: String,
}

impl Reply {
    pub fn message(&self) -> Message {
        Message {
            role: Role::Assistant,
            blocks: self.blocks.clone(),
        }
    }

    pub fn text(&self) -> String {
        self.message().text()
    }
}

/// What arrives while the model answers, for the user to see it working.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Event<'a> {
    /// More of the answer's text.
    Text(&'a str),
    /// The model is thinking (no text to show).
    Thinking,
    /// The model started writing a call to this tool.
    Tool(&'a str),
}

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

    #[test]
    fn text_and_tool_uses() {
        let m = Message {
            role: Role::Assistant,
            blocks: vec![
                Block::Opaque(serde_json::json!({"type": "thinking"})),
                Block::Text("first".into()),
                Block::ToolUse {
                    id: "t1".into(),
                    name: "find_all".into(),
                    input: serde_json::json!({"pattern": "x"}),
                },
                Block::Text("second".into()),
            ],
        };
        assert_eq!(m.text(), "first\nsecond");
        let calls = m.tool_uses();
        assert_eq!(calls.len(), 1);
        assert_eq!(calls[0].1, "find_all");
        assert_eq!(Effort::from_id("high"), Some(Effort::High));
    }
}