Skip to main content

troupekit_kit/
tool.rs

1use crate::output::IntoToolOutput;
2use schemars::JsonSchema;
3use serde::de::DeserializeOwned;
4use serde_json::Value;
5use std::any::TypeId;
6use std::collections::HashMap;
7use std::future::Future;
8use std::sync::{Arc, Mutex, OnceLock};
9use troupekit_tools::{typed_tool, Tool, ToolContext, ToolSpec};
10
11/// Anything an agent or graph accepts as a tool: every `Tool + 'static`.
12/// A `#[tool]` fn and the `tool(..)` function form both qualify; an
13/// `Arc<dyn Tool>` goes through `.tool_arc(..)` instead.
14#[diagnostic::on_unimplemented(
15    message = "`{Self}` is not a tool",
16    note = "mark its fn with #[tool], or pass an Arc<dyn Tool> with .tool_arc(..)"
17)]
18pub trait AsTool: Tool + 'static {
19    /// Moves the tool behind an `Arc<dyn Tool>` for a registry.
20    /// A zero-sized tool, such as a `#[tool]` fn, returns one shared `Arc`
21    /// per type, so graphs can tell two uses of it are the same tool.
22    fn into_arc(self) -> Arc<dyn Tool>
23    where
24        Self: Sized;
25}
26
27impl<T: Tool + 'static> AsTool for T {
28    fn into_arc(self) -> Arc<dyn Tool>
29    where
30        Self: Sized,
31    {
32        if std::mem::size_of::<T>() != 0 {
33            return Arc::new(self);
34        }
35        static SHARED: OnceLock<Mutex<HashMap<TypeId, Arc<dyn Tool>>>> = OnceLock::new();
36        let mut shared = SHARED
37            .get_or_init(Default::default)
38            .lock()
39            .unwrap_or_else(|e| e.into_inner());
40        shared
41            .entry(TypeId::of::<T>())
42            .or_insert_with(|| Arc::new(self))
43            .clone()
44    }
45}
46
47/// Builds a tool from argument type `A` and async fn `f`, without a macro.
48/// `f` takes the parsed arguments and returns any `IntoToolOutput` value;
49/// `name` and `description` are what the model sees. The schema is the
50/// same one `typed_tool` derives from `A`.
51pub fn tool<A, F, Fut>(name: &str, description: &str, f: F) -> impl Tool + 'static
52where
53    A: DeserializeOwned + JsonSchema + Send + 'static,
54    F: Fn(A) -> Fut + Send + Sync + 'static,
55    Fut: Future + Send + 'static,
56    Fut::Output: IntoToolOutput,
57{
58    typed_tool(name, description, move |args: A, _ctx: ToolContext| {
59        let pending = f(args);
60        async move { Ok(pending.await.into_output()) }
61    })
62}
63
64/// Returns the `ToolSpec` for argument type `A` named `name`.
65/// The schema is `schema_for!(A)` without `$schema` and `title`, exactly
66/// what `typed_tool` produces, so both paths give the model one schema.
67/// Used by the `#[tool]` expansion.
68pub fn spec<A: JsonSchema>(name: &str, description: &str) -> ToolSpec {
69    let mut schema = schemars::schema_for!(A).to_value();
70    assert!(schema.is_object(), "a derived schema is a JSON object");
71    if let Value::Object(map) = &mut schema {
72        map.remove("$schema");
73        map.remove("title");
74    }
75    ToolSpec {
76        name: name.into(),
77        description: description.into(),
78        schema,
79        hosted: None,
80    }
81}