Skip to main content

troupekit_kit/
output.rs

1use serde::Serialize;
2use serde_json::Value;
3use std::fmt::Display;
4use troupekit_tools::ToolOutput;
5
6/// Converts a tool fn's return value into what the model sees.
7/// Text, numbers, `bool`, `()`, JSON values, `Json<T>`, `Option<T>` and
8/// `Result<T, E: Display>` convert; an `Err` becomes an error output so the
9/// model can react to the failure instead of the run stopping.
10#[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    /// Consumes the value and returns the model-facing output.
16    /// Never panics; a value that cannot be rendered becomes an error output.
17    /// The output content is the text the model reads.
18    fn into_output(self) -> ToolOutput;
19}
20
21/// Wraps any `Serialize` value so a tool can return it as JSON text.
22/// A serialize failure becomes an error output naming the failure.
23/// Use it for structs: `Json(Point { x, y })`.
24#[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);