use alloc::{boxed::Box, format, vec::Vec};
use super::{
rust_tool::{ErasedTool, RustTool, definition_of},
types::{ToolContext, ToolDefinition, ToolError, ToolOutput},
};
use crate::compat::HashMap;
struct RegisteredTool {
definition: ToolDefinition,
erased: Box<dyn ErasedTool>,
}
pub struct ToolRegistry {
tools: HashMap<&'static str, RegisteredTool>,
}
impl core::fmt::Debug for ToolRegistry {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
let names: Vec<&str> = self
.tools
.values()
.map(|r| r.definition.name.as_str())
.collect();
f.debug_struct("ToolRegistry")
.field("tool_count", &self.tools.len())
.field("tool_names", &names)
.finish()
}
}
impl Default for ToolRegistry {
fn default() -> Self {
Self::new()
}
}
impl ToolRegistry {
#[must_use]
pub fn new() -> Self {
Self {
tools: HashMap::new(),
}
}
pub fn register<T: RustTool + 'static>(&mut self, tool: T) -> &mut Self {
if let Err(e) = self.try_register(tool) {
panic!("Failed to build definition for tool '{}': {e}", T::NAME);
}
self
}
pub fn try_register<T: RustTool + 'static>(&mut self, tool: T) -> Result<&mut Self, ToolError> {
let definition = definition_of(&tool)?;
self.tools.insert(
T::NAME,
RegisteredTool {
definition,
erased: Box::new(tool),
},
);
Ok(self)
}
#[must_use]
pub fn with_tool<T: RustTool + 'static>(mut self, tool: T) -> Self {
self.register(tool);
self
}
#[must_use]
pub fn definitions(&self) -> Vec<ToolDefinition> {
self.tools
.values()
.map(|entry| entry.definition.clone())
.collect()
}
pub async fn dispatch(
&self,
name: &str,
args: serde_json::Value,
ctx: &ToolContext,
) -> Option<Result<ToolOutput, ToolError>> {
let entry = self.tools.get(name)?;
Some(entry.erased.call_erased(args, ctx).await)
}
pub async fn dispatch_str(
&self,
name: &str,
args_json: &str,
ctx: &ToolContext,
) -> Option<Result<ToolOutput, ToolError>> {
if !self.contains(name) {
return None;
}
let args = match serde_json::from_str(args_json) {
Ok(args) => args,
Err(e) => {
return Some(Err(ToolError::new(format!(
"Malformed JSON arguments: {e}"
))));
}
};
self.dispatch(name, args, ctx).await
}
#[must_use]
pub fn len(&self) -> usize {
self.tools.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.tools.is_empty()
}
#[must_use]
pub fn contains(&self, name: &str) -> bool {
self.tools.contains_key(name)
}
#[must_use]
pub fn definition(&self, name: &str) -> Option<&ToolDefinition> {
self.tools.get(name).map(|entry| &entry.definition)
}
#[must_use]
pub fn iter(&self) -> ToolDefinitions<'_> {
ToolDefinitions {
inner: self.tools.iter(),
}
}
}
pub struct ToolDefinitions<'a> {
inner: crate::compat::HashMapIter<'a, &'static str, RegisteredTool>,
}
impl Iterator for ToolDefinitions<'_> {
type Item = (&'static str, ToolDefinition);
fn next(&mut self) -> Option<Self::Item> {
self.inner
.next()
.map(|(name, entry)| (*name, entry.definition.clone()))
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
}
impl ExactSizeIterator for ToolDefinitions<'_> {
fn len(&self) -> usize {
self.inner.len()
}
}
impl<'a> IntoIterator for &'a ToolRegistry {
type Item = (&'static str, ToolDefinition);
type IntoIter = ToolDefinitions<'a>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
#[cfg(all(test, feature = "std"))]
mod tests;