Skip to main content

ds_api/
tool_trait.rs

1use crate::raw::request::tool::Tool as RawTool;
2use async_trait::async_trait;
3use serde_json::{Value, json};
4
5pub trait JsonSchema {
6    fn schema() -> Value;
7}
8
9impl JsonSchema for String {
10    fn schema() -> Value {
11        json!({"type": "string"})
12    }
13}
14impl JsonSchema for &str {
15    fn schema() -> Value {
16        json!({"type": "string"})
17    }
18}
19impl JsonSchema for bool {
20    fn schema() -> Value {
21        json!({"type": "boolean"})
22    }
23}
24impl JsonSchema for i8 {
25    fn schema() -> Value {
26        json!({"type": "integer"})
27    }
28}
29impl JsonSchema for i16 {
30    fn schema() -> Value {
31        json!({"type": "integer"})
32    }
33}
34impl JsonSchema for i32 {
35    fn schema() -> Value {
36        json!({"type": "integer"})
37    }
38}
39impl JsonSchema for i64 {
40    fn schema() -> Value {
41        json!({"type": "integer"})
42    }
43}
44impl JsonSchema for u8 {
45    fn schema() -> Value {
46        json!({"type": "integer"})
47    }
48}
49impl JsonSchema for u16 {
50    fn schema() -> Value {
51        json!({"type": "integer"})
52    }
53}
54impl JsonSchema for u32 {
55    fn schema() -> Value {
56        json!({"type": "integer"})
57    }
58}
59impl JsonSchema for u64 {
60    fn schema() -> Value {
61        json!({"type": "integer"})
62    }
63}
64impl JsonSchema for f32 {
65    fn schema() -> Value {
66        json!({"type": "number"})
67    }
68}
69impl JsonSchema for f64 {
70    fn schema() -> Value {
71        json!({"type": "number"})
72    }
73}
74
75impl<T: JsonSchema> JsonSchema for Vec<T> {
76    fn schema() -> Value {
77        json!({"type": "array", "items": T::schema()})
78    }
79}
80
81impl<T: JsonSchema> JsonSchema for Option<T> {
82    fn schema() -> Value {
83        T::schema()
84    }
85}
86
87#[async_trait]
88pub trait Tool: Send + Sync {
89    fn raw_tools(&self) -> Vec<RawTool>;
90    /// Invoke the named tool with the given arguments and return the result as a JSON value.
91    ///
92    /// When using the `#[tool]` macro you do not implement this method yourself —
93    /// the macro generates it. The generated implementation accepts any return type
94    /// that implements `serde::Serialize` (including `serde_json::Value`, plain
95    /// structs with `#[derive(Serialize)]`, primitives, etc.) and converts the
96    /// value to `serde_json::Value` automatically.
97    async fn call(&self, name: &str, args: Value) -> Value;
98}