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 serde::{Serialize, Serializer};
use serde_json::{Map, Value};

use crate::WireStyle;

const ANTHROPIC_REQUEST_FIELDS: &[&str] = &[
    "model",
    "max_tokens",
    "messages",
    "system",
    "temperature",
    "tools",
    "tool_choice",
    "stream",
    "thinking",
    "stop_sequences",
    "output_config",
    "cache_control",
];
const OPENAI_COMPATIBLE_REQUEST_FIELDS: &[&str] = &[
    "model",
    "messages",
    "reasoning_effort",
    "max_tokens",
    "stream",
    "stream_options",
    "temperature",
    "stop",
    "tools",
    "tool_choice",
    "thinking",
    "enable_thinking",
    "enable_search",
    "search_options",
];
const OPENAI_RESPONSE_REQUEST_FIELDS: &[&str] = &[
    "model",
    "input",
    "tools",
    "tool_choice",
    "parallel_tool_calls",
    "max_output_tokens",
    "temperature",
    "reasoning",
    "stream",
    "include",
    "store",
];
const GEMINI_REQUEST_FIELDS: &[&str] =
    &["contents", "systemInstruction", "generationConfig", "tools", "toolConfig"];

impl WireStyle {
    /// The fields of `extra_body` that collide with the fields this wire's
    /// request already sets, sorted. For the caller to check before it builds
    /// a client: the send path trusts what it is handed.
    pub fn conflicts(&self, extra_body: &Map<String, Value>) -> Vec<String> {
        let reserved = match self {
            Self::AnthropicMessage => ANTHROPIC_REQUEST_FIELDS,
            Self::OpenAiCompatible => OPENAI_COMPATIBLE_REQUEST_FIELDS,
            Self::OpenAiResponse => OPENAI_RESPONSE_REQUEST_FIELDS,
            Self::Gemini => GEMINI_REQUEST_FIELDS,
        };
        let mut conflicts: Vec<String> =
            extra_body.keys().filter(|key| reserved.contains(&key.as_str())).cloned().collect();
        conflicts.sort();
        conflicts
    }
}

/// A provider wire request on its way out, with any provider-configured
/// fields merged in. Without an `extra_body`, the typed request serializes
/// straight to bytes.
#[derive(Debug)]
pub(crate) enum RequestBody<'a, Req> {
    Plain(&'a Req),
    Extended { request: &'a Req, extra_body: &'a Map<String, Value> },
}

impl<Req> Serialize for RequestBody<'_, Req>
where
    Req: Serialize,
{
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match self {
            Self::Plain(request) => request.serialize(serializer),
            Self::Extended { request, extra_body } => {
                #[derive(Serialize)]
                struct Merged<'a, Req> {
                    #[serde(flatten)]
                    request: &'a Req,
                    #[serde(flatten)]
                    extra_body: &'a Map<String, Value>,
                }
                Merged { request, extra_body }.serialize(serializer)
            }
        }
    }
}

/// Pair a provider's normal chat request with its user-configured fields.
/// The caller has already dropped the ones [`WireStyle::conflicts`]
/// reports, so the send path merges without re-checking and without an
/// intermediate `Value`.
pub(crate) fn decorate<'a, Req>(
    request: &'a Req,
    extra_body: &'a Map<String, Value>,
) -> RequestBody<'a, Req> {
    if extra_body.is_empty() {
        return RequestBody::Plain(request);
    }
    RequestBody::Extended { request, extra_body }
}

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

    #[test]
    fn collision_rules_follow_wire_style() {
        let extra_body = [
            ("messages".to_string(), Value::Array(Vec::new())),
            ("generationConfig".to_string(), Value::Object(Map::new())),
            ("service_tier".to_string(), Value::String("priority".to_string())),
            ("tool_choice".to_string(), Value::String("auto".to_string())),
        ]
        .into_iter()
        .collect();

        assert_eq!(WireStyle::AnthropicMessage.conflicts(&extra_body), ["messages", "tool_choice"]);
        assert_eq!(WireStyle::OpenAiCompatible.conflicts(&extra_body), ["messages", "tool_choice"]);
        assert_eq!(WireStyle::Gemini.conflicts(&extra_body), ["generationConfig"]);
    }
}