use std::collections::BTreeSet;
use indexmap::IndexMap;
use rig_core::{
completion::ToolDefinition,
effect::{Key, family},
tool::{ToolContext, ToolResult},
};
use super::registry::{RegisteredTool, ToolDispatch, execute_tool};
#[cfg(not(target_family = "wasm"))]
pub type ToolLease = std::sync::Arc<dyn std::any::Any + Send + Sync>;
#[cfg(target_family = "wasm")]
pub type ToolLease = std::sync::Arc<dyn std::any::Any>;
#[derive(Clone)]
pub struct ToolCatalog {
definitions: Vec<ToolDefinition>,
tools: IndexMap<String, RegisteredTool>,
leases: Vec<ToolLease>,
}
impl ToolCatalog {
pub(crate) fn from_registered(tools: IndexMap<String, RegisteredTool>) -> Self {
let definitions = tools
.iter()
.map(|(name, tool)| tool.definition_with_name(name.clone()))
.collect();
Self {
definitions,
tools,
leases: Vec::new(),
}
}
pub(crate) fn with_leases(mut self, leases: Vec<ToolLease>) -> Self {
self.leases = leases;
self
}
pub fn definitions(&self) -> &[ToolDefinition] {
&self.definitions
}
pub fn names(&self) -> impl Iterator<Item = &str> {
self.tools.keys().map(String::as_str)
}
pub fn len(&self) -> usize {
self.tools.len()
}
pub fn is_empty(&self) -> bool {
self.tools.is_empty()
}
pub fn contains(&self, name: &str) -> bool {
self.tools.contains_key(name)
}
pub fn get(&self, name: &str) -> Option<&RegisteredTool> {
self.tools.get(name)
}
pub fn key(&self, name: &str) -> Option<&Key<family::Tool>> {
self.tools.get(name).map(RegisteredTool::key)
}
pub fn iter(&self) -> impl Iterator<Item = (&str, &RegisteredTool)> {
self.tools.iter().map(|(name, tool)| (name.as_str(), tool))
}
pub async fn execute(
&self,
tool_name: &str,
args: &str,
context: &mut ToolContext,
) -> ToolResult {
context.clear_dispatch_result();
self.execute_scoped(tool_name, args, context)
.await
.publish_to(context)
}
pub fn take_definitions(&mut self) -> Vec<ToolDefinition> {
std::mem::take(&mut self.definitions)
}
pub(crate) fn retain_names(&mut self, names: &BTreeSet<String>) {
self.definitions
.retain(|definition| names.contains(&definition.name));
self.tools.retain(|name, _| names.contains(name));
}
pub async fn execute_scoped(
&self,
tool_name: &str,
args: &str,
context: &ToolContext,
) -> ToolDispatch {
let tool = self.tools.get(tool_name).cloned();
execute_tool(tool_name, args.to_string(), tool, context).await
}
}
#[cfg(test)]
mod tests;