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 futures_util::Stream;
use std::collections::HashMap;
use std::pin::Pin;

use serde::{Deserialize, Serialize};

mod chat_request;
mod message;
mod schema;
mod tool_args;

pub use ante_protocol_shape::{
    Effort, MISSING_TOOL_NAME, MalformedToolArgs, ModelSpec, ToolUse, Usage, WeightClass,
};
pub use chat_request::{CacheTtl, ChatRequest, ToolChoice};
pub use message::{Attachment, Content, ContentPart, Message, Role};
pub use schema::normalize_tool_schema;
pub(crate) use tool_args::{decode_tool_args, decoded_tool_use, replay_safe_tool_args};

/// The effort levels each of `models` declares, by model id, ascending and
/// deduplicated. Models that declare nothing are absent.
pub(crate) fn supported_efforts_by_model(models: &[ModelSpec]) -> HashMap<String, Vec<Effort>> {
    models
        .iter()
        .filter_map(|model| {
            model.supported_efforts.as_ref().map(|supported_efforts| {
                (model.id.clone(), crate::effort::normalize_levels(supported_efforts.clone()))
            })
        })
        .collect()
}

/// Default timeout for opening a stream and for silence between transport reads.
/// A client can be built with another.
pub const DEFAULT_STREAM_IDLE_TIMEOUT_SECS: u64 = 300;

/// Readable reasoning returned by a provider, independently of reasoning effort.
/// An absent setting sends no display parameter, leaving the provider's default.
/// Providers use the closest supported mode, or ignore the setting when unsupported.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ThinkingDisplay {
    /// Omit readable reasoning without disabling thinking.
    Off,
    /// Request a concise summary, or the provider's available summary format.
    Concise,
    /// Request a detailed summary, or the provider's available summary format.
    Detailed,
}

/// The outcome of a tool call, sent back to the model in a user message.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ToolResult {
    /// The [`ToolUse::id`] this answers.
    pub tool_use_id: String,
    /// What the tool returned: text, or parts such as images.
    pub content: Content,
    /// Whether the call failed. The content then describes the failure.
    pub is_error: bool,
}

impl ToolResult {
    /// A successful result.
    pub fn ok(tool_use_id: String, content: Content) -> Self {
        Self { tool_use_id, content, is_error: false }
    }
}

/// A tool the model may call.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolDefinition {
    /// The name the model calls it by.
    pub name: String,
    /// What the tool does, for the model.
    pub description: Option<String>,
    /// The JSON Schema of the call's arguments. [`normalize_tool_schema`]
    /// rewrites a schema into the subset every provider accepts.
    pub input_schema: serde_json::Value,
}

#[cfg(test)]
impl ToolDefinition {
    /// A schema-less tool for tests that only need a name to point at.
    pub(crate) fn stub(name: &str) -> Self {
        Self {
            name: name.to_string(),
            description: None,
            input_schema: serde_json::json!({ "type": "object" }),
        }
    }
}

/// One event of a streamed reply, in the same terms for every provider. A
/// complete reply ends with [`StreamEvent::MessageStop`].
#[derive(Debug, Clone)]
pub enum StreamEvent {
    /// A piece of readable reasoning.
    ThinkingDelta {
        /// The reasoning text. Empty when the event carries only a signature.
        thinking: String,
        /// The provider's signature over the reasoning, which must go back
        /// with it on the next call.
        signature: Option<String>,
    },
    /// A piece of the reply's text.
    TextDelta(String),
    /// Completed content that is not represented as a text/thinking delta.
    ContentPart(ContentPart),
    /// A complete tool call. Arguments that are not valid JSON are on its
    /// `malformed_args`.
    ToolUse(ToolUse),
    /// The current text or reasoning block ended.
    ContentStop,
    /// A label the provider put on this message, kept in [`Message::tags`].
    Tag {
        /// The label's name.
        name: String,
        /// The label's value.
        value: String,
    },
    /// The provider is still reading the prompt (prefill) and has produced
    /// no output: `processed` of its `total` tokens are read, `cached` of
    /// them taken from the provider's prompt cache. The counts are the
    /// provider's own, unchecked: normally `cached <= processed <= total`.
    PrefillProgress {
        /// Tokens in the prompt.
        total: u32,
        /// Tokens taken from the provider's prompt cache.
        cached: u32,
        /// Tokens read so far, the cached ones included.
        processed: u32,
    },
    /// The reply is complete.
    MessageStop {
        /// Tokens used by this call.
        usage: Usage,
        /// Why the model stopped, when the provider says.
        stop_reason: Option<StopReason>,
    },
}

impl StreamEvent {
    /// Whether this event carries model output: nonempty text or reasoning,
    /// or a well-formed tool call.
    pub fn is_output(&self) -> bool {
        match self {
            StreamEvent::TextDelta(text)
            | StreamEvent::ThinkingDelta { thinking: text, .. }
            | StreamEvent::ContentPart(
                ContentPart::Text(text) | ContentPart::Thinking { text, .. },
            ) => !text.is_empty(),
            StreamEvent::ToolUse(tool) | StreamEvent::ContentPart(ContentPart::ToolUse(tool)) => {
                tool.malformed_args.is_none()
            }
            _ => false,
        }
    }
}

/// The events of one streamed call, as returned by
/// [`ChatClient::stream_chat`](crate::client::ChatClient::stream_chat).
pub type ChatResponseStream =
    Pin<Box<dyn Stream<Item = Result<StreamEvent, crate::error::LlmError>> + Send>>;

/// A complete reply: the stream of one call, collected.
#[derive(Debug, Clone)]
pub struct ChatResponse {
    /// The model's message.
    pub message: Message,
    /// Why the model stopped, when the provider says.
    pub stop_reason: Option<StopReason>,
    /// Tokens used by the call.
    pub usage: Usage,
}

/// The answer to a web search, with the pages it cites.
#[derive(Debug)]
pub struct WebSearchResult {
    /// The answer.
    pub content: Content,
    /// The pages the answer cites.
    pub citations: Vec<WebCitation>,
}

/// A page cited by a [`WebSearchResult`].
#[derive(Debug, Deserialize, Serialize)]
pub struct WebCitation {
    /// The page title.
    pub title: String,
    /// The page address.
    pub uri: String,
}

/// Why the model stopped generating.
#[derive(Debug, Clone, Default, PartialEq)]
pub enum StopReason {
    /// natural end of turn

    #[default]
    EndTurn,

    /// maximum number of tokens reached
    MaxTokens,

    /// blocked by policy: the model refused, or the provider's content
    /// filter cut the reply
    Refusal,

    /// other reason
    Other(String),
}

#[cfg(test)]
mod tests {
    use serde_json::json;

    use super::*;

    #[test]
    fn output_is_nonempty_text_or_reasoning_or_a_well_formed_tool_call() {
        let tool = ToolUse::new("call", "Read", json!({}));
        let mut malformed = tool.clone();
        malformed.malformed_args = Some(MalformedToolArgs { raw: "{".into(), error: "EOF".into() });

        for event in [
            StreamEvent::TextDelta("answer".into()),
            StreamEvent::ThinkingDelta { thinking: "reasoning".into(), signature: None },
            StreamEvent::ToolUse(tool.clone()),
            StreamEvent::ContentPart(ContentPart::Text("answer".into())),
            StreamEvent::ContentPart(ContentPart::Thinking {
                text: "reasoning".into(),
                signature: None,
            }),
            StreamEvent::ContentPart(ContentPart::ToolUse(tool)),
        ] {
            assert!(event.is_output(), "{event:?}");
        }

        for event in [
            StreamEvent::TextDelta(String::new()),
            StreamEvent::ThinkingDelta { thinking: String::new(), signature: Some("sig".into()) },
            StreamEvent::ContentPart(ContentPart::RedactedThinking { data: "opaque".into() }),
            StreamEvent::ToolUse(malformed),
            StreamEvent::ContentStop,
            StreamEvent::MessageStop { usage: Usage::default(), stop_reason: None },
        ] {
            assert!(!event.is_output(), "{event:?}");
        }
    }
}