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 super::types::{
    FunctionCall, ImageUrl, OpenAIContent, OpenAIContentItem, OpenAIMessage, OpenAIRequest,
    OpenAITool, OpenAIToolCall, OpenAIToolChoice, OpenAIToolFunction,
};
use crate::openai_compatible::OpenAiCompatProfile;
use crate::types::{
    Attachment, ChatRequest, Content, ContentPart, Effort, Message, Role, ToolChoice,
    ToolDefinition, ToolResult, ToolUse, replay_safe_tool_args,
};
use anyhow::Result;
use tracing::debug;

pub(in crate::openai_compatible) fn to_message_request(
    request: &ChatRequest,
    provider_id: &str,
    supported_efforts: Option<&[Effort]>,
) -> Result<OpenAIRequest> {
    let profile = OpenAiCompatProfile::from_model(provider_id, &request.model);
    let thinking = profile.thinking_params(supported_efforts, request.effort);

    tracing::debug!(
        model = %request.model,
        thinking = ?request.effort,
        reasoning_effort = ?thinking.reasoning_effort,
        thinking_config = ?thinking.thinking.as_ref().map(|config| config.thinking_type()),
        enable_thinking = ?thinking.enable_thinking,
        "OpenAI-compatible thinking config"
    );

    let mut messages = Vec::new();

    if profile.supports_system_role() {
        if profile.merges_system_messages() {
            // These models/templates only support a single system message.
            let system_text = request.system_text();
            if !system_text.is_empty() {
                messages.push(OpenAIMessage::system_text(system_text));
            }
        } else {
            for system in request.system_prompts() {
                messages.push(OpenAIMessage::system_text(system.to_string()));
            }
        }
    }

    for message in request.messages.iter() {
        messages.extend(to_open_ai_message(message.as_ref(), profile)?);
    }

    // Models like Devstral don't support the system role.
    // Prepend system text to the first user message instead.
    if !profile.supports_system_role() {
        let system_text = request.system_text();
        if !system_text.is_empty() {
            if let Some(msg) = messages.iter_mut().find(|m| m.role == "user") {
                msg.prepend_text(&system_text);
            } else {
                // No user message to carry it (tool-only or resumed conversation):
                // inject a leading user message rather than dropping the
                // entire system prompt.
                messages
                    .insert(0, OpenAIMessage::new("user", Some(OpenAIContent::Text(system_text))));
            }
        }
    }

    let tools = convert_tools(request.tools.to_vec());
    let tool_choice = request.resolved_tool_choice()?.map(|choice| match choice {
        ToolChoice::Required => OpenAIToolChoice::Required,
        ToolChoice::Tool(name) => OpenAIToolChoice::Function { name: name.clone() },
        ToolChoice::Forbid => OpenAIToolChoice::None,
    });

    let wire = OpenAIRequest {
        model: request.model.clone(),
        messages,
        reasoning_effort: thinking.reasoning_effort,
        max_tokens: request.max_tokens,
        temperature: request.temperature,
        stop: request.stop_sequences.as_ref().map(|s| serde_json::json!(s)),
        tools,
        tool_choice,
        thinking: thinking.thinking,
        enable_thinking: thinking.enable_thinking,
        ..Default::default()
    };
    debug!(
        "OpenAI-compatible request: {}",
        serde_json::to_string_pretty(&wire).unwrap_or_default()
    );
    Ok(wire)
}

fn to_openai_role(role: &Role) -> String {
    match role {
        Role::User => "user".to_string(),
        Role::Model => "assistant".to_string(),
        Role::System => "developer".to_string(),
        Role::Custom(role) => role.clone(),
    }
}

fn openai_item_for_image(image: &Attachment) -> OpenAIContentItem {
    OpenAIContentItem::ImageUrl { image_url: ImageUrl { url: image.to_uri() } }
}

/// Note: OpenAI-compatible APIs typically don't support document types (PDFs, etc.).
/// Documents are converted to a text placeholder explaining the limitation.
fn openai_item_for_document(document: &Attachment) -> OpenAIContentItem {
    let media_type = match document {
        Attachment::Base64 { media_type, .. } => media_type.clone(),
        Attachment::Url { url } => format!("url:{url}"),
    };
    OpenAIContentItem::Text {
        text: format!(
            "[Document content (type: {media_type}) - model does not support document vision]"
        ),
    }
}

impl TryFrom<&ToolUse> for OpenAIToolCall {
    type Error = anyhow::Error;

    fn try_from(tool_use: &ToolUse) -> Result<Self> {
        Ok(OpenAIToolCall {
            id: tool_use.id.clone(),
            call_type: "function".to_string(),
            function: FunctionCall {
                name: tool_use.name.clone(),
                arguments: serde_json::to_string(replay_safe_tool_args(tool_use).as_ref())?,
            },
        })
    }
}

/// Result of converting a ToolResult to OpenAI format.
/// Chat Completions doesn't support images in tool role messages, so we may return
/// both a tool message and a separate user message containing images.
struct ToolResultConversion {
    tool_message: OpenAIMessage,
    image_message: Option<OpenAIMessage>,
}

fn tool_result_to_openai(result: &ToolResult) -> ToolResultConversion {
    let mut text_content = String::new();
    let mut image_items: Vec<OpenAIContentItem> = Vec::new();

    match &result.content {
        Content::Text(text) => {
            text_content = text.clone();
        }
        Content::Parts(parts) => {
            for part in parts {
                match part {
                    ContentPart::Text(text) => {
                        if !text_content.is_empty() {
                            text_content.push('\n');
                        }
                        text_content.push_str(text);
                    }
                    ContentPart::Image(image) => {
                        image_items.push(openai_item_for_image(image));
                    }
                    ContentPart::Document(document) => {
                        image_items.push(openai_item_for_document(document));
                    }
                    _ => {}
                }
            }
        }
    }

    // Images follow the whole batch of tool responses, so positional association
    // is ambiguous when some results have no attachments. Label both sides.
    if !image_items.is_empty() {
        if !text_content.is_empty() {
            text_content.push('\n');
        }
        text_content.push_str(&format!(
            "[Attachments from tool call {} are included below.]",
            result.tool_use_id
        ));
        image_items.insert(
            0,
            OpenAIContentItem::Text {
                text: format!("Attachments from tool call {}:", result.tool_use_id),
            },
        );
    }
    let tool_message =
        OpenAIMessage::tool_response(result.tool_use_id.clone(), OpenAIContent::Text(text_content));

    // The images ride in a user message of their own.
    let image_message = if image_items.is_empty() {
        None
    } else {
        Some(OpenAIMessage::new("user", Some(OpenAIContent::List(image_items))))
    };

    ToolResultConversion { tool_message, image_message }
}

/// Convert a single ContentPart to OpenAI content items (for non-tool-result parts)
fn content_part_to_openai_items(part: &ContentPart) -> Vec<OpenAIContentItem> {
    match part {
        ContentPart::Text(text) => vec![OpenAIContentItem::Text { text: text.clone() }],
        ContentPart::Image(image) => vec![openai_item_for_image(image)],
        ContentPart::Document(document) => vec![openai_item_for_document(document)],
        ContentPart::RedactedThinking { .. } => vec![],
        // Non-assistant thinking and other types are converted to debug text.
        other => vec![OpenAIContentItem::Text { text: format!("{other:?}") }],
    }
}

pub(in crate::openai_compatible) fn to_open_ai_message(
    message: &Message,
    profile: OpenAiCompatProfile,
) -> Result<Vec<OpenAIMessage>> {
    let role = to_openai_role(&message.role);
    let is_assistant = matches!(message.role, Role::Model);

    match &message.content {
        Content::Text(text) => {
            let mut msg = OpenAIMessage::new(role, Some(OpenAIContent::Text(text.clone())));
            // As in the Content::Parts branch: some thinking dialects require
            // `reasoning_content` on every assistant message in a span that
            // contains a tool_call. A plain-text assistant message carries no
            // Thinking parts, so emit an empty string.
            if profile.requires_assistant_reasoning() && is_assistant {
                msg.reasoning_content = Some(String::new());
            }
            Ok(vec![msg])
        }
        Content::Parts(parts) => {
            let mut messages = Vec::new();
            let mut image_messages = Vec::new();
            let mut items = Vec::new();
            let mut tool_calls = Vec::new();
            let mut reasoning_content: Option<String> = None;

            for part in parts {
                match part {
                    ContentPart::ToolUse(tool_use) => {
                        tool_calls.push(OpenAIToolCall::try_from(tool_use)?);
                    }
                    ContentPart::ToolResult(result) => {
                        // Collect tool messages and image messages separately to avoid
                        // interleaving user messages between tool responses (which breaks
                        // APIs that require all tool responses to immediately follow the
                        // assistant message with tool_calls).
                        let conversion = tool_result_to_openai(result);
                        messages.push(conversion.tool_message);
                        if let Some(image_msg) = conversion.image_message {
                            image_messages.push(image_msg);
                        }
                    }
                    // Extract thinking content for DeepSeek's reasoning_content field (assistant only)
                    ContentPart::Thinking { text, .. } if is_assistant => {
                        match &mut reasoning_content {
                            Some(existing) => {
                                existing.push('\n');
                                existing.push_str(text);
                            }
                            None => {
                                reasoning_content = Some(text.clone());
                            }
                        }
                    }
                    // All other content parts (Text, Image, Document, non-assistant Thinking)
                    other => {
                        items.extend(content_part_to_openai_items(other));
                    }
                }
            }

            // OpenAI/DeepSeek require `content` or `tool_calls` on every
            // assistant message. When the only parts were Thinking blocks
            // (e.g. DeepSeek hit `finish_reason: "length"` mid-thought, or a
            // stream cut off after only `reasoning_content` chunks), both are
            // empty, which DeepSeek V4 rejects with HTTP 400 "content or
            // tool_calls must be set". Send empty text instead.
            let content = if !items.is_empty() {
                Some(OpenAIContent::List(items))
            } else if is_assistant && tool_calls.is_empty() && messages.is_empty() {
                Some(OpenAIContent::Text(String::new()))
            } else {
                None
            };

            // DeepSeek V4 thinking mode returns HTTP 400 when any assistant
            // message between two user turns lacks `reasoning_content` and an
            // assistant in that span made a tool call, plain-text summary
            // turns included. Fall back to an empty string so serde emits the
            // field. Both replayed reasoning and the fallback are scoped by
            // profile because most OpenAI-compatible providers reject unknown
            // fields. Thinking was consumed above, so omitting the field
            // cannot leak it into visible content.
            let resolved_reasoning = if profile.requires_assistant_reasoning() && is_assistant {
                Some(reasoning_content.unwrap_or_default())
            } else {
                None
            };

            if tool_calls.is_empty() {
                if messages.is_empty() {
                    let mut msg = OpenAIMessage::new(role, content);
                    msg.reasoning_content = resolved_reasoning;
                    messages.push(msg);
                }
            } else if messages.is_empty() {
                messages.push(OpenAIMessage::with_tool_calls(
                    role,
                    content,
                    resolved_reasoning,
                    tool_calls,
                ));
            }

            // Append image user messages after all tool response messages so they
            // don't break the tool_call_id response chain.
            messages.extend(image_messages);

            Ok(messages)
        }
    }
}

pub(in crate::openai_compatible) fn convert_tools(
    tools: Vec<ToolDefinition>,
) -> Option<Vec<OpenAITool>> {
    if tools.is_empty() {
        return None;
    }

    Some(
        tools
            .into_iter()
            .map(|tool| OpenAITool {
                tool_type: "function".to_string(),
                function: OpenAIToolFunction {
                    name: tool.name,
                    description: tool.description.unwrap_or_default(),
                    parameters: materialize_empty_properties(tool.input_schema),
                },
            })
            .collect(),
    )
}

/// The canonical schema form omits empty `properties` because Gemini rejects
/// it (see `normalize_tool_schema`), but some OpenAI-compatible endpoints
/// require the key on object schemas, so parameterless tools must render as
/// `{"type": "object", "properties": {}}` on this wire.
fn materialize_empty_properties(mut schema: serde_json::Value) -> serde_json::Value {
    if let Some(obj) = schema.as_object_mut()
        && obj.get("type").is_some_and(|t| t == "object")
        && !obj.contains_key("properties")
    {
        obj.insert("properties".to_string(), serde_json::Value::Object(serde_json::Map::new()));
    }
    schema
}

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

    #[test]
    fn parameterless_tool_renders_empty_properties() {
        let tools = vec![ToolDefinition {
            name: "no_args".to_string(),
            description: Some("takes nothing".to_string()),
            input_schema: json!({"type": "object"}),
        }];

        let converted = convert_tools(tools).unwrap();

        assert_eq!(converted[0].function.parameters, json!({"type": "object", "properties": {}}));
    }
}