a2a_protocol_server/tool_loop/answer.rs
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Tom F. <[email protected]> (https://github.com/tomtom215)
3
4//! [`Answer`]: what a run of the loop produced, and when it counts as one.
5
6use super::loop_error::LoopError;
7
8/// The `finish_reason` of a reply that stopped at the model's output limit.
9///
10/// [`OpenAiChatModel`](super::OpenAiChatModel) passes the provider's value
11/// through, and this is the OpenAI-compatible spelling; a
12/// [`ToolModel`](super::ToolModel) of your own reports a cut-off reply as
13/// this too, through
14/// [`ModelTurn::with_finish_reason`](super::ModelTurn::with_finish_reason).
15pub const FINISH_REASON_LENGTH: &str = "length";
16
17/// The `metadata` key that marks an answer cut off at the output limit.
18///
19/// It is on the answer artifact, and on the status message of the task that
20/// completed with it; its value is the model's `finish_reason`. Present only
21/// when the reply was cut off ([`FINISH_REASON_LENGTH`]): the text is then a
22/// prefix of an answer, and may end mid-sentence.
23pub const FINISH_REASON_METADATA_KEY: &str = "a2a-rust.com/finish-reason";
24
25/// What a run produced.
26#[derive(Debug, Clone, PartialEq, Eq)]
27#[non_exhaustive]
28pub struct Answer {
29 /// The model's final text. Never empty or blank: a run whose final reply
30 /// has no text ends in [`LoopError::EmptyAnswer`] instead.
31 pub text: String,
32 /// One line per tool call, in the order they ran: `name(arguments) ->
33 /// result`. Empty when the model answered without calling anything.
34 pub trace: Vec<String>,
35 /// Why the final reply stopped, as the provider spelled it (`stop`,
36 /// `length`, …), when it said.
37 pub finish_reason: Option<String>,
38}
39
40impl Answer {
41 /// The answer a run ends in when its final reply was `text`, or
42 /// [`LoopError::EmptyAnswer`] when that reply has no text to give: an
43 /// empty reply is no answer, however the model came to send it (a
44 /// reasoning model whose output limit went on thinking sends one).
45 pub(super) fn from_reply(
46 text: String,
47 trace: Vec<String>,
48 finish_reason: Option<String>,
49 ) -> Result<Self, LoopError> {
50 if text.trim().is_empty() {
51 return Err(LoopError::EmptyAnswer { finish_reason });
52 }
53 Ok(Self {
54 text,
55 trace,
56 finish_reason,
57 })
58 }
59
60 /// Whether the reply stopped at the model's output limit, so that
61 /// [`text`](Self::text) may end mid-sentence.
62 #[must_use]
63 pub fn truncated(&self) -> bool {
64 self.finish_reason.as_deref() == Some(FINISH_REASON_LENGTH)
65 }
66}
67
68#[cfg(test)]
69mod tests {
70 use super::*;
71
72 fn reply(text: &str, reason: Option<&str>) -> Result<Answer, LoopError> {
73 Answer::from_reply(
74 text.to_owned(),
75 vec!["t() -> ok".to_owned()],
76 reason.map(str::to_owned),
77 )
78 }
79
80 /// The text, trace and reason arrive as given.
81 #[test]
82 fn an_answer_carries_what_the_reply_gave() {
83 assert_eq!(
84 reply("done", Some("stop")),
85 Ok(Answer {
86 text: "done".to_owned(),
87 trace: vec!["t() -> ok".to_owned()],
88 finish_reason: Some("stop".to_owned()),
89 })
90 );
91 }
92
93 /// Nothing, or only whitespace, is not an answer; one character is. The
94 /// reason the model gave goes with the error, and the text is not kept.
95 #[test]
96 fn a_reply_with_no_text_is_not_an_answer() {
97 for blank in ["", " ", "\n", " \t\r\n "] {
98 assert_eq!(
99 reply(blank, Some("length")),
100 Err(LoopError::EmptyAnswer {
101 finish_reason: Some("length".to_owned())
102 }),
103 "{blank:?}"
104 );
105 }
106 assert_eq!(
107 reply("", None),
108 Err(LoopError::EmptyAnswer {
109 finish_reason: None
110 })
111 );
112 assert_eq!(reply("a", None).unwrap().text, "a");
113 // Surrounding whitespace is the model's, and kept.
114 assert_eq!(reply(" a\n", None).unwrap().text, " a\n");
115 }
116
117 /// Only `length` is a cut-off; `stop`, a tool-call reason, no reason, and
118 /// a near miss are not.
119 #[test]
120 fn only_the_output_limit_makes_an_answer_truncated() {
121 let truncated = |reason: Option<&str>| reply("x", reason).unwrap().truncated();
122 assert!(truncated(Some("length")));
123 for other in [
124 Some("stop"),
125 Some("tool_calls"),
126 Some("Length"),
127 Some(""),
128 None,
129 ] {
130 assert!(!truncated(other), "{other:?}");
131 }
132 }
133}