1use serde::Serialize;
2use serde_json::Value;
3use std::fmt::Display;
4use troupekit_tools::ToolOutput;
5
6#[diagnostic::on_unimplemented(
11 message = "`{Self}` cannot be a #[tool] return type",
12 note = "return String, a number, bool, (), serde_json::Value, Json<T>, Option<T> or Result<T, E: Display>"
13)]
14pub trait IntoToolOutput {
15 fn into_output(self) -> ToolOutput;
19}
20
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
25pub struct Json<T>(pub T);
26
27impl IntoToolOutput for ToolOutput {
28 fn into_output(self) -> ToolOutput {
29 self
30 }
31}
32
33impl IntoToolOutput for String {
34 fn into_output(self) -> ToolOutput {
35 ToolOutput::text(self)
36 }
37}
38
39impl IntoToolOutput for &str {
40 fn into_output(self) -> ToolOutput {
41 ToolOutput::text(self)
42 }
43}
44
45impl IntoToolOutput for () {
46 fn into_output(self) -> ToolOutput {
47 ToolOutput::text("ok")
48 }
49}
50
51impl IntoToolOutput for Value {
52 fn into_output(self) -> ToolOutput {
53 ToolOutput::text(self.to_string())
54 }
55}
56
57impl<T: Serialize> IntoToolOutput for Json<T> {
58 fn into_output(self) -> ToolOutput {
59 match serde_json::to_string(&self.0) {
60 Ok(text) => ToolOutput::text(text),
61 Err(e) => ToolOutput::error(format!("the tool result does not serialize: {e}")),
62 }
63 }
64}
65
66impl<T: IntoToolOutput> IntoToolOutput for Option<T> {
67 fn into_output(self) -> ToolOutput {
68 match self {
69 Some(value) => value.into_output(),
70 None => ToolOutput::text("null"),
71 }
72 }
73}
74
75impl<T: IntoToolOutput, E: Display> IntoToolOutput for Result<T, E> {
76 fn into_output(self) -> ToolOutput {
77 match self {
78 Ok(value) => value.into_output(),
79 Err(e) => ToolOutput::error(e.to_string()),
80 }
81 }
82}
83
84macro_rules! display_output {
85 ($($t:ty),* $(,)?) => {
86 $(
87 impl IntoToolOutput for $t {
88 fn into_output(self) -> ToolOutput {
89 ToolOutput::text(self.to_string())
90 }
91 }
92 )*
93 };
94}
95
96display_output!(bool, i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize, f32, f64);