use std::future::Future;
use rig_core::tool::{IntoToolOutput, Tool, ToolContext, ToolExecutionError};
use serde_json::Value;
use vld::llm::{LlmFeedbackOptions, LlmSchema, LlmSchemaError, Provider};
use vld::schema::VldParse;
pub trait VldToolHandler: Send + Sync {
const NAME: &'static str;
type Args: VldParse + LlmSchema + Send;
type Output: IntoToolOutput;
type Error: std::error::Error + Send + Sync + 'static;
fn description(&self) -> String;
fn call(
&self,
args: Self::Args,
) -> impl Future<Output = Result<Self::Output, Self::Error>> + Send;
}
pub struct VldTool<H> {
handler: H,
schema: Value,
}
impl<H: VldToolHandler> VldTool<H> {
pub fn new(handler: H) -> Result<Self, LlmSchemaError> {
Self::for_provider(handler, Provider::Generic)
}
pub fn for_provider(handler: H, provider: Provider) -> Result<Self, LlmSchemaError> {
Ok(Self {
schema: H::Args::llm_schema(provider)?,
handler,
})
}
pub fn handler(&self) -> &H {
&self.handler
}
}
pub fn parse_args<T: VldParse>(
args: &Value,
schema: Option<&Value>,
) -> Result<T, ToolExecutionError> {
T::vld_parse_value(args).map_err(|e| {
let options = LlmFeedbackOptions {
schema: schema.cloned(),
..Default::default()
};
ToolExecutionError::invalid_args(e.llm_feedback_with(&options))
})
}
impl<H: VldToolHandler> Tool for VldTool<H> {
const NAME: &'static str = H::NAME;
type Args = Value;
type Output = H::Output;
type Error = ToolExecutionError;
fn description(&self) -> String {
self.handler.description()
}
fn parameters(&self) -> Value {
self.schema.clone()
}
async fn call(
&self,
_: &mut ToolContext,
args: Value,
) -> Result<H::Output, ToolExecutionError> {
let args = parse_args::<H::Args>(&args, Some(&self.schema))?;
self.handler
.call(args)
.await
.map_err(ToolExecutionError::from_error)
}
}