ante-llm 0.4.2

Streaming LLM client for Anthropic, OpenAI, Gemini and Chat Completions servers, from the Ante coding agent
Documentation
// Copyright 2026 Antigma Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

use std::{borrow::Cow, collections::BTreeMap};

use serde::{Deserialize, Serialize};

use super::{ToolResult, ToolUse};

/// Content blocks represent different types of renderable content in a message
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub enum ContentPart {
    /// Simple text content
    Text(String),
    /// An image.
    Image(Attachment),
    /// A document, such as a PDF.
    Document(Attachment),
    /// Thinking/reasoning step
    Thinking {
        /// The readable reasoning.
        text: String,
        /// The provider's signature over the reasoning, sent back with it.
        signature: Option<String>,
    },
    /// Reasoning the provider returned only in encrypted form, sent back
    /// unchanged.
    RedactedThinking {
        /// The encrypted reasoning.
        data: String,
    },
    /// A tool call the model made.
    ToolUse(ToolUse),
    /// The result of a tool call, sent back to the model.
    ToolResult(ToolResult),
}

impl ContentPart {
    /// A reasoning part: thinking, plain or redacted.
    pub fn is_reasoning(&self) -> bool {
        matches!(self, ContentPart::Thinking { .. } | ContentPart::RedactedThinking { .. })
    }

    pub fn text(text: String) -> Self {
        Self::Text(text)
    }

    pub fn as_tool_use(&self) -> Option<&ToolUse> {
        match self {
            Self::ToolUse(tool_use) => Some(tool_use),
            _ => None,
        }
    }

    pub fn image(media_type: String, data: String) -> Self {
        Self::Image(Attachment::Base64 { media_type, data })
    }

    pub fn document(media_type: String, data: String) -> Self {
        Self::Document(Attachment::Base64 { media_type, data })
    }
}

/// The bytes of an image or document, inline or by address.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub enum Attachment {
    /// Inline data.
    Base64 {
        /// The MIME type, such as `image/png`.
        media_type: String,
        /// The base64-encoded bytes.
        data: String,
    },
    /// A URL the provider fetches.
    Url {
        /// The address.
        url: String,
    },
}

impl Attachment {
    pub(crate) fn to_uri(&self) -> String {
        match self {
            Attachment::Base64 { media_type, data } => format!("data:{media_type};base64,{data}"),
            Attachment::Url { url } => url.clone(),
        }
    }
}

/// The body of a message or tool result.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub enum Content {
    /// Plain text.
    Text(String),
    /// A sequence of parts: text, attachments, reasoning, and tool calls or
    /// results.
    Parts(Vec<ContentPart>),
}

impl Content {
    pub fn text(text: String) -> Self {
        Self::Text(text)
    }

    /// Returns the text content as a single string, joining all text parts with newlines.
    /// If there are no text parts, returns an empty string.
    pub fn as_text(&self) -> String {
        match self {
            Content::Text(text) => text.clone(),
            Content::Parts(parts) => parts
                .iter()
                .filter_map(|part| match part {
                    ContentPart::Text(text) => Some(text.as_str()),
                    _ => None,
                })
                .collect::<Vec<&str>>()
                .join("\n"),
        }
    }

    pub fn as_parts(&self) -> Cow<'_, [ContentPart]> {
        match self {
            Content::Parts(parts) => Cow::Borrowed(parts),
            Content::Text(text) => Cow::Owned(vec![ContentPart::Text(text.clone())]),
        }
    }

    pub fn parts(&self) -> &[ContentPart] {
        match self {
            Content::Parts(parts) => parts,
            Content::Text(_) => &[],
        }
    }

    pub fn add_part(&mut self, part: ContentPart) {
        match self {
            Content::Parts(parts) => parts.push(part),
            Content::Text(text) => {
                *self = Content::Parts(vec![ContentPart::Text(text.clone()), part])
            }
        }
    }

    pub fn add_parts(&mut self, other_parts: Vec<ContentPart>) {
        match self {
            Content::Parts(parts) => parts.extend(other_parts),
            Content::Text(text) => {
                *self = Content::Parts(vec![ContentPart::Text(text.clone())]);
                self.add_parts(other_parts);
            }
        }
    }

    pub fn tool_uses(&self) -> impl Iterator<Item = &ToolUse> + '_ {
        self.parts().iter().filter_map(ContentPart::as_tool_use)
    }

    pub fn images(&self) -> impl Iterator<Item = &Attachment> {
        self.parts().iter().filter_map(|part| match part {
            ContentPart::Image(image) => Some(image),
            _ => None,
        })
    }

    pub fn documents(&self) -> impl Iterator<Item = &Attachment> {
        self.parts().iter().filter_map(|part| match part {
            ContentPart::Document(document) => Some(document),
            _ => None,
        })
    }

    pub fn is_empty(&self) -> bool {
        match self {
            Content::Text(text) => text.is_empty(),
            Content::Parts(parts) => {
                parts.is_empty()
                    || parts.len() == 1
                        && match parts.first() {
                            Some(ContentPart::Text(text)) => text.is_empty(),
                            _ => false,
                        }
            }
        }
    }

    /// Trim thinking parts from the content.
    ///
    /// Returns the number of thinking parts trimmed.
    pub fn trim_thinkings(&mut self) -> usize {
        if let Content::Parts(parts) = self {
            let previous_len = parts.len();
            parts.retain(|part| !part.is_reasoning());
            return previous_len - parts.len();
        }
        0
    }

    pub fn add_reminder(&mut self, text: String) {
        self.add_part(ContentPart::reminder(text));
    }

    pub(crate) fn reminder(text: String) -> Content {
        Self::Text(reminder(text))
    }
}

impl ContentPart {
    /// A text part carrying `text` as a `<system-reminder>` block.
    pub fn reminder(text: String) -> Self {
        Self::Text(reminder(text))
    }
}

fn reminder(text: String) -> String {
    format!("<system-reminder>\n{text}\n</system-reminder>")
}

impl std::fmt::Display for Content {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Content::Text(text) => write!(f, "{text}"),
            Content::Parts(parts) => write!(f, "{parts:?}"),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{Content, ContentPart, Message};

    // Tags are saved only when set, so a message saved before they existed
    // loads the same as one that has none.
    #[test]
    fn tags_are_saved_only_when_set() {
        let mut message = Message::model("answer".to_string());
        let saved = serde_json::to_value(&message).unwrap();
        assert!(saved.get("tags").is_none());
        assert!(serde_json::from_value::<Message>(saved).unwrap().tags.is_empty());

        message.tags.insert("phase".to_string(), "final_answer".to_string());
        let saved = serde_json::to_value(&message).unwrap();
        assert_eq!(saved["tags"]["phase"], "final_answer");
        assert_eq!(serde_json::from_value::<Message>(saved).unwrap().tags, message.tags);
    }

    #[test]
    fn a_reminder_is_the_text_on_its_own_lines_between_the_tags() {
        assert_eq!(
            ContentPart::reminder("runtime rule".to_string()),
            ContentPart::Text("<system-reminder>\nruntime rule\n</system-reminder>".to_string())
        );
    }

    #[test]
    fn content_trim_thinkings() {
        let mut c = Content::Parts(vec![
            ContentPart::Text("hello".to_string()),
            ContentPart::Thinking { text: "thinking".to_string(), signature: None },
        ]);
        let trimmed = c.trim_thinkings();
        assert_eq!(trimmed, 1);
        assert!(
            matches!(&c, Content::Parts(parts) if parts.len() == 1 && matches!(&parts[0], ContentPart::Text(t) if t == "hello"))
        );

        let mut c = Content::Parts(vec![
            ContentPart::Thinking { text: "thinking".to_string(), signature: None },
            ContentPart::Thinking { text: "thinking".to_string(), signature: None },
        ]);
        let trimmed = c.trim_thinkings();
        assert_eq!(trimmed, 2);
        assert!(c.is_empty());
    }
}

/// One turn of a conversation.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Message {
    /// Who wrote it.
    pub role: Role,
    /// What it says.
    pub content: Content,
    /// Labels a provider put on this message and expects back unchanged.
    /// Only the wire that set a tag reads it, and a provider switch clears
    /// them.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub tags: BTreeMap<String, String>,
}

/// The author of a [`Message`].
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub enum Role {
    /// The user, including tool results.
    User,
    /// The model.
    Model,
    /// Runtime instructions from the application, independent of text markup.
    System,
    /// A role name sent to the provider as is.
    Custom(String),
}

impl Message {
    pub fn new(role: Role, content: Content) -> Self {
        Self { role, content, tags: BTreeMap::new() }
    }

    pub fn system(text: String) -> Self {
        Self::new(Role::System, Content::text(text))
    }

    pub fn user(content: Content) -> Self {
        Self::new(Role::User, content)
    }

    pub fn user_text(text: String) -> Self {
        Self::new(Role::User, Content::text(text))
    }

    pub fn model(text: String) -> Self {
        Self::new(Role::Model, Content::text(text))
    }

    pub fn model_content(content: Content) -> Self {
        Self::new(Role::Model, content)
    }

    pub fn is_user(&self) -> bool {
        self.role == Role::User
    }

    pub fn is_model(&self) -> bool {
        self.role == Role::Model
    }

    pub fn is_system(&self) -> bool {
        self.role == Role::System
    }

    pub fn is_empty(&self) -> bool {
        self.content.is_empty()
    }
}

impl std::fmt::Display for Message {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:?}: {}", self.role, self.content)
    }
}