use std::fmt;
use std::sync::Arc;
use futures::future::BoxFuture;
use serde::{Deserialize, Serialize};
use crate::value::Value;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ToolSpec {
pub name: String,
pub description: String,
pub parameters: serde_json::Value,
}
#[derive(Clone, Debug, PartialEq)]
pub struct ToolOutput {
pub text: String,
pub data: Value,
pub is_error: bool,
}
impl ToolOutput {
pub fn text(text: impl Into<String>) -> Self {
Self { text: text.into(), data: Value::Null, is_error: false }
}
pub fn error(text: impl Into<String>) -> Self {
Self { text: text.into(), data: Value::Null, is_error: true }
}
}
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
#[error("tool `{tool}`: {message}")]
pub struct ToolError {
pub tool: String,
pub message: String,
}
pub trait ToolRuntime: Send + Sync + fmt::Debug {
fn list(&self) -> BoxFuture<'_, Result<Vec<ToolSpec>, ToolError>>;
fn call<'a>(&'a self, name: &'a str, arguments: serde_json::Value) -> BoxFuture<'a, Result<ToolOutput, ToolError>>;
}
#[derive(Clone, Default)]
pub struct ToolRegistry {
providers: indexmap::IndexMap<String, Arc<dyn ToolRuntime>>,
}
impl fmt::Debug for ToolRegistry {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.providers.keys()).finish()
}
}
impl ToolRegistry {
pub fn new() -> Self {
Self::default()
}
pub fn add(&mut self, provider: impl Into<String>, runtime: Arc<dyn ToolRuntime>) -> &mut Self {
self.providers.insert(provider.into(), runtime);
self
}
pub fn get(&self, provider: &str) -> Option<&Arc<dyn ToolRuntime>> {
self.providers.get(provider)
}
pub fn providers(&self) -> impl Iterator<Item = (&str, &Arc<dyn ToolRuntime>)> {
self.providers.iter().map(|(k, v)| (k.as_str(), v))
}
}