use crate::ai::message::ContentBlock;
use crate::ai::model::Tool;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ToolValidationError {
NotAToolCall,
NameMismatch { expected: String, actual: String },
InvalidSchema(String),
Invalid(Vec<String>),
}
impl std::fmt::Display for ToolValidationError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ToolValidationError::NotAToolCall => write!(f, "content block is not a tool call"),
ToolValidationError::NameMismatch { expected, actual } => {
write!(
f,
"tool name mismatch: expected `{expected}`, got `{actual}`"
)
}
ToolValidationError::InvalidSchema(m) => write!(f, "invalid tool schema: {m}"),
ToolValidationError::Invalid(errors) => {
write!(f, "tool arguments invalid: {}", errors.join("; "))
}
}
}
}
impl std::error::Error for ToolValidationError {}
pub fn validate_tool_call(tool: &Tool, call: &ContentBlock) -> Result<(), ToolValidationError> {
let (name, arguments) = match call {
ContentBlock::ToolCall {
name, arguments, ..
} => (name, arguments),
_ => return Err(ToolValidationError::NotAToolCall),
};
if name != &tool.name {
return Err(ToolValidationError::NameMismatch {
expected: tool.name.clone(),
actual: name.clone(),
});
}
let validator = jsonschema::validator_for(&tool.parameters)
.map_err(|e| ToolValidationError::InvalidSchema(e.to_string()))?;
let errors: Vec<String> = validator
.iter_errors(arguments)
.map(|e| e.to_string())
.collect();
if errors.is_empty() {
Ok(())
} else {
Err(ToolValidationError::Invalid(errors))
}
}
#[cfg(test)]
#[path = "validation_tests.rs"]
mod tests;