use rig_core::message::{Message, ToolChoice};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "reason", rename_all = "snake_case")]
#[non_exhaustive]
pub enum InvalidToolCallReason {
UnknownTool,
DisallowedByToolChoice,
MalformedArguments {
error: String,
},
}
impl InvalidToolCallReason {
pub fn malformed_arguments(raw: &str) -> Self {
Self::MalformedArguments {
error: arguments_parse_error(raw),
}
}
}
pub(crate) fn arguments_parse_error(raw: &str) -> String {
match serde_json::from_str::<serde_json::Value>(raw) {
Err(error) => error.to_string(),
Ok(value) => format!("expected a JSON object, found {}", json_kind(&value)),
}
}
fn json_kind(value: &serde_json::Value) -> &'static str {
match value {
serde_json::Value::Null => "null",
serde_json::Value::Bool(_) => "a boolean",
serde_json::Value::Number(_) => "a number",
serde_json::Value::String(_) => "a string",
serde_json::Value::Array(_) => "an array",
serde_json::Value::Object(_) => "an object",
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct InvalidToolCallContext {
pub tool_name: String,
pub tool_call_id: Option<rig_core::message::CallId>,
pub args: Option<String>,
pub available_tools: Vec<String>,
pub allowed_tools: Vec<String>,
pub tool_choice: Option<ToolChoice>,
pub chat_history: Vec<Message>,
pub is_streaming: bool,
pub reason: InvalidToolCallReason,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum RetryRequest {
Repeat,
Feedback(String),
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum InvalidToolCallAction {
Fail,
Retry {
feedback: String,
},
Repair {
tool_name: String,
},
Skip {
reason: String,
},
Stop {
reason: String,
},
}
impl InvalidToolCallAction {
pub fn fail() -> Self {
Self::Fail
}
pub fn retry(feedback: impl Into<String>) -> Self {
Self::Retry {
feedback: feedback.into(),
}
}
pub fn repair(tool_name: impl Into<String>) -> Self {
Self::Repair {
tool_name: tool_name.into(),
}
}
pub fn skip(reason: impl Into<String>) -> Self {
Self::Skip {
reason: reason.into(),
}
}
pub fn stop(reason: impl Into<String>) -> Self {
Self::Stop {
reason: reason.into(),
}
}
}
#[cfg(test)]
mod tests;