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

mod convert;
pub(crate) use convert::effort_levels;
mod types;

use self::convert::to_message_request;
use self::types::{
    AnthropicContent, AnthropicDelta, AnthropicMessage, AnthropicStreamEvent, AnthropicTool,
    AnthropicUsageDelta, ContentBlock, ListModelsResponse, MessageRequest, MessageResponse,
    ServerTool, stop_reason,
};
use crate::DEFAULT_MAX_TOKENS;
use crate::WireStyle;
use crate::client::{ChatClient, Client, ClientResponse, ProviderClient};
use crate::error::{LlmError, LlmErrorKind, ProviderError, http_status_to_kind, parse_error_body};
use crate::extra_body::decorate;
use crate::stream_driver::StreamMapper;
use crate::system_messages;
use crate::types::{
    ChatRequest, ChatResponseStream, ContentPart, Effort, ModelSpec, StopReason, StreamEvent,
    ThinkingDisplay, Usage, WebSearchResult, decoded_tool_use, supported_efforts_by_model,
};
use anyhow::{Context, Result};
use async_trait::async_trait;
use reqwest::header::{HeaderName, HeaderValue};
use serde_json::{Map, Value};
use std::collections::HashMap;

use tracing::{debug, info, warn};

/// The Anthropic API, for [`Client::new`].
pub const BASE_URL: &str = "https://api.anthropic.com/v1";

/// The `anthropic-version` this wire is written against, sent unless the
/// caller's client already sets one.
const API_VERSION: &str = "2026-10-21";

/// The web search tool for `model` at `base_url`. Anthropic's own API gives
/// every current model but Haiku the version that filters results on the
/// server; Haiku and any proxy get the basic one.
fn web_search_tool(base_url: &str, model: &str) -> &'static str {
    if is_anthropic_api(base_url) && !model.contains("haiku") {
        "web_search_20260209"
    } else {
        "web_search_20250305"
    }
}

/// The one way this wire reaches the server: with its API version and its
/// error classifier.
fn provider_client(client: Client) -> ProviderClient {
    let client = client.with_default_header(
        HeaderName::from_static("anthropic-version"),
        HeaderValue::from_static(API_VERSION),
    );
    ProviderClient::new(client, classify_anthropic_http_response)
}

/// How many times one web search is resumed after the server pauses it.
const MAX_SEARCH_RESUMES: usize = 3;

/// Anthropic Messages API client.
#[derive(Clone)]
pub struct Anthropic {
    client: ProviderClient,
    extra_body: Map<String, Value>,
    thinking_display: Option<ThinkingDisplay>,
    max_request_images: Option<u32>,
    supported_efforts: HashMap<String, Vec<Effort>>,
}

/// Perform a web search using Claude's built-in web search tool
pub(super) async fn search(
    transport: &Client,
    query: &str,
    model: &ModelSpec,
) -> Result<WebSearchResult, LlmError> {
    let client = provider_client(transport.clone());
    let mut request = MessageRequest {
        model: model.id.clone(),
        max_tokens: model.max_tokens.unwrap_or(DEFAULT_MAX_TOKENS),
        messages: vec![AnthropicMessage {
            role: "user".to_string(),
            content: AnthropicContent::Text(query.to_string()),
        }],
        tools: Some(vec![AnthropicTool::ServerTool(ServerTool {
            tool_type: web_search_tool(transport.base_url(), &model.id).to_string(),
            name: "web_search".to_string(),
            max_uses: Some(5),
        })]),
        ..Default::default()
    };

    // A long search stops with `pause_turn` before it has answered. Sending
    // what it produced back as the assistant turn, under the same tools,
    // resumes it; each response carries only the new blocks.
    let mut response: MessageResponse = client.post_json("/messages", &request).await?;
    for _ in 0..MAX_SEARCH_RESUMES {
        if response.stop_reason.as_deref() != Some("pause_turn") {
            break;
        }
        request.messages.truncate(1);
        request.messages.push(AnthropicMessage {
            role: "assistant".to_string(),
            content: AnthropicContent::Blocks(response.content.clone()),
        });
        let next: MessageResponse = client.post_json("/messages", &request).await?;
        response.content.extend(next.content);
        response.stop_reason = next.stop_reason;
    }
    if response.stop_reason.as_deref() == Some("pause_turn") {
        warn!("web search still paused after {MAX_SEARCH_RESUMES} resumes; using what it found");
    }
    WebSearchResult::try_from(response)
        .context("Failed to parse web search response")
        .map_err(LlmError::response_decode)
}

#[async_trait]
impl ChatClient for Anthropic {
    /// Send a message and get a streaming response
    async fn stream_chat(&self, request: ChatRequest) -> Result<ChatResponseStream, LlmError> {
        let mut wire = self.wire_request(&request)?;
        wire.stream = Some(true);
        let body = decorate(&wire, &self.extra_body);

        self.client.post_stream("/messages", &body, AnthropicMapper::default()).await
    }

    async fn list_models(&self) -> Result<Vec<ModelSpec>, LlmError> {
        let resp: ListModelsResponse = self.client.get_json("/models", &()).await?;
        Ok(resp.data.into_iter().map(ModelSpec::from).collect())
    }
}

impl Anthropic {
    pub fn new(client: Client) -> Self {
        Self {
            client: provider_client(client),
            extra_body: Map::new(),
            thinking_display: None,
            max_request_images: None,
            supported_efforts: HashMap::new(),
        }
    }

    /// Add these fields to every chat request body. They are sent as given:
    /// pass only what [`WireStyle::conflicts`] clears.
    pub fn with_extra_body(mut self, extra_body: Map<String, Value>) -> Self {
        self.extra_body = extra_body;
        self
    }

    /// Ask for readable reasoning in this form. `None` leaves the provider's
    /// default.
    pub fn with_thinking_display(mut self, display: Option<ThinkingDisplay>) -> Self {
        self.thinking_display = display;
        self
    }

    /// Send at most this many images per request: the newest stay and older
    /// ones become text markers. `None` sends them all.
    pub fn with_max_request_images(mut self, max_request_images: Option<u32>) -> Self {
        self.max_request_images = max_request_images;
        self
    }

    /// Round effort onto the levels each model in `models` declares.
    pub fn with_supported_efforts(mut self, models: &[ModelSpec]) -> Self {
        self.supported_efforts = supported_efforts_by_model(models);
        self
    }

    /// Lower `request` to the provider's wire shape; the provider never sees a
    /// request that fails here.
    fn wire_request(&self, request: &ChatRequest) -> Result<MessageRequest, LlmError> {
        system_messages::prepare(request, &WireStyle::AnthropicMessage, self.client.base_url())
            .map(|request| request.within_image_budget(self.max_request_images))
            .and_then(|request| {
                let declared = self.supported_efforts.get(&request.model).map(Vec::as_slice);
                to_message_request(&request, self.thinking_display, declared)
            })
            .map(|mut wire| {
                if is_anthropic_api(self.client.base_url()) {
                    stream_tool_input(&mut wire);
                }
                wire
            })
            .map_err(LlmError::request_conversion)
    }
}

/// Whether `base_url` is Anthropic's own API. A proxy speaking this wire may
/// reject fields only Anthropic defines.
fn is_anthropic_api(base_url: &str) -> bool {
    base_url.trim_end_matches('/') == BASE_URL
}

/// Ask for every user tool's input to stream as the model writes it.
fn stream_tool_input(wire: &mut MessageRequest) {
    for tool in wire.tools.iter_mut().flatten() {
        if let AnthropicTool::Function { eager_input_streaming, .. } = tool {
            *eager_input_streaming = true;
        }
    }
}

fn classify_anthropic_http_response(resp: ClientResponse) -> LlmError {
    let (error_type, message) = parse_error_body(&resp.body, &["type"]);
    let kind = anthropic_error_kind(resp.status, error_type.as_deref(), message.as_deref());
    LlmError::http(kind, resp.status, error_type, message.unwrap_or(resp.body))
}

fn anthropic_stream_error(error_type: String, message: String) -> LlmError {
    let kind = anthropic_error_kind(reqwest::StatusCode::OK, Some(&error_type), Some(&message));
    LlmError::new(
        kind,
        ProviderError { provider_code: Some(error_type), message, ..ProviderError::default() },
    )
}

fn anthropic_error_kind(
    status: reqwest::StatusCode,
    error_type: Option<&str>,
    message: Option<&str>,
) -> LlmErrorKind {
    if message_is_context_overflow(message) {
        return LlmErrorKind::ContextOverflow;
    }
    if message_is_oauth_inference_scope_rejection(message) {
        return LlmErrorKind::OAuth;
    }

    if let Some(error_type) = error_type {
        match error_type {
            "authentication_error" | "permission_error" => return LlmErrorKind::Auth,
            "rate_limit_error" => return LlmErrorKind::RateLimited,
            "api_error" => return LlmErrorKind::ServerError,
            "overloaded_error" => return LlmErrorKind::Overloaded,
            "invalid_request" | "invalid_request_error" | "not_found_error" => {
                return LlmErrorKind::InvalidRequest;
            }
            _ => {}
        }
    }

    http_status_to_kind(status)
}

fn message_is_oauth_inference_scope_rejection(message: Option<&str>) -> bool {
    let Some(message) = message else {
        return false;
    };
    let message = message.to_ascii_lowercase();
    message.contains("scope")
        && (message.contains("user:inference")
            || message.contains("user:ccr_inference")
            || message.contains("inference scope"))
}

fn message_is_context_overflow(message: Option<&str>) -> bool {
    let Some(message) = message else {
        return false;
    };
    let message = message.to_ascii_lowercase();
    message.contains("prompt is too long")
        || (message.contains("context") && message.contains("exceed"))
}

struct ActiveToolUse {
    id: String,
    name: String,
    input: String,
}

/// Maps Anthropic's streaming events into the shared `StreamEvent` vocabulary.
#[derive(Default)]
struct AnthropicMapper {
    active_tool: HashMap<u32, ActiveToolUse>,
    /// The counts seen so far, patched event by event.
    usage: AnthropicUsageDelta,
    stop_reason: Option<StopReason>,
}

impl StreamMapper for AnthropicMapper {
    type Raw = AnthropicStreamEvent;

    fn map(&mut self, event: AnthropicStreamEvent) -> Result<Vec<StreamEvent>, LlmError> {
        match event {
            AnthropicStreamEvent::MessageStart { message } => {
                self.usage.patch(message.usage);
                Ok(vec![])
            }
            AnthropicStreamEvent::ContentBlockStart { index, content_block } => {
                match content_block {
                    ContentBlock::ToolUse { id, name, .. } => {
                        debug!("Starting tool use for index {}: {} {}", index, id, name);
                        self.active_tool.insert(
                            index,
                            ActiveToolUse {
                                id,
                                name,
                                input: String::new(), // Start with empty string, build from deltas
                            },
                        );
                    }
                    ContentBlock::RedactedThinking { data } => {
                        return Ok(vec![StreamEvent::ContentPart(ContentPart::RedactedThinking {
                            data,
                        })]);
                    }
                    _ => {}
                }
                Ok(vec![])
            }
            AnthropicStreamEvent::ContentBlockDelta { index, delta } => match delta {
                AnthropicDelta::TextDelta { text } => Ok(vec![StreamEvent::TextDelta(text)]),
                AnthropicDelta::ThinkingDelta { thinking } => {
                    Ok(vec![StreamEvent::ThinkingDelta { thinking, signature: None }])
                }
                AnthropicDelta::SignatureDelta { signature } => {
                    Ok(vec![StreamEvent::ThinkingDelta {
                        thinking: String::new(),
                        signature: Some(signature),
                    }])
                }
                AnthropicDelta::InputJsonDelta { partial_json } => {
                    if let Some(tool) = self.active_tool.get_mut(&index) {
                        tool.input.push_str(&partial_json);
                    }
                    Ok(vec![])
                }
                _ => Ok(vec![]),
            },
            AnthropicStreamEvent::ContentBlockStop { index } => {
                // A tool block ends as its call; a text or thinking block
                // just ends.
                let Some(tool_use) = self.active_tool.remove(&index) else {
                    debug!("not a tool use for index: {index} simple content stop");
                    return Ok(vec![StreamEvent::ContentStop]);
                };
                Ok(vec![StreamEvent::ToolUse(decoded_tool_use(
                    tool_use.id,
                    tool_use.name,
                    &tool_use.input,
                ))])
            }
            AnthropicStreamEvent::MessageDelta { delta, usage } => {
                self.usage.patch(usage);
                if let Some(reason) = delta.stop_reason.as_deref() {
                    self.stop_reason = Some(stop_reason(reason));
                }
                Ok(vec![])
            }
            AnthropicStreamEvent::MessageStop => {
                let usage = Usage::from(std::mem::take(&mut self.usage));
                Ok(vec![StreamEvent::MessageStop { usage, stop_reason: self.stop_reason.take() }])
            }
            AnthropicStreamEvent::Ping => Ok(vec![]),
            AnthropicStreamEvent::Error { error } => {
                info!(?error, "anthropic stream error event");
                Err(anthropic_stream_error(error.error_type, error.message))
            }
            AnthropicStreamEvent::Unknown { event_type, payload } => {
                debug!(?event_type, ?payload, "unhandled unknown anthropic stream event");
                Ok(vec![])
            }
        }
    }
}

#[cfg(test)]
mod tests;