1use std::fmt;
5use std::sync::Arc;
6
7use futures::future::BoxFuture;
8use serde::{Deserialize, Serialize};
9
10use crate::value::Value;
11
12#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
14pub struct ToolSpec {
15 pub name: String,
17 pub description: String,
18 pub parameters: serde_json::Value,
20}
21
22#[derive(Clone, Debug, PartialEq)]
24pub struct ToolOutput {
25 pub text: String,
27 pub data: Value,
29 pub is_error: bool,
31}
32
33impl ToolOutput {
34 pub fn text(text: impl Into<String>) -> Self {
35 Self { text: text.into(), data: Value::Null, is_error: false }
36 }
37
38 pub fn error(text: impl Into<String>) -> Self {
39 Self { text: text.into(), data: Value::Null, is_error: true }
40 }
41}
42
43#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
45#[error("tool `{tool}`: {message}")]
46pub struct ToolError {
47 pub tool: String,
48 pub message: String,
49}
50
51pub trait ToolRuntime: Send + Sync + fmt::Debug {
53 fn list(&self) -> BoxFuture<'_, Result<Vec<ToolSpec>, ToolError>>;
55 fn call<'a>(&'a self, name: &'a str, arguments: serde_json::Value) -> BoxFuture<'a, Result<ToolOutput, ToolError>>;
57}
58
59#[derive(Clone, Default)]
62pub struct ToolRegistry {
63 providers: indexmap::IndexMap<String, Arc<dyn ToolRuntime>>,
64}
65
66impl fmt::Debug for ToolRegistry {
67 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68 f.debug_list().entries(self.providers.keys()).finish()
69 }
70}
71
72impl ToolRegistry {
73 pub fn new() -> Self {
74 Self::default()
75 }
76
77 pub fn add(&mut self, provider: impl Into<String>, runtime: Arc<dyn ToolRuntime>) -> &mut Self {
78 self.providers.insert(provider.into(), runtime);
79 self
80 }
81
82 pub fn get(&self, provider: &str) -> Option<&Arc<dyn ToolRuntime>> {
83 self.providers.get(provider)
84 }
85
86 pub fn providers(&self) -> impl Iterator<Item = (&str, &Arc<dyn ToolRuntime>)> {
87 self.providers.iter().map(|(k, v)| (k.as_str(), v))
88 }
89}