use crate::output::IntoToolOutput;
use schemars::JsonSchema;
use serde::de::DeserializeOwned;
use serde_json::Value;
use std::any::TypeId;
use std::collections::HashMap;
use std::future::Future;
use std::sync::{Arc, Mutex, OnceLock};
use troupekit_tools::{typed_tool, Tool, ToolContext, ToolSpec};
#[diagnostic::on_unimplemented(
message = "`{Self}` is not a tool",
note = "mark its fn with #[tool], or pass an Arc<dyn Tool> with .tool_arc(..)"
)]
pub trait AsTool: Tool + 'static {
fn into_arc(self) -> Arc<dyn Tool>
where
Self: Sized;
}
impl<T: Tool + 'static> AsTool for T {
fn into_arc(self) -> Arc<dyn Tool>
where
Self: Sized,
{
if std::mem::size_of::<T>() != 0 {
return Arc::new(self);
}
static SHARED: OnceLock<Mutex<HashMap<TypeId, Arc<dyn Tool>>>> = OnceLock::new();
let mut shared = SHARED
.get_or_init(Default::default)
.lock()
.unwrap_or_else(|e| e.into_inner());
shared
.entry(TypeId::of::<T>())
.or_insert_with(|| Arc::new(self))
.clone()
}
}
pub fn tool<A, F, Fut>(name: &str, description: &str, f: F) -> impl Tool + 'static
where
A: DeserializeOwned + JsonSchema + Send + 'static,
F: Fn(A) -> Fut + Send + Sync + 'static,
Fut: Future + Send + 'static,
Fut::Output: IntoToolOutput,
{
typed_tool(name, description, move |args: A, _ctx: ToolContext| {
let pending = f(args);
async move { Ok(pending.await.into_output()) }
})
}
pub fn spec<A: JsonSchema>(name: &str, description: &str) -> ToolSpec {
let mut schema = schemars::schema_for!(A).to_value();
assert!(schema.is_object(), "a derived schema is a JSON object");
if let Value::Object(map) = &mut schema {
map.remove("$schema");
map.remove("title");
}
ToolSpec {
name: name.into(),
description: description.into(),
schema,
hosted: None,
}
}