Skip to main content

strands/tools/
error.rs

1//! [`ToolError`], the error type of tool bodies.
2
3use std::error::Error as StdError;
4use std::fmt;
5use std::sync::Arc;
6
7use super::tool::ToolOutcome;
8use crate::error::BoxError;
9use crate::interrupt::InterruptError;
10use crate::types::{ToolResultBlock, ToolResultContent, ToolResultError};
11
12/// The error a tool body returns, much like `anyhow::Error`.
13///
14/// Any [`std::error::Error`] converts into it with `?`, and so does the [`InterruptError`] that
15/// [`ToolContext::interrupt`](crate::tools::ToolContext::interrupt) returns, also after it passed
16/// through a [`BoxError`]. The model sees a failure as an error result with the text
17/// `Error: <message>`; an interrupt ends the tool as [`ToolOutcome::Interrupt`] instead, so a tool
18/// cannot turn an interrupt into a failure by accident.
19///
20/// `ToolError` does not implement [`std::error::Error`] itself, which is what lets every error
21/// type convert into it.
22///
23/// ```
24/// use strands::ToolError;
25///
26/// fn parse(input: &str) -> Result<u32, ToolError> {
27///     Ok(input.parse::<u32>()?)
28/// }
29///
30/// assert_eq!(parse("x").unwrap_err().to_string(), "invalid digit found in string");
31/// assert_eq!(ToolError::msg("city not found").to_string(), "city not found");
32/// ```
33pub struct ToolError {
34    repr: Box<Repr>,
35}
36
37enum Repr {
38    Error(ToolResultError),
39    Interrupt(InterruptError),
40}
41
42#[derive(Debug)]
43struct MessageError(String);
44
45impl fmt::Display for MessageError {
46    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47        f.write_str(&self.0)
48    }
49}
50
51impl StdError for MessageError {}
52
53impl ToolError {
54    /// Creates an error from a message.
55    pub fn msg(message: impl fmt::Display) -> Self {
56        Self::new(MessageError(message.to_string()))
57    }
58
59    /// Wraps an error; an [`InterruptError`] stays an interrupt.
60    pub fn new(error: impl StdError + Send + Sync + 'static) -> Self {
61        Self::from_boxed(Box::new(error))
62    }
63
64    /// Wraps a boxed error: a [`BoxError`], or what an error type without a
65    /// [`std::error::Error`] impl (such as `anyhow::Error`) converts into. `BoxError` cannot
66    /// convert with `?` itself, because it does not implement `std::error::Error`.
67    ///
68    /// ```
69    /// use strands::{BoxError, ToolError};
70    ///
71    /// fn lookup() -> Result<u32, BoxError> {
72    ///     Err("not found".into())
73    /// }
74    ///
75    /// fn tool_body() -> Result<u32, ToolError> {
76    ///     lookup().map_err(ToolError::from_boxed)
77    /// }
78    ///
79    /// assert_eq!(tool_body().unwrap_err().to_string(), "not found");
80    /// ```
81    ///
82    /// An [`InterruptError`] inside stays an interrupt.
83    #[must_use]
84    pub fn from_boxed(error: BoxError) -> Self {
85        let repr = match error.downcast::<InterruptError>() {
86            Ok(interrupt) => Repr::Interrupt(*interrupt),
87            Err(error) => Repr::Error(Arc::from(error)),
88        };
89        Self { repr: Box::new(repr) }
90    }
91
92    /// Whether this is an interrupt rather than a failure.
93    #[must_use]
94    pub fn is_interrupt(&self) -> bool {
95        matches!(*self.repr, Repr::Interrupt(_))
96    }
97
98    /// The interrupts, when this is one.
99    #[must_use]
100    pub fn as_interrupt(&self) -> Option<&InterruptError> {
101        match &*self.repr {
102            Repr::Interrupt(interrupt) => Some(interrupt),
103            Repr::Error(_) => None,
104        }
105    }
106
107    /// The underlying error, unless this is an interrupt.
108    #[must_use]
109    pub fn as_error(&self) -> Option<&(dyn StdError + Send + Sync + 'static)> {
110        match &*self.repr {
111            Repr::Error(error) => Some(error.as_ref()),
112            Repr::Interrupt(_) => None,
113        }
114    }
115
116    /// The outcome of a tool that failed with this error: an error result with the text
117    /// `Error: <message>` that keeps the error, or the interrupt.
118    #[must_use]
119    pub fn into_outcome(self, tool_use_id: impl Into<String>) -> ToolOutcome {
120        match *self.repr {
121            Repr::Interrupt(interrupt) => ToolOutcome::Interrupt(interrupt),
122            Repr::Error(error) => {
123                let text = format!("Error: {error}");
124                let mut result = ToolResultBlock::error(tool_use_id, vec![ToolResultContent::text(text)]);
125                result.error = Some(error);
126                ToolOutcome::Result(result)
127            }
128        }
129    }
130}
131
132impl<E: StdError + Send + Sync + 'static> From<E> for ToolError {
133    fn from(error: E) -> Self {
134        Self::new(error)
135    }
136}
137
138impl fmt::Display for ToolError {
139    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
140        match &*self.repr {
141            Repr::Error(error) => fmt::Display::fmt(error, f),
142            Repr::Interrupt(interrupt) => fmt::Display::fmt(interrupt, f),
143        }
144    }
145}
146
147impl fmt::Debug for ToolError {
148    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
149        match &*self.repr {
150            Repr::Error(error) => fmt::Debug::fmt(error, f),
151            Repr::Interrupt(interrupt) => f.debug_tuple("Interrupt").field(interrupt).finish(),
152        }
153    }
154}
155
156#[cfg(test)]
157mod tests {
158    use serde_json::json;
159
160    use super::*;
161    use crate::Error;
162    use crate::interrupt::Interrupt;
163
164    #[test]
165    fn failures_become_error_results_with_the_error_kept() {
166        let error: ToolError = Error::other("city not found").into();
167        assert!(!error.is_interrupt());
168        let ToolOutcome::Result(result) = error.into_outcome("t-1") else {
169            panic!("expected a result");
170        };
171        assert_eq!(
172            serde_json::to_value(&result).unwrap(),
173            json!({"toolUseId": "t-1", "status": "error", "content": [{"text": "Error: city not found"}]})
174        );
175        assert_eq!(result.error.unwrap().to_string(), "city not found");
176    }
177
178    #[test]
179    fn interrupts_stay_interrupts() {
180        let interrupt = InterruptError::from(Interrupt::new("tool:t-1:confirm", "confirm"));
181        let error = ToolError::from(interrupt.clone());
182        assert_eq!(error.to_string(), "Interrupt raised: confirm");
183        assert_eq!(error.as_interrupt(), Some(&interrupt));
184        assert!(error.as_error().is_none());
185        assert_eq!(error.into_outcome("t-1"), ToolOutcome::Interrupt(interrupt));
186    }
187
188    #[test]
189    fn interrupts_survive_a_box_error() {
190        let interrupts = InterruptError::new([Interrupt::new("a", "a"), Interrupt::new("b", "b")]);
191        let boxed: BoxError = Box::new(interrupts.clone());
192        let error = ToolError::from_boxed(boxed);
193        assert_eq!(error.to_string(), "2 interrupts raised: a, b");
194        assert_eq!(error.into_outcome("t-1"), ToolOutcome::Interrupt(interrupts));
195        let failure = ToolError::from_boxed("plain".into());
196        assert!(!failure.is_interrupt());
197        assert_eq!(failure.to_string(), "plain");
198    }
199
200    #[test]
201    fn tool_error_is_one_pointer() {
202        assert_eq!(std::mem::size_of::<ToolError>(), std::mem::size_of::<usize>());
203    }
204}