use std::future::Future;
use super::error::ToolCallExtractError;
use super::{ExtractedToolCall, ToolCallExtractor};
use crate::llm::ChatResponse;
pub const DEFAULT_MAX_REPAIR_ATTEMPTS: u32 = 2;
pub fn build_corrective_message(error: &ToolCallExtractError) -> String {
match error {
ToolCallExtractError::NoCallFound { tried } => format!(
"Your previous response did not contain a recognisable tool call. \
Please emit exactly one tool call using either the native function-call \
mechanism, a ```json fenced block shaped like {{\"name\": \"<tool>\", \"arguments\": {{...}}}}, \
or a <tool_call>{{...}}</tool_call> tag. (Already checked and found nothing: {tried:?}.)"
),
ToolCallExtractError::MalformedArguments { name, source } => format!(
"Your call to '{name}' had arguments that are not valid JSON ({source}). \
Please re-emit the call to '{name}' with syntactically valid JSON arguments."
),
ToolCallExtractError::UnknownTool { name } => format!(
"'{name}' is not a recognised tool in this conversation. \
Please re-emit your call using one of the tools already provided to you."
),
ToolCallExtractError::SchemaInvalid { name, violations } => {
let details = violations
.iter()
.map(|v| format!("- {v}"))
.collect::<Vec<_>>()
.join("\n");
format!(
"Your call to '{name}' had invalid arguments:\n{details}\n\
Please re-emit the call to '{name}' with corrected arguments that satisfy every point above."
)
}
ToolCallExtractError::Retry(source) => format!(
"A transient error occurred while requesting a repair ({source}). Please try again."
),
ToolCallExtractError::Unrepairable { .. } => {
"the previous tool call could not be repaired".to_string()
}
}
}
pub async fn extract_with_repair<F, Fut>(
extractor: &ToolCallExtractor<'_>,
mut response: ChatResponse,
model_slug: &str,
max_attempts: u32,
mut retry: F,
) -> Result<Vec<ExtractedToolCall>, ToolCallExtractError>
where
F: FnMut(String) -> Fut,
Fut: Future<Output = Result<ChatResponse, ToolCallExtractError>>,
{
let mut attempts = 0u32;
loop {
match extractor.extract(&response, model_slug) {
Ok(calls) => return Ok(calls),
Err(err) => {
if attempts >= max_attempts {
return Err(ToolCallExtractError::Unrepairable {
attempts,
last_error: Box::new(err),
});
}
let corrective = build_corrective_message(&err);
attempts += 1;
response = retry(corrective).await?;
}
}
}
}
#[cfg(test)]
mod tests {
use std::sync::atomic::{AtomicU32, Ordering};
use serde_json::json;
use super::*;
fn bash_schema_entry() -> serde_json::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(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": "bash", "arguments": {arguments:?}}}
}}]
}},
"finish_reason": "tool_calls"
}}],
"usage": {{"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}}
}}"#
);
serde_json::from_str(&fixture).expect("fixture deserialises")
}
#[test]
fn default_is_two() {
assert_eq!(DEFAULT_MAX_REPAIR_ATTEMPTS, 2);
}
#[test]
fn corrective_message_names_missing_field() {
let err = ToolCallExtractError::SchemaInvalid {
name: "bash".into(),
violations: vec![super::super::SchemaViolation {
path: "$".into(),
message: "missing required property 'command'".into(),
}],
};
let msg = build_corrective_message(&err);
assert!(msg.contains("bash"));
assert!(msg.contains("command"));
}
#[test]
fn corrective_message_for_malformed_json() {
let parse_err = serde_json::from_str::<serde_json::Value>("{not json").unwrap_err();
let err = ToolCallExtractError::MalformedArguments {
name: "bash".into(),
source: parse_err,
};
let msg = build_corrective_message(&err);
assert!(msg.contains("bash"));
assert!(msg.contains("valid JSON"));
}
#[tokio::test]
async fn succeeds_immediately_without_calling_retry() {
let extractor = extractor_with_bash();
let response = response_with_native_call(r#"{"command": "ls"}"#);
let result = extract_with_repair(
&extractor,
response,
"anthropic/claude-sonnet-4-5",
DEFAULT_MAX_REPAIR_ATTEMPTS,
|_corrective| async { panic!("retry must not be called on first-attempt success") },
)
.await
.expect("should succeed without repair");
assert_eq!(result[0].name, "bash");
}
#[tokio::test]
async fn malformed_then_one_repair_succeeds() {
let extractor = extractor_with_bash();
let first = response_with_native_call("{}"); let call_count = AtomicU32::new(0);
let result = extract_with_repair(
&extractor,
first,
"anthropic/claude-sonnet-4-5",
DEFAULT_MAX_REPAIR_ATTEMPTS,
|corrective| {
call_count.fetch_add(1, Ordering::SeqCst);
assert!(
corrective.contains("command"),
"corrective message: {corrective}"
);
async { Ok(response_with_native_call(r#"{"command": "ls"}"#)) }
},
)
.await
.expect("should succeed after one repair");
assert_eq!(result[0].name, "bash");
assert_eq!(result[0].arguments, json!({"command": "ls"}));
assert_eq!(
call_count.load(Ordering::SeqCst),
1,
"exactly one repair round-trip"
);
}
#[tokio::test]
async fn unrepairable_after_max_attempts_returns_structured_error() {
let extractor = extractor_with_bash();
let call_count = AtomicU32::new(0);
let max_attempts = 2;
let err = extract_with_repair(
&extractor,
response_with_native_call("{}"),
"anthropic/claude-sonnet-4-5",
max_attempts,
|_corrective| {
call_count.fetch_add(1, Ordering::SeqCst);
let resp = response_with_native_call("{}");
async move { Ok(resp) }
},
)
.await
.expect_err("should be unrepairable");
match err {
ToolCallExtractError::Unrepairable {
attempts,
last_error,
} => {
assert_eq!(attempts, max_attempts);
assert!(matches!(
*last_error,
ToolCallExtractError::SchemaInvalid { .. }
));
}
other => panic!("expected Unrepairable, got {other:?}"),
}
assert_eq!(
call_count.load(Ordering::SeqCst),
max_attempts,
"retry must be called exactly max_attempts times"
);
}
#[tokio::test]
async fn retry_failure_propagates_immediately() {
let extractor = extractor_with_bash();
let first = response_with_native_call("{}");
let err = extract_with_repair(
&extractor,
first,
"anthropic/claude-sonnet-4-5",
DEFAULT_MAX_REPAIR_ATTEMPTS,
|_corrective| async {
Err(ToolCallExtractError::UnknownTool {
name: "irrelevant".into(),
})
},
)
.await
.expect_err("should propagate the retry error");
assert!(matches!(err, ToolCallExtractError::UnknownTool { .. }));
}
}