Skip to main content

rig_core/tool/
output.rs

1//! Canonical text, JSON, and multimodal tool output.
2//!
3//! ```
4//! use rig_core::tool::ToolOutput;
5//!
6//! let output = ToolOutput::text("done");
7//! assert_eq!(output.as_text(), Some("done"));
8//! ```
9
10use std::{any::Any, fmt};
11
12use serde::Serialize;
13
14use crate::{message::ToolResultContent, tool::ToolExecutionError};
15
16/// The canonical model-visible output produced by a tool.
17///
18/// Every output is stored as one or more typed [`ToolResultContent`] blocks.
19/// Ordinary serializable Rust values are converted through [`IntoToolOutput`]:
20/// values that serialize as JSON strings become literal text blocks and all
21/// other values become structured JSON blocks. An explicit
22/// [`serde_json::Value`], including a JSON string, stays JSON. Multimodal tools
23/// opt in explicitly with [`Self::content`]. Rig never reparses text as JSON to
24/// guess whether it represents rich content.
25#[derive(Clone, PartialEq)]
26pub struct ToolOutput {
27    content: Vec<ToolResultContent>,
28}
29
30// Serde is the content list itself; deserialization goes through
31// [`ToolOutput::content`] so an empty list is rejected at the boundary, the
32// same as at construction.
33impl Serialize for ToolOutput {
34    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
35        self.content.serialize(serializer)
36    }
37}
38
39impl<'de> serde::Deserialize<'de> for ToolOutput {
40    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
41        let content = Vec::<ToolResultContent>::deserialize(deserializer)?;
42        Self::content(content).map_err(serde::de::Error::custom)
43    }
44}
45
46impl fmt::Debug for ToolOutput {
47    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
48        let content_kinds = self
49            .content
50            .iter()
51            .map(|content| match content {
52                ToolResultContent::Text(_) => "text",
53                ToolResultContent::Image(_) => "image",
54                ToolResultContent::Json { .. } => "json",
55            })
56            .collect::<Vec<_>>();
57        formatter
58            .debug_struct("ToolOutput")
59            .field("content_count", &self.content.len())
60            .field("content_kinds", &content_kinds)
61            .finish()
62    }
63}
64
65impl ToolOutput {
66    /// Construct literal text output.
67    pub fn text(text: impl Into<String>) -> Self {
68        Self::one(ToolResultContent::text(text))
69    }
70
71    /// Construct structured JSON output.
72    ///
73    /// Unlike an ordinary Rust string tool output, an explicit JSON string stays
74    /// a JSON content block.
75    pub fn json(value: serde_json::Value) -> Self {
76        Self::one(ToolResultContent::json(value))
77    }
78
79    /// Constructs explicit model content, rejecting an empty block list.
80    /// Use [`Self::text`] with `""` to represent an empty text result.
81    pub fn content(content: Vec<ToolResultContent>) -> Result<Self, ToolExecutionError> {
82        if content.is_empty() {
83            return Err(ToolExecutionError::other(
84                "tool output has no content blocks; return at least one block — \
85                 an empty text block is valid",
86            ));
87        }
88        Ok(Self { content })
89    }
90
91    /// Construct one explicit model-content block.
92    pub fn one(content: ToolResultContent) -> Self {
93        Self {
94            content: vec![content],
95        }
96    }
97
98    /// Return literal text when this output is exactly one plain text block.
99    pub fn as_text(&self) -> Option<&str> {
100        match self.content.as_slice() {
101            [ToolResultContent::Text(text)] if text.native.is_none() => Some(&text.text),
102            _ => None,
103        }
104    }
105
106    /// Return structured JSON when this output is exactly one JSON block.
107    pub fn as_json(&self) -> Option<&serde_json::Value> {
108        match self.content.as_slice() {
109            [ToolResultContent::Json { value }] => Some(value),
110            _ => None,
111        }
112    }
113
114    /// Borrow the canonical ordered content blocks.
115    pub fn as_content(&self) -> &[ToolResultContent] {
116        &self.content
117    }
118
119    /// Convert this output into the canonical message content sent to a model.
120    pub fn into_content(self) -> Vec<ToolResultContent> {
121        self.content
122    }
123
124    /// Render a stable text representation for telemetry and diagnostics.
125    ///
126    /// This is a terminal rendering operation; the returned text is never used
127    /// to reconstruct structured output.
128    pub fn render(&self) -> String {
129        if let Some(text) = self.as_text() {
130            text.to_string()
131        } else if let Some(value) = self.as_json() {
132            value.to_string()
133        } else {
134            serde_json::to_string(&self.content)
135                .unwrap_or_else(|_| "<structured tool output>".to_string())
136        }
137    }
138}
139
140impl From<String> for ToolOutput {
141    fn from(text: String) -> Self {
142        Self::text(text)
143    }
144}
145
146impl From<&str> for ToolOutput {
147    fn from(text: &str) -> Self {
148        Self::text(text)
149    }
150}
151
152impl From<serde_json::Value> for ToolOutput {
153    fn from(value: serde_json::Value) -> Self {
154        Self::json(value)
155    }
156}
157
158impl From<ToolResultContent> for ToolOutput {
159    fn from(content: ToolResultContent) -> Self {
160        Self::one(content)
161    }
162}
163
164impl TryFrom<Vec<ToolResultContent>> for ToolOutput {
165    type Error = ToolExecutionError;
166
167    fn try_from(content: Vec<ToolResultContent>) -> Result<Self, Self::Error> {
168        Self::content(content)
169    }
170}
171
172/// Conversion into Rig's canonical tool output.
173///
174/// A blanket implementation keeps ordinary [`Serialize`] outputs ergonomic.
175/// Because that blanket implementation already covers every serializable type,
176/// it cannot be overridden with another implementation for a serializable
177/// custom type. Return [`ToolOutput`] from [`Tool::call`](crate::tool::Tool::call)
178/// when that type needs a custom presentation. Implement this trait directly
179/// only for output types that do not implement [`Serialize`].
180pub trait IntoToolOutput {
181    /// Convert this value without routing structured data through a string.
182    fn into_tool_output(self) -> Result<ToolOutput, ToolExecutionError>;
183}
184
185#[cfg(test)]
186mod debug_tests;
187
188impl<T> IntoToolOutput for T
189where
190    T: Serialize + 'static,
191{
192    fn into_tool_output(self) -> Result<ToolOutput, ToolExecutionError> {
193        // Take explicit content types and text as they are, before the
194        // serialization fallback, so multimodal blocks are not converted
195        // into JSON objects and nothing is copied.
196        let mut value = Some(self);
197        let slot = &mut value as &mut dyn Any;
198        if let Some(output) = take::<ToolOutput>(slot) {
199            return Ok(output);
200        }
201        if let Some(content) = take::<ToolResultContent>(slot) {
202            return Ok(ToolOutput::one(content));
203        }
204        if let Some(content) = take::<Vec<ToolResultContent>>(slot) {
205            // Reject empty rich output as a tool failure rather than inventing
206            // text or allowing an invalid result into history.
207            return ToolOutput::content(content);
208        }
209        if let Some(text) = take::<String>(slot) {
210            return Ok(ToolOutput::text(text));
211        }
212        let is_explicit_json = slot.is::<Option<serde_json::Value>>();
213
214        // `Some(value)` serializes as `value`.
215        serde_json::to_value(value)
216            .map(|value| match value {
217                serde_json::Value::String(text) if !is_explicit_json => ToolOutput::text(text),
218                value => ToolOutput::json(value),
219            })
220            .map_err(|error| {
221                ToolExecutionError::other(format!("failed to serialize tool output: {error}"))
222                    .with_source(error)
223            })
224    }
225}
226
227/// The `T` in `slot`, an `Option<T>`, taken; `None` for another type.
228fn take<T: 'static>(slot: &mut dyn Any) -> Option<T> {
229    slot.downcast_mut::<Option<T>>().and_then(Option::take)
230}
231
232#[cfg(test)]
233mod tests;