Skip to main content

vld_web/
rig.rs

1//! [rig](https://docs.rs/rig-core) tools whose arguments are validated by vld.
2//!
3//! Implement [`VldToolHandler`] (name, description, a vld `Args` type and
4//! `call`) and register [`VldTool::new(handler)?`](VldTool::new) as a rig
5//! [`Tool`]: its `parameters()` is the vld schema prepared for the chosen
6//! [`Provider`], and arguments that fail validation return
7//! [`ToolExecutionError::invalid_args`] whose model-visible text is
8//! [`VldError::llm_feedback`](vld::error::VldError::llm_feedback), so the
9//! model can retry the call.
10//!
11//! ```ignore
12//! use vld_web::rig::{VldTool, VldToolHandler};
13//!
14//! vld::schema! {
15//!     #[derive(Debug)]
16//!     pub struct AddArgs { pub a: i64 => vld::i64(), pub b: i64 => vld::i64().min(0) }
17//! }
18//!
19//! struct Add;
20//! impl VldToolHandler for Add {
21//!     const NAME: &'static str = "add";
22//!     type Args = AddArgs;
23//!     type Output = i64;
24//!     type Error = std::convert::Infallible;
25//!     fn description(&self) -> String { "Add two numbers".into() }
26//!     async fn call(&self, args: AddArgs) -> Result<i64, Self::Error> { Ok(args.a + args.b) }
27//! }
28//!
29//! let tool = VldTool::new(Add)?; // a rig `Tool`
30//! ```
31
32use std::future::Future;
33
34use rig_core::tool::{IntoToolOutput, Tool, ToolContext, ToolExecutionError};
35use serde_json::Value;
36use vld::llm::{LlmFeedbackOptions, LlmSchema, LlmSchemaError, Provider};
37use vld::schema::VldParse;
38
39/// A rig tool with vld-validated arguments; wrap it in [`VldTool`].
40pub trait VldToolHandler: Send + Sync {
41    /// Registration and provider-facing name.
42    const NAME: &'static str;
43    /// The arguments, validated by vld before [`call`](Self::call).
44    type Args: VldParse + LlmSchema + Send;
45    /// The tool's output.
46    type Output: IntoToolOutput;
47    /// The tool's own error (not argument validation).
48    type Error: std::error::Error + Send + Sync + 'static;
49
50    /// What the tool does, for the model.
51    fn description(&self) -> String;
52
53    /// Run the tool on validated arguments.
54    fn call(
55        &self,
56        args: Self::Args,
57    ) -> impl Future<Output = Result<Self::Output, Self::Error>> + Send;
58}
59
60/// A [`VldToolHandler`] as a rig [`Tool`].
61pub struct VldTool<H> {
62    handler: H,
63    schema: Value,
64}
65
66impl<H: VldToolHandler> VldTool<H> {
67    /// The tool with a plain JSON Schema ([`Provider::Generic`]).
68    pub fn new(handler: H) -> Result<Self, LlmSchemaError> {
69        Self::for_provider(handler, Provider::Generic)
70    }
71
72    /// The tool with its schema prepared for `provider` (e.g.
73    /// [`Provider::OpenAiStrict`] for strict function calling); fails when
74    /// the provider would reject the schema.
75    pub fn for_provider(handler: H, provider: Provider) -> Result<Self, LlmSchemaError> {
76        Ok(Self {
77            schema: H::Args::llm_schema(provider)?,
78            handler,
79        })
80    }
81
82    /// The wrapped handler.
83    pub fn handler(&self) -> &H {
84        &self.handler
85    }
86}
87
88/// Parse tool arguments as `T`; a failure is an `invalid_args` error whose
89/// model-visible text is the feedback (unknown keys hinted from `schema`).
90pub fn parse_args<T: VldParse>(
91    args: &Value,
92    schema: Option<&Value>,
93) -> Result<T, ToolExecutionError> {
94    T::vld_parse_value(args).map_err(|e| {
95        let options = LlmFeedbackOptions {
96            schema: schema.cloned(),
97            ..Default::default()
98        };
99        ToolExecutionError::invalid_args(e.llm_feedback_with(&options))
100    })
101}
102
103impl<H: VldToolHandler> Tool for VldTool<H> {
104    const NAME: &'static str = H::NAME;
105    type Args = Value;
106    type Output = H::Output;
107    type Error = ToolExecutionError;
108
109    fn description(&self) -> String {
110        self.handler.description()
111    }
112
113    fn parameters(&self) -> Value {
114        self.schema.clone()
115    }
116
117    async fn call(
118        &self,
119        _: &mut ToolContext,
120        args: Value,
121    ) -> Result<H::Output, ToolExecutionError> {
122        let args = parse_args::<H::Args>(&args, Some(&self.schema))?;
123        self.handler
124            .call(args)
125            .await
126            .map_err(ToolExecutionError::from_error)
127    }
128}