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 std::borrow::Cow;

use serde_json::{Map, Value};

use super::{MalformedToolArgs, ToolUse};

/// Decode model-emitted tool arguments while retaining malformed input for feedback.
/// Empty input is the wire convention for a no-argument call and maps to `{}`.
pub(crate) fn decode_tool_args(raw: &str) -> (Value, Option<MalformedToolArgs>) {
    let normalized = if raw.trim().is_empty() { "{}" } else { raw };
    match serde_json::from_str(normalized) {
        Ok(args) => (args, None),
        Err(error) => (
            Value::Object(Map::new()),
            Some(MalformedToolArgs { raw: raw.to_string(), error: error.to_string() }),
        ),
    }
}

/// A tool call from its raw argument string.
pub(crate) fn decoded_tool_use(id: String, name: String, raw: &str) -> ToolUse {
    let (args, malformed_args) = decode_tool_args(raw);
    ToolUse { id, name, args, malformed_args, signature: None }
}

/// Arguments safe to serialize when replaying a tool call to any model provider.
/// Malformed calls keep their raw input only as diagnostic metadata and replay as `{}`.
pub(crate) fn replay_safe_tool_args(tool_use: &ToolUse) -> Cow<'_, Value> {
    if tool_use.malformed_args.is_some() {
        Cow::Owned(Value::Object(Map::new()))
    } else {
        Cow::Borrowed(&tool_use.args)
    }
}

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

    #[test]
    fn decode_preserves_malformed_input_with_a_safe_placeholder() {
        let raw = "{oops";
        let (args, malformed) = decode_tool_args(raw);
        assert_eq!(args, serde_json::json!({}));
        let malformed = malformed.expect("malformed metadata");
        assert_eq!(malformed.raw, raw);
        assert!(!malformed.error.is_empty());
        assert!(!malformed.error.contains(raw));
    }
}