mod error;
mod repair;
mod schema;
mod strategies;
pub use error::ToolCallExtractError;
pub use repair::{DEFAULT_MAX_REPAIR_ATTEMPTS, extract_with_repair};
pub use schema::SchemaViolation;
use serde_json::Value;
use crate::llm::ChatResponse;
const FALLBACK_CALL_ID: &str = "fallback-call-0";
type SchemaLookup<'a> = Box<dyn Fn(&str) -> Option<Value> + Send + Sync + 'a>;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExtractionStrategy {
Native,
FencedJson,
AngleBracket,
BalancedJsonScan,
}
#[derive(Debug, Clone, PartialEq)]
pub struct ExtractedToolCall {
pub id: String,
pub name: String,
pub arguments: Value,
pub strategy: ExtractionStrategy,
}
pub fn strategy_order_for(model_slug: &str) -> [ExtractionStrategy; 3] {
let lower = model_slug.to_ascii_lowercase();
if lower.contains("qwen") || lower.contains("deepseek") {
[
ExtractionStrategy::AngleBracket,
ExtractionStrategy::FencedJson,
ExtractionStrategy::BalancedJsonScan,
]
} else {
[
ExtractionStrategy::FencedJson,
ExtractionStrategy::AngleBracket,
ExtractionStrategy::BalancedJsonScan,
]
}
}
pub struct ToolCallExtractor<'a> {
schema_lookup: SchemaLookup<'a>,
}
impl<'a> ToolCallExtractor<'a> {
pub fn new(schema_lookup: impl Fn(&str) -> Option<Value> + Send + Sync + 'a) -> Self {
Self {
schema_lookup: Box::new(schema_lookup),
}
}
pub fn extract(
&self,
response: &ChatResponse,
model_slug: &str,
) -> Result<Vec<ExtractedToolCall>, ToolCallExtractError> {
let native = response.first_tool_calls();
if !native.is_empty() {
let mut out = Vec::with_capacity(native.len());
for call in native {
let args =
self.parse_and_validate(&call.function.name, &call.function.arguments)?;
out.push(ExtractedToolCall {
id: call.id.clone(),
name: call.function.name.clone(),
arguments: args,
strategy: ExtractionStrategy::Native,
});
}
return Ok(out);
}
let text = response.first_text().unwrap_or_default();
let order = strategy_order_for(model_slug);
for strategy in order {
let candidate = match strategy {
ExtractionStrategy::FencedJson => strategies::extract_fenced_json(&text),
ExtractionStrategy::AngleBracket => strategies::extract_angle_bracket(&text),
ExtractionStrategy::BalancedJsonScan => {
strategies::extract_balanced_json_scan(&text)
}
ExtractionStrategy::Native => {
unreachable!("strategy_order_for never returns Native")
}
};
if let Some((name, args)) = candidate {
let validated = self.validate(&name, args, strategy)?;
return Ok(vec![ExtractedToolCall {
id: FALLBACK_CALL_ID.to_string(),
..validated
}]);
}
}
Err(ToolCallExtractError::NoCallFound {
tried: order.to_vec(),
})
}
pub fn parse_and_validate(
&self,
name: &str,
raw_arguments: &str,
) -> Result<Value, ToolCallExtractError> {
let trimmed = raw_arguments.trim();
let args: Value = if trimmed.is_empty() {
Value::Object(Default::default())
} else {
serde_json::from_str(trimmed).map_err(|source| {
ToolCallExtractError::MalformedArguments {
name: name.to_string(),
source,
}
})?
};
self.validate(name, args, ExtractionStrategy::Native)
.map(|c| c.arguments)
}
fn validate(
&self,
name: &str,
args: Value,
strategy: ExtractionStrategy,
) -> Result<ExtractedToolCall, ToolCallExtractError> {
let schema =
(self.schema_lookup)(name).ok_or_else(|| ToolCallExtractError::UnknownTool {
name: name.to_string(),
})?;
let parameters = schema
.get("function")
.and_then(|f| f.get("parameters"))
.cloned()
.unwrap_or_else(|| Value::Object(Default::default()));
schema::validate_args(¶meters, &args).map_err(|violations| {
ToolCallExtractError::SchemaInvalid {
name: name.to_string(),
violations,
}
})?;
Ok(ExtractedToolCall {
id: String::new(),
name: name.to_string(),
arguments: args,
strategy,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn bash_schema_entry() -> Value {
json!({
"type": "function",
"function": {
"name": "bash",
"parameters": {
"type": "object",
"properties": { "command": { "type": "string" } },
"required": ["command"],
"additionalProperties": false
}
}
})
}
fn extractor_with_bash() -> ToolCallExtractor<'static> {
ToolCallExtractor::new(|name| match name {
"bash" => Some(bash_schema_entry()),
_ => None,
})
}
fn response_with_native_call(name: &str, arguments: &str) -> ChatResponse {
let fixture = format!(
r#"{{
"id": "gen-1",
"choices": [{{
"message": {{
"role": "assistant",
"content": null,
"tool_calls": [{{
"id": "call_1",
"type": "function",
"function": {{"name": "{name}", "arguments": {arguments:?}}}
}}]
}},
"finish_reason": "tool_calls"
}}],
"usage": {{"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}}
}}"#
);
serde_json::from_str(&fixture).expect("fixture deserialises")
}
fn response_with_text(text: &str) -> ChatResponse {
let fixture = json!({
"id": "gen-2",
"choices": [{
"message": { "role": "assistant", "content": text, "tool_calls": [] },
"finish_reason": "stop"
}],
"usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}
});
serde_json::from_str(&fixture.to_string()).expect("fixture deserialises")
}
#[test]
fn extract_native_success() {
let resp = response_with_native_call("bash", r#"{"command": "ls"}"#);
let extractor = extractor_with_bash();
let calls = extractor
.extract(&resp, "anthropic/claude-sonnet-4-5")
.expect("extract");
assert_eq!(calls.len(), 1);
assert_eq!(calls[0].id, "call_1");
assert_eq!(calls[0].name, "bash");
assert_eq!(calls[0].arguments, json!({"command": "ls"}));
assert_eq!(calls[0].strategy, ExtractionStrategy::Native);
}
#[test]
fn extract_fenced_json_success() {
let text = "```json\n{\"name\": \"bash\", \"arguments\": {\"command\": \"pwd\"}}\n```";
let resp = response_with_text(text);
let extractor = extractor_with_bash();
let calls = extractor
.extract(&resp, "google/gemma-2-27b-it")
.expect("extract");
assert_eq!(calls[0].name, "bash");
assert_eq!(calls[0].strategy, ExtractionStrategy::FencedJson);
assert_eq!(calls[0].id, FALLBACK_CALL_ID);
}
#[test]
fn extract_angle_bracket_success() {
let text = "<tool_call>{\"name\": \"bash\", \"arguments\": {\"command\": \"echo hi\"}}</tool_call>";
let resp = response_with_text(text);
let extractor = extractor_with_bash();
let calls = extractor
.extract(&resp, "qwen/qwen-2.5-coder-32b-instruct")
.expect("extract");
assert_eq!(calls[0].name, "bash");
assert_eq!(calls[0].strategy, ExtractionStrategy::AngleBracket);
}
#[test]
fn parse_and_validate_success() {
let extractor = extractor_with_bash();
let args = extractor
.parse_and_validate("bash", r#"{"command": "ls"}"#)
.expect("valid");
assert_eq!(args, json!({"command": "ls"}));
}
#[test]
fn parse_and_validate_empty_string_becomes_empty_object() {
let extractor = extractor_with_bash();
let err = extractor
.parse_and_validate("bash", "")
.expect_err("missing required field");
assert!(matches!(err, ToolCallExtractError::SchemaInvalid { .. }));
}
#[test]
fn parse_and_validate_malformed_json() {
let extractor = extractor_with_bash();
let err = extractor
.parse_and_validate("bash", "not json")
.expect_err("malformed");
assert!(
matches!(err, ToolCallExtractError::MalformedArguments { name, .. } if name == "bash")
);
}
#[test]
fn extract_no_call_found() {
let resp = response_with_text("Sure, here's the answer: 42.");
let extractor = extractor_with_bash();
let err = extractor
.extract(&resp, "google/gemma-2-27b-it")
.expect_err("should fail");
assert!(matches!(err, ToolCallExtractError::NoCallFound { .. }));
}
#[test]
fn extract_native_malformed_arguments() {
let resp = response_with_native_call("bash", "{not valid json");
let extractor = extractor_with_bash();
let err = extractor
.extract(&resp, "anthropic/claude-sonnet-4-5")
.expect_err("should fail");
assert!(
matches!(err, ToolCallExtractError::MalformedArguments { name, .. } if name == "bash")
);
}
#[test]
fn extract_unknown_tool() {
let resp = response_with_native_call("frobnicate", "{}");
let extractor = extractor_with_bash();
let err = extractor
.extract(&resp, "anthropic/claude-sonnet-4-5")
.expect_err("should fail");
assert!(matches!(err, ToolCallExtractError::UnknownTool { name } if name == "frobnicate"));
}
#[test]
fn extract_schema_invalid_arguments() {
let resp = response_with_native_call("bash", "{}");
let extractor = extractor_with_bash();
let err = extractor
.extract(&resp, "anthropic/claude-sonnet-4-5")
.expect_err("should fail");
assert!(matches!(err, ToolCallExtractError::SchemaInvalid { name, .. } if name == "bash"));
}
#[test]
fn strategy_order_prefers_angle_bracket_for_qwen_and_deepseek() {
for slug in ["qwen/qwen-2.5-coder-32b-instruct", "deepseek/deepseek-chat"] {
assert_eq!(
strategy_order_for(slug)[0],
ExtractionStrategy::AngleBracket
);
}
}
#[test]
fn strategy_order_prefers_fenced_json_for_others() {
for slug in ["google/gemma-2-27b-it", "mistralai/mixtral-8x7b"] {
assert_eq!(strategy_order_for(slug)[0], ExtractionStrategy::FencedJson);
}
}
}