Skip to main content

strands/agent/
result.rs

1//! The result of an agent invocation (`AgentResult`).
2
3use std::fmt;
4
5use serde::de::DeserializeOwned;
6use serde::ser::SerializeMap;
7use serde::{Deserialize, Deserializer, Serialize, Serializer};
8
9use super::invocation_context::InvocationContext;
10use super::invocation_state::InvocationState;
11use crate::error::{Result, StructuredOutputError};
12use crate::interrupt::Interrupt;
13use crate::telemetry::{AgentMetrics, AgentTrace};
14use crate::types::{ContentBlock, JsonValue, Message, StopReason};
15
16/// The error text when [`AgentResult::structured_output`] is read from a result without one.
17const NO_STRUCTURED_OUTPUT: &str = "The agent result has no structured output.";
18
19/// The result of an agent invocation (`AgentResult`).
20///
21/// Serializes to `type`, `stopReason`, `lastMessage` and, when present, `structuredOutput`.
22/// Traces, metrics, the invocation context and the invocation state stay out of the JSON so a
23/// result can be forwarded over the wire without bloat.
24///
25/// `Display` writes the interrupts as JSON when there are any, else the structured output as JSON,
26/// else the text of the last message.
27#[derive(Debug, Clone)]
28#[non_exhaustive]
29pub struct AgentResult {
30    inner: Box<Inner>,
31}
32
33/// The fields, boxed so stream events that carry a result stay small.
34#[derive(Debug, Clone)]
35struct Inner {
36    stop_reason: StopReason,
37    last_message: Message,
38    traces: Option<Vec<AgentTrace>>,
39    structured_output: Option<JsonValue>,
40    metrics: Option<AgentMetrics>,
41    invocation_context: Option<InvocationContext>,
42    invocation_state: InvocationState,
43    interrupts: Vec<Interrupt>,
44}
45
46impl AgentResult {
47    /// Creates a result with a stop reason and the last message, and empty invocation state.
48    pub fn new(stop_reason: StopReason, last_message: Message) -> Self {
49        Self {
50            inner: Box::new(Inner {
51                stop_reason,
52                last_message,
53                traces: None,
54                structured_output: None,
55                metrics: None,
56                invocation_context: None,
57                invocation_state: InvocationState::new(),
58                interrupts: Vec::new(),
59            }),
60        }
61    }
62
63    /// Sets the traces.
64    #[must_use]
65    pub fn with_traces(mut self, traces: Vec<AgentTrace>) -> Self {
66        self.inner.traces = Some(traces);
67        self
68    }
69
70    /// Sets the validated structured output.
71    #[must_use]
72    pub fn with_structured_output(mut self, structured_output: JsonValue) -> Self {
73        self.inner.structured_output = Some(structured_output);
74        self
75    }
76
77    /// Sets the metrics.
78    #[must_use]
79    pub fn with_metrics(mut self, metrics: AgentMetrics) -> Self {
80        self.inner.metrics = Some(metrics);
81        self
82    }
83
84    /// Sets the invocation context.
85    #[must_use]
86    pub fn with_invocation_context(mut self, invocation_context: InvocationContext) -> Self {
87        self.inner.invocation_context = Some(invocation_context);
88        self
89    }
90
91    /// Sets the invocation state.
92    #[must_use]
93    pub fn with_invocation_state(mut self, invocation_state: InvocationState) -> Self {
94        self.inner.invocation_state = invocation_state;
95        self
96    }
97
98    /// Sets the interrupts that stopped the agent.
99    #[must_use]
100    pub fn with_interrupts(mut self, interrupts: Vec<Interrupt>) -> Self {
101        self.inner.interrupts = interrupts;
102        self
103    }
104
105    /// Why the invocation stopped.
106    #[must_use]
107    pub fn stop_reason(&self) -> StopReason {
108        self.inner.stop_reason.clone()
109    }
110
111    /// The last message added to the conversation.
112    #[must_use]
113    pub fn last_message(&self) -> &Message {
114        &self.inner.last_message
115    }
116
117    /// Local execution traces collected during the invocation.
118    #[must_use]
119    pub fn traces(&self) -> Option<&[AgentTrace]> {
120        self.inner.traces.as_deref()
121    }
122
123    /// The validated structured output as raw JSON, when a schema was given.
124    #[must_use]
125    pub fn structured_output_value(&self) -> Option<&JsonValue> {
126        self.inner.structured_output.as_ref()
127    }
128
129    /// The structured output deserialized into `T`.
130    ///
131    /// # Errors
132    ///
133    /// [`Error::StructuredOutput`](crate::Error::StructuredOutput) when the result has no structured output, or a decoding error
134    /// when it does not fit `T`.
135    pub fn structured_output<T: DeserializeOwned>(&self) -> Result<T> {
136        let Some(value) = &self.inner.structured_output else {
137            return Err(StructuredOutputError::new(NO_STRUCTURED_OUTPUT).into());
138        };
139        Ok(T::deserialize(value)?)
140    }
141
142    /// Aggregated loop metrics of the agent.
143    #[must_use]
144    pub fn metrics(&self) -> Option<&AgentMetrics> {
145        self.inner.metrics.as_ref()
146    }
147
148    /// The request this call ran in. Its usage covers the whole request; pass it to a later call to
149    /// continue on the same limits and usage.
150    #[must_use]
151    pub fn invocation_context(&self) -> Option<&InvocationContext> {
152        self.inner.invocation_context.as_ref()
153    }
154
155    /// The invocation state passed through hooks and tools.
156    #[must_use]
157    pub fn invocation_state(&self) -> &InvocationState {
158        &self.inner.invocation_state
159    }
160
161    /// The unanswered interrupts when the stop reason is [`StopReason::Interrupt`].
162    #[must_use]
163    pub fn interrupts(&self) -> &[Interrupt] {
164        &self.inner.interrupts
165    }
166
167    /// The whole prompt the model processed on the last call.
168    #[must_use]
169    pub fn context_size(&self) -> Option<u64> {
170        self.inner
171            .metrics
172            .as_ref()
173            .and_then(|metrics| metrics.latest_context_size)
174    }
175
176    /// Projected context size of the next model call.
177    #[must_use]
178    pub fn projected_context_size(&self) -> Option<u64> {
179        self.inner
180            .metrics
181            .as_ref()
182            .and_then(|metrics| metrics.projected_context_size)
183    }
184
185    fn text_parts(&self) -> Vec<String> {
186        let mut parts = Vec::new();
187        for block in &self.inner.last_message.content {
188            match block {
189                ContentBlock::Text(text) => parts.push(text.text.clone()),
190                ContentBlock::Reasoning(reasoning) => {
191                    if let Some(text) = reasoning.text.as_deref().filter(|text| !text.is_empty()) {
192                        parts.push(format!("šŸ’­ Reasoning:\n   {}", text.replace('\n', "\n   ")));
193                    }
194                }
195                ContentBlock::Citations(citations) => {
196                    parts.extend(citations.content.iter().map(|content| content.text.clone()));
197                }
198                other => tracing::debug!("block=<{}> | skipping content block type", block_type(other)),
199            }
200        }
201        parts
202    }
203}
204
205fn block_type(block: &ContentBlock) -> &'static str {
206    match block {
207        ContentBlock::ToolUse(_) => "toolUseBlock",
208        ContentBlock::ToolResult(_) => "toolResultBlock",
209        ContentBlock::CachePoint(_) => "cachePointBlock",
210        ContentBlock::GuardContent(_) => "guardContentBlock",
211        ContentBlock::Audio(_) => "audioBlock",
212        ContentBlock::Image(_) => "imageBlock",
213        ContentBlock::Video(_) => "videoBlock",
214        ContentBlock::Document(_) => "documentBlock",
215        ContentBlock::Injected(_) => "injectedBlock",
216        ContentBlock::Summary(_) => "summaryBlock",
217        _ => "unknownBlock",
218    }
219}
220
221impl fmt::Display for AgentResult {
222    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
223        if !self.inner.interrupts.is_empty() {
224            let json = serde_json::to_string(&self.inner.interrupts).map_err(|_| fmt::Error)?;
225            return f.write_str(&json);
226        }
227        if let Some(structured_output) = &self.inner.structured_output {
228            return write!(f, "{structured_output}");
229        }
230        f.write_str(&self.text_parts().join("\n"))
231    }
232}
233
234impl Serialize for AgentResult {
235    fn serialize<S: Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
236        let len = if self.inner.structured_output.is_some() { 4 } else { 3 };
237        let mut map = serializer.serialize_map(Some(len))?;
238        map.serialize_entry("type", "agentResult")?;
239        map.serialize_entry("stopReason", &self.inner.stop_reason)?;
240        map.serialize_entry("lastMessage", &self.inner.last_message)?;
241        if let Some(structured_output) = &self.inner.structured_output {
242            map.serialize_entry("structuredOutput", structured_output)?;
243        }
244        map.end()
245    }
246}
247
248#[derive(Deserialize)]
249#[serde(rename_all = "camelCase")]
250struct AgentResultData {
251    #[serde(rename = "type")]
252    _type: AgentResultTag,
253    stop_reason: StopReason,
254    last_message: Message,
255    #[serde(default)]
256    structured_output: Option<JsonValue>,
257}
258
259#[derive(Deserialize)]
260enum AgentResultTag {
261    #[serde(rename = "agentResult")]
262    AgentResult,
263}
264
265impl<'de> Deserialize<'de> for AgentResult {
266    /// Reads the serialized shape. The fields it leaves out (traces, metrics, invocation context and
267    /// state) start empty.
268    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> {
269        let data = AgentResultData::deserialize(deserializer)?;
270        let result = Self::new(data.stop_reason, data.last_message);
271        Ok(match data.structured_output {
272            Some(structured_output) => result.with_structured_output(structured_output),
273            None => result,
274        })
275    }
276}
277
278#[cfg(test)]
279mod tests {
280    use serde_json::json;
281
282    use super::*;
283    use crate::types::{
284        CachePointBlock, Citation, CitationGeneratedContent, CitationLocation, CitationSourceContent, CitationsBlock,
285        DocumentCharLocation, ReasoningBlock, Role, ToolResultBlock, ToolResultContent, ToolUseBlock,
286    };
287
288    fn assistant(content: Vec<ContentBlock>) -> Message {
289        Message::new(Role::Assistant, content)
290    }
291
292    fn result(stop_reason: StopReason, content: Vec<ContentBlock>) -> AgentResult {
293        AgentResult::new(stop_reason, assistant(content)).with_metrics(AgentMetrics::new())
294    }
295
296    fn text(text: &str) -> ContentBlock {
297        ContentBlock::text(text)
298    }
299
300    #[test]
301    fn returns_empty_string() {
302        assert_eq!(result(StopReason::EndTurn, vec![]).to_string(), "");
303    }
304
305    #[test]
306    fn returns_the_text_content() {
307        assert_eq!(
308            result(StopReason::EndTurn, vec![text("Hello, world!")]).to_string(),
309            "Hello, world!"
310        );
311    }
312
313    #[test]
314    fn returns_all_text_joined_with_newlines() {
315        let result = result(
316            StopReason::EndTurn,
317            vec![text("First line"), text("Second line"), text("Third line")],
318        );
319        assert_eq!(result.to_string(), "First line\nSecond line\nThird line");
320    }
321
322    #[test]
323    fn returns_the_reasoning_text_with_prefix() {
324        let block = ReasoningBlock::new().with_text("Let me think about this...");
325        assert_eq!(
326            result(StopReason::EndTurn, vec![block.into()]).to_string(),
327            "šŸ’­ Reasoning:\n   Let me think about this..."
328        );
329    }
330
331    #[test]
332    fn returns_empty_string_reasoning_block_is_skipped() {
333        let block = ReasoningBlock::new().with_signature("abc123");
334        assert_eq!(result(StopReason::EndTurn, vec![block.into()]).to_string(), "");
335    }
336
337    #[test]
338    fn returns_all_text_joined_with_newlines_for_mixed_text_and_reasoning() {
339        let result = result(
340            StopReason::EndTurn,
341            vec![
342                text("Here is my response."),
343                ReasoningBlock::new().with_text("I reasoned carefully.").into(),
344                text("Additional context."),
345            ],
346        );
347        assert_eq!(
348            result.to_string(),
349            "Here is my response.\nšŸ’­ Reasoning:\n   I reasoned carefully.\nAdditional context."
350        );
351    }
352
353    #[test]
354    fn indents_multi_line_reasoning() {
355        let block = ReasoningBlock::new().with_text("one\ntwo");
356        assert_eq!(
357            result(StopReason::EndTurn, vec![block.into()]).to_string(),
358            "šŸ’­ Reasoning:\n   one\n   two"
359        );
360    }
361
362    #[test]
363    fn returns_empty_string_for_only_non_text_blocks() {
364        let result = result(
365            StopReason::ToolUse,
366            vec![
367                ToolUseBlock::new("calc", "id-1", json!({"a": 1, "b": 2})).into(),
368                ToolResultBlock::success("id-1", vec![ToolResultContent::text("3")]).into(),
369                CachePointBlock::new().into(),
370            ],
371        );
372        assert_eq!(result.to_string(), "");
373    }
374
375    #[test]
376    fn returns_only_text_from_text_block_and_reasoning_block() {
377        let result = result(
378            StopReason::ToolUse,
379            vec![
380                text("Before tool"),
381                ToolUseBlock::new("calc", "id-1", json!({"a": 1, "b": 2})).into(),
382                ReasoningBlock::new().with_text("Thinking...").into(),
383                CachePointBlock::new().into(),
384                text("After tool"),
385            ],
386        );
387        assert_eq!(
388            result.to_string(),
389            "Before tool\nšŸ’­ Reasoning:\n   Thinking...\nAfter tool"
390        );
391    }
392
393    #[test]
394    fn returns_json_stringified_interrupts_taking_priority_over_text_content() {
395        let interrupt = Interrupt::new("i-1", "confirm").with_reason("ok?");
396        let result = result(StopReason::Interrupt, vec![text("ignored")]).with_interrupts(vec![interrupt.clone()]);
397        assert_eq!(result.to_string(), serde_json::to_string(&[interrupt]).unwrap());
398        assert_eq!(
399            result.to_string(),
400            r#"[{"id":"i-1","name":"confirm","reason":"ok?","source":"hook"}]"#
401        );
402    }
403
404    #[test]
405    fn falls_through_when_interrupts_array_is_empty() {
406        let result = result(StopReason::EndTurn, vec![text("Hello")]).with_interrupts(vec![]);
407        assert_eq!(result.to_string(), "Hello");
408    }
409
410    #[test]
411    fn returns_json_stringified_structured_output_taking_priority_over_text_content() {
412        let result = result(StopReason::EndTurn, vec![text("ignored")])
413            .with_structured_output(json!({"answer": 42, "note": "hello"}));
414        assert_eq!(result.to_string(), r#"{"answer":42,"note":"hello"}"#);
415    }
416
417    #[test]
418    fn returns_interrupts_taking_priority_over_structured_output() {
419        let interrupt = Interrupt::new("i-1", "confirm");
420        let result = result(StopReason::Interrupt, vec![text("ignored")])
421            .with_interrupts(vec![interrupt])
422            .with_structured_output(json!({"answer": 42}));
423        assert_eq!(result.to_string(), r#"[{"id":"i-1","name":"confirm","source":"hook"}]"#);
424    }
425
426    #[test]
427    fn concatenates_generated_content_text_from_citations() {
428        let citation = Citation::new(
429            CitationLocation::DocumentChar(DocumentCharLocation::new(0, 0, 5)),
430            "doc",
431            vec![CitationSourceContent::new("source text")],
432            "Doc",
433        );
434        let citations = CitationsBlock::new(vec![citation], vec![CitationGeneratedContent::new("cited fragment")]);
435        let result = result(StopReason::EndTurn, vec![text("Here is a citation:"), citations.into()]);
436        assert_eq!(result.to_string(), "Here is a citation:\ncited fragment");
437    }
438
439    #[test]
440    fn works_with_string_conversion() {
441        assert_eq!(result(StopReason::EndTurn, vec![text("Hello")]).to_string(), "Hello");
442    }
443
444    #[test]
445    fn works_with_template_literals() {
446        let result = result(StopReason::EndTurn, vec![text("World")]);
447        assert_eq!(format!("Response: {result}"), "Response: World");
448    }
449
450    #[test]
451    fn returns_latest_context_size_from_metrics() {
452        let result = AgentResult::new(StopReason::EndTurn, assistant(vec![text("Hello")]))
453            .with_metrics(AgentMetrics::new().with_latest_context_size(500));
454        assert_eq!(result.context_size(), Some(500));
455    }
456
457    #[test]
458    fn returns_undefined_when_metrics_has_no_latest_context_size() {
459        assert_eq!(result(StopReason::EndTurn, vec![text("Hello")]).context_size(), None);
460    }
461
462    #[test]
463    fn returns_undefined_when_no_metrics_are_available() {
464        let result = AgentResult::new(StopReason::EndTurn, assistant(vec![text("Hello")]));
465        assert_eq!(result.context_size(), None);
466        assert_eq!(result.projected_context_size(), None);
467    }
468
469    #[test]
470    fn returns_projected_context_size_from_metrics() {
471        let result = AgentResult::new(StopReason::EndTurn, assistant(vec![text("Hello")]))
472            .with_metrics(AgentMetrics::new().with_projected_context_size(750));
473        assert_eq!(result.projected_context_size(), Some(750));
474    }
475
476    #[test]
477    fn returns_undefined_when_metrics_has_no_projected_context_size() {
478        assert_eq!(
479            result(StopReason::EndTurn, vec![text("Hello")]).projected_context_size(),
480            None
481        );
482    }
483
484    fn with_traces(content: &str) -> (AgentResult, Message) {
485        let message = assistant(vec![text(content)]).with_tracking_id("m-1");
486        let result = AgentResult::new(StopReason::EndTurn, message.clone())
487            .with_traces(vec![AgentTrace::new("Cycle 1", 0)])
488            .with_metrics(AgentMetrics::new());
489        (result, message)
490    }
491
492    #[test]
493    fn excludes_traces_and_metrics_from_serialization() {
494        let (result, message) = with_traces("Hello");
495        assert_eq!(
496            serde_json::to_value(&result).unwrap(),
497            json!({"type": "agentResult", "stopReason": "endTurn", "lastMessage": message})
498        );
499    }
500
501    #[test]
502    fn includes_structured_output_when_present() {
503        let result = AgentResult::new(StopReason::EndTurn, assistant(vec![text("Response")]))
504            .with_structured_output(json!({"field": "value"}));
505        assert_eq!(
506            serde_json::to_value(&result).unwrap()["structuredOutput"],
507            json!({"field": "value"})
508        );
509    }
510
511    #[test]
512    fn excludes_structured_output_when_not_present() {
513        let result = AgentResult::new(StopReason::EndTurn, assistant(vec![text("Response")]));
514        assert!(serde_json::to_value(&result).unwrap().get("structuredOutput").is_none());
515    }
516
517    #[test]
518    fn is_automatically_used_by_json_stringify() {
519        let (result, _) = with_traces("Hello");
520        let parsed: JsonValue = serde_json::from_str(&serde_json::to_string(&result).unwrap()).unwrap();
521        assert_eq!(parsed["type"], "agentResult");
522        assert_eq!(parsed["lastMessage"]["role"], "assistant");
523        assert_eq!(parsed.as_object().unwrap().len(), 3);
524    }
525
526    #[test]
527    fn preserves_traces_and_metrics_as_accessible_properties() {
528        let (result, message) = with_traces("Hello");
529        assert_eq!(result.traces().map(<[AgentTrace]>::len), Some(1));
530        assert_eq!(result.metrics(), Some(&AgentMetrics::new()));
531        assert_eq!(
532            serde_json::to_value(&result).unwrap(),
533            json!({"type": "agentResult", "stopReason": "endTurn", "lastMessage": message})
534        );
535    }
536
537    #[test]
538    fn prevents_bloated_api_responses_when_forwarding_result_directly() {
539        let (result, _) = with_traces("Response text");
540        let response: JsonValue = serde_json::to_value(&result).unwrap();
541        assert!(response.get("traces").is_none());
542        assert!(response.get("metrics").is_none());
543    }
544
545    #[test]
546    fn deserializes_the_to_json_shape() {
547        let wire = r#"{"type":"agentResult","stopReason":"endTurn","lastMessage":{"role":"assistant","content":[{"text":"hi"}],"trackingId":"m-1"},"structuredOutput":{"a":1}}"#;
548        let result: AgentResult = serde_json::from_str(wire).unwrap();
549        assert_eq!(serde_json::to_string(&result).unwrap(), wire);
550        assert_eq!(result.structured_output::<JsonValue>().unwrap(), json!({"a": 1}));
551        assert!(serde_json::from_str::<AgentResult>(&wire.replace("agentResult", "other")).is_err());
552    }
553
554    #[test]
555    fn structured_output_is_typed_and_errors_when_absent() {
556        #[derive(Deserialize, Debug, PartialEq)]
557        struct Answer {
558            answer: u32,
559        }
560        let result =
561            AgentResult::new(StopReason::EndTurn, assistant(vec![])).with_structured_output(json!({"answer": 42}));
562        assert_eq!(result.structured_output::<Answer>().unwrap(), Answer { answer: 42 });
563        let error = AgentResult::new(StopReason::EndTurn, assistant(vec![]))
564            .structured_output::<Answer>()
565            .unwrap_err();
566        assert_eq!(error.to_string(), NO_STRUCTURED_OUTPUT);
567    }
568}