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

//! Request body compression, for the endpoints that accept it.

use std::io::Write;

use flate2::{Compression, write::GzEncoder};
use url::Url;

/// Below this the saving is not worth the encoder call.
const MIN_BYTES: usize = 16 * 1024;

/// A `Content-Encoding` a provider endpoint accepts for a request body.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Encoding {
    Gzip,
    Zstd,
}

impl Encoding {
    /// The `Content-Encoding` header value.
    pub(super) fn name(self) -> &'static str {
        match self {
            Self::Gzip => "gzip",
            Self::Zstd => "zstd",
        }
    }
}

/// The encoding the endpoint at `url` accepts; `None` for one to send plain
/// JSON. Each provider's own endpoint accepts one encoding and rejects the
/// other. A gateway that speaks the same wire may accept none, and OpenAI's
/// `/chat/completions` reads neither, so the match is on the exact host and
/// path.
pub(super) fn encoding_for(url: &str) -> Option<Encoding> {
    let url = Url::parse(url).ok()?;
    match (url.host_str()?, url.path()) {
        ("api.anthropic.com", "/v1/messages") => Some(Encoding::Gzip),
        ("api.openai.com", "/v1/responses") | ("chatgpt.com", "/backend-api/codex/responses") => {
            Some(Encoding::Zstd)
        }
        _ => None,
    }
}

/// `json` compressed as `encoding`; `None` for a body to send as it is.
pub(super) fn compress(json: &[u8], encoding: Encoding) -> Option<Vec<u8>> {
    if json.len() < MIN_BYTES {
        return None;
    }
    match encoding {
        Encoding::Gzip => {
            let mut encoder = GzEncoder::new(Vec::new(), Compression::fast());
            encoder.write_all(json).ok()?;
            encoder.finish().ok()
        }
        Encoding::Zstd => {
            let bytes = zstd::bulk::compress(json, 3).ok()?;
            // The Responses API answers 413 to a body that expands over 100:1.
            (json.len() <= bytes.len() * 100).then_some(bytes)
        }
    }
}

#[cfg(test)]
mod tests {
    use std::io::Read;

    use flate2::read::GzDecoder;

    use super::*;

    fn tool_results(count: usize) -> Vec<u8> {
        let results: Vec<String> = (0..count).map(|i| format!("tool result {i}")).collect();
        serde_json::to_vec(&results).unwrap()
    }

    #[test]
    fn each_provider_endpoint_gets_the_encoding_it_accepts() {
        for (url, encoding) in [
            ("https://api.anthropic.com/v1/messages", Some(Encoding::Gzip)),
            ("https://api.anthropic.com/v1/messages?beta=true", Some(Encoding::Gzip)),
            ("https://api.openai.com/v1/responses", Some(Encoding::Zstd)),
            ("https://chatgpt.com/backend-api/codex/responses", Some(Encoding::Zstd)),
            ("https://api.anthropic.com.example/v1/messages", None),
            ("https://api.openai.com/v1/chat/completions", None),
            ("not a url", None),
        ] {
            assert_eq!(encoding_for(url), encoding, "{url}");
        }
    }

    #[test]
    fn a_compressed_body_decodes_to_the_json() {
        let json = tool_results(4096);

        let gzip = compress(&json, Encoding::Gzip).unwrap();
        let mut decoded = Vec::new();
        GzDecoder::new(gzip.as_slice()).read_to_end(&mut decoded).unwrap();
        assert_eq!(decoded, json);

        let zstd = compress(&json, Encoding::Zstd).unwrap();
        assert_eq!(zstd::bulk::decompress(&zstd, json.len()).unwrap(), json);
    }

    #[test]
    fn a_body_not_worth_compressing_is_sent_as_it_is() {
        let small = tool_results(8);
        // Expands far over 100:1.
        let repeated = serde_json::to_vec(&"x".repeat(4 * MIN_BYTES)).unwrap();

        assert!(compress(&small, Encoding::Gzip).is_none());
        assert!(compress(&small, Encoding::Zstd).is_none());
        assert!(compress(&repeated, Encoding::Zstd).is_none());
    }
}