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::{collections::VecDeque, sync::Arc};

use anyhow::{Result, bail};
use tracing::debug;

use super::{
    Attachment, Content, ContentPart, Effort, Message, ModelSpec, ToolDefinition, ToolResult,
};

/// One model call: the conversation plus the model settings that reach the
/// wire. The caller builds one per call from its conversation and a
/// [`ModelSpec`], with image fallback already applied. Unchanged conversation
/// messages ride as shared `Arc`s, and callers shape per-call intent (tools,
/// `max_tokens`, `tool_choice`) on the value before sending it. Only fields a
/// provider reads at send time live here — the rest of what is known about
/// a model stays on `ModelSpec`.
#[derive(Debug, Clone, Default)]
pub struct ChatRequest {
    /// The system prompt, in blocks.
    pub system: Arc<Vec<Arc<str>>>,
    /// The tools the model may call.
    pub tools: Arc<Vec<ToolDefinition>>,
    /// The conversation so far, oldest first.
    pub messages: Arc<Vec<Arc<Message>>>,
    /// The provider's model id.
    pub model: String,
    /// Sampling temperature, on wires that still accept one.
    pub temperature: Option<f32>,
    /// The most tokens the reply may use.
    pub max_tokens: Option<u32>,
    /// Text that ends the reply where it appears.
    pub stop_sequences: Option<Vec<String>>,
    /// How hard the model reasons, mapped onto the provider's own levels.
    pub effort: Option<Effort>,
    /// How the model may use `tools` this call. `None` leaves the provider's
    /// default in place.
    pub tool_choice: Option<ToolChoice>,
    /// How long the provider keeps this prompt cached for a later call that
    /// starts with it, where the wire lets the caller choose. `None` asks for
    /// no caching: a one-off call.
    pub cache_ttl: Option<CacheTtl>,
}

/// A prompt-cache lifetime. `Short` outlasts the next step of a running
/// loop; `Long` also outlasts a person's pause, at a higher write price.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CacheTtl {
    /// The provider's default lifetime.
    Short,
    /// An hour, where the provider offers it.
    Long,
}

/// A constraint on tool use for one call. The variants are the ones every
/// supported wire can express; provider-specific modes are not exposed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ToolChoice {
    /// The model must call some tool.
    Required,
    /// The model must call the named tool.
    Tool(String),
    /// Tools stay visible but the model may not call any.
    Forbid,
}

impl ChatRequest {
    /// An empty request to `model`, with every setting left to the provider.
    pub fn new(model: impl Into<String>) -> Self {
        Self { model: model.into(), ..Self::default() }
    }

    /// The wire-bound projection of `model` with an empty conversation.
    pub fn for_model(model: &ModelSpec) -> Self {
        Self {
            temperature: model.temperature,
            max_tokens: model.max_tokens,
            stop_sequences: model.stop_sequences.clone(),
            effort: model.effort,
            ..Self::new(&model.id)
        }
    }

    /// The non-empty system prompt sections, in order.
    pub(crate) fn system_prompts(&self) -> impl Iterator<Item = &str> {
        self.system.iter().map(AsRef::as_ref).filter(|s| !s.is_empty())
    }

    /// The system prompt sections merged into one block, for wires that carry
    /// a single system string.
    pub(crate) fn system_text(&self) -> String {
        self.system_prompts().collect::<Vec<_>>().join("\n\n")
    }

    /// Append a system prompt section.
    pub fn with_system(mut self, text: impl Into<Arc<str>>) -> Self {
        Arc::make_mut(&mut self.system).push(text.into());
        self
    }

    /// Offer `tools` to the model, replacing any already offered.
    pub fn with_tools(mut self, tools: Vec<ToolDefinition>) -> Self {
        self.tools = Arc::new(tools);
        self
    }

    /// Append `message`. Copies the message list when it is still shared
    /// with the conversation it was built from.
    pub fn with_message(mut self, message: Message) -> Self {
        Arc::make_mut(&mut self.messages).push(Arc::new(message));
        self
    }

    /// Append a user message holding `text`.
    pub fn with_user_text(self, text: impl Into<String>) -> Self {
        self.with_message(Message::user_text(text.into()))
    }

    /// Retain the last `limit` images in request order, including tool-result
    /// contents, and replace older ones with markers ending in `reason`. Copies
    /// only changed messages; the conversation and other requests built from
    /// it keep their images.
    pub fn retain_newest_images(&mut self, limit: u32, reason: &str) {
        let mut remaining = limit;
        let mut replaced_images = 0;
        for index in (0..self.messages.len()).rev() {
            if let Some(content) = project_images(
                &self.messages[index].content,
                &mut remaining,
                reason,
                &mut replaced_images,
            ) {
                let Message { role, tags, .. } = self.messages[index].as_ref();
                let message = Message { role: role.clone(), content, tags: tags.clone() };
                Arc::make_mut(&mut self.messages)[index] = Arc::new(message);
            }
        }
        if replaced_images > 0 {
            debug!(model = %self.model, limit, replaced_images, reason, "replaced images");
        }
    }

    /// Apply a provider's `max_request_images` just before wire conversion.
    /// `None` leaves the request as it is.
    pub(crate) fn within_image_budget(mut self, max_request_images: Option<u32>) -> Self {
        if let Some(limit) = max_request_images {
            self.retain_newest_images(
                limit,
                &format!("omitted to fit provider image budget (max_request_images={limit})"),
            );
        }
        self
    }

    /// The tool choice a converter should emit, after the checks every wire
    /// shares: a forced call needs tools to pick from, a named tool must be
    /// among them, and forbidding calls when there are no tools is a no-op.
    pub(crate) fn resolved_tool_choice(&self) -> Result<Option<&ToolChoice>> {
        let Some(choice) = &self.tool_choice else {
            return Ok(None);
        };
        match choice {
            ToolChoice::Forbid if self.tools.is_empty() => Ok(None),
            ToolChoice::Forbid => Ok(Some(choice)),
            ToolChoice::Required => {
                if self.tools.is_empty() {
                    bail!("tool_choice requires a tool call but the request has no tools");
                }
                Ok(Some(choice))
            }
            ToolChoice::Tool(name) => {
                if !self.tools.iter().any(|tool| tool.name == *name) {
                    bail!("tool_choice names `{name}`, which is not among the request's tools");
                }
                Ok(Some(choice))
            }
        }
    }
}

/// Allocate only after finding an omitted image; never clone its base64 payload
/// to discard it. Walk backwards so the allowance goes to the newest images.
fn project_images(
    content: &Content,
    remaining: &mut u32,
    reason: &str,
    replaced_images: &mut usize,
) -> Option<Content> {
    let Content::Parts(parts) = content else { return None };
    let mut replaced: Option<VecDeque<ContentPart>> = None;
    for (index, part) in parts.iter().enumerate().rev() {
        let replacement = match part {
            ContentPart::Image(_) if *remaining > 0 => {
                *remaining -= 1;
                None
            }
            ContentPart::Image(image) => {
                *replaced_images += 1;
                let media_type = match image {
                    Attachment::Base64 { media_type, .. } => media_type.clone(),
                    Attachment::Url { url } => format!("url:{url}"),
                };
                Some(ContentPart::Text(format!("[Image content (type: {media_type}) {reason}]")))
            }
            ContentPart::ToolResult(result) => {
                project_images(&result.content, remaining, reason, replaced_images).map(|content| {
                    ContentPart::ToolResult(ToolResult {
                        tool_use_id: result.tool_use_id.clone(),
                        content,
                        is_error: result.is_error,
                    })
                })
            }
            _ => None,
        };
        if let Some(replacement) = replacement {
            replaced
                .get_or_insert_with(|| parts[index + 1..].iter().cloned().collect())
                .push_front(replacement);
        } else if let Some(replaced) = &mut replaced {
            replaced.push_front(part.clone());
        }
    }
    replaced.map(|parts| Content::Parts(parts.into()))
}

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

    #[test]
    fn image_budget_preserves_nested_results_and_shares_unchanged_messages() {
        let image = |data: &str| ContentPart::image("image/png".into(), data.into());
        let omitted = |part: &ContentPart| matches!(part, ContentPart::Text(text) if text.contains("omitted by budget"));
        let nested = ContentPart::ToolResult(ToolResult {
            tool_use_id: "inner".into(),
            is_error: true,
            content: Content::Parts(vec![image("inner-old"), image("inner-new")]),
        });
        let original = ChatRequest {
            messages: Arc::new(vec![
                Arc::new(Message::user(Content::Parts(vec![image("oldest")]))),
                Arc::new(Message::user(Content::Parts(vec![ContentPart::ToolResult(
                    ToolResult::ok(
                        "outer".into(),
                        Content::Parts(vec![
                            ContentPart::Text("before".into()),
                            nested,
                            image("last"),
                        ]),
                    ),
                )]))),
                Arc::new(Message::user_text("after".into())),
            ]),
            ..Default::default()
        };
        let mut request = original.clone();
        request.retain_newest_images(2, "omitted by budget");
        assert!(omitted(&request.messages[0].content.parts()[0]));
        assert!(Arc::ptr_eq(&request.messages[2], &original.messages[2]));
        let ContentPart::ToolResult(outer) = &request.messages[1].content.parts()[0] else {
            panic!("outer result must survive");
        };
        assert_eq!(outer.tool_use_id, "outer");
        assert!(!outer.is_error);
        assert_eq!(outer.content.parts()[0], ContentPart::Text("before".into()));
        assert_eq!(outer.content.parts()[2], image("last"));
        let ContentPart::ToolResult(inner) = &outer.content.parts()[1] else {
            panic!("inner result must survive");
        };
        assert_eq!(inner.tool_use_id, "inner");
        assert!(inner.is_error);
        assert!(omitted(&inner.content.parts()[0]));
        assert_eq!(inner.content.parts()[1], image("inner-new"));

        // Reapplying the same limit is a no-op, as is a limit above the count.
        let already_projected = Arc::clone(&request.messages);
        request.retain_newest_images(2, "omitted by budget");
        assert!(Arc::ptr_eq(&request.messages, &already_projected));
        let mut unlimited = original.clone();
        unlimited.retain_newest_images(u32::MAX, "omitted by budget");
        assert!(Arc::ptr_eq(&unlimited.messages, &original.messages));
    }

    fn with_tools(tools: Vec<ToolDefinition>, tool_choice: Option<ToolChoice>) -> ChatRequest {
        ChatRequest { tools: Arc::new(tools), tool_choice, ..ChatRequest::default() }
    }

    #[test]
    fn system_helpers_skip_blank_sections() {
        let request = ChatRequest {
            system: Arc::new(vec!["a".into(), "".into(), "b".into()]),
            ..ChatRequest::default()
        };
        assert_eq!(request.system_prompts().collect::<Vec<_>>(), ["a", "b"]);
        assert_eq!(request.system_text(), "a\n\nb");
    }

    #[test]
    fn forced_calls_need_matching_tools() {
        let error =
            with_tools(vec![], Some(ToolChoice::Required)).resolved_tool_choice().unwrap_err();
        assert!(error.to_string().contains("no tools"), "{error}");

        let error =
            with_tools(vec![ToolDefinition::stub("grep")], Some(ToolChoice::Tool("read".into())))
                .resolved_tool_choice()
                .unwrap_err();
        assert!(error.to_string().contains("`read`"), "{error}");
    }
}