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#[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 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
47pub 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
64pub 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}