a2a_protocol_server/tool_loop/model.rs
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Tom F. <[email protected]> (https://github.com/tomtom215)
3
4//! [`ToolModel`], one completion turn of a model that can call tools, and
5//! the conversation it is given.
6//!
7//! The types here are provider-neutral: they say what a turn needs (the
8//! preamble, the conversation, the tool catalogue) and what it returns (text
9//! and calls), not how any one API spells them.
10//! [`OpenAiChatModel`](super::OpenAiChatModel) is the bundled translation
11//! to the chat-completions wire format; any other provider is a
12//! [`ToolModel`] the integrator writes.
13
14use std::fmt;
15use std::future::Future;
16use std::pin::Pin;
17use std::time::Duration;
18
19use serde::{Deserialize, Serialize};
20use serde_json::Value;
21
22/// One message of the conversation a [`ToolModel`] is given.
23#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
24#[serde(tag = "role", content = "body", rename_all = "snake_case")]
25#[non_exhaustive]
26pub enum ChatMessage {
27 /// An instruction from the operator, beside the preamble.
28 System(String),
29 /// What the caller asked.
30 User(String),
31 /// A turn the model took: its text and the calls it asked for.
32 Assistant {
33 /// The text of the turn; empty when the model only called tools.
34 text: String,
35 /// The calls it asked for, in order.
36 tool_calls: Vec<ToolCall>,
37 },
38 /// The result of one call, sent back to the model.
39 ToolResult {
40 /// The [`ToolCall::id`] this answers.
41 call_id: String,
42 /// The tool that ran.
43 name: String,
44 /// What the tool returned, or the error the loop reports for it.
45 content: String,
46 },
47}
48
49/// One call a model asked for.
50#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
51#[non_exhaustive]
52pub struct ToolCall {
53 /// The provider's id for the call, which the result must carry back.
54 pub id: String,
55 /// The tool's name, as the model wrote it.
56 pub name: String,
57 /// The arguments as JSON text, as the model wrote them. Not parsed here:
58 /// arguments that are not a JSON object are the model's mistake, and the
59 /// loop tells the model so rather than failing the turn.
60 pub arguments: String,
61}
62
63impl ToolCall {
64 /// A call to `name` with `arguments` as JSON text.
65 #[must_use]
66 pub fn new(
67 id: impl Into<String>,
68 name: impl Into<String>,
69 arguments: impl Into<String>,
70 ) -> Self {
71 Self {
72 id: id.into(),
73 name: name.into(),
74 arguments: arguments.into(),
75 }
76 }
77}
78
79/// What the model is told about one tool.
80#[derive(Debug, Clone, PartialEq, Eq)]
81#[non_exhaustive]
82pub struct ToolSpec {
83 /// The name the model calls it by.
84 pub name: String,
85 /// What it does, for the model to choose by.
86 pub description: String,
87 /// A JSON Schema for its arguments.
88 pub parameters: Value,
89}
90
91impl ToolSpec {
92 /// A specification from its three parts.
93 #[must_use]
94 pub fn new(name: impl Into<String>, description: impl Into<String>, parameters: Value) -> Self {
95 Self {
96 name: name.into(),
97 description: description.into(),
98 parameters,
99 }
100 }
101}
102
103/// Everything one turn is asked with.
104///
105/// A provider holds no state between turns, so every request carries the
106/// whole conversation and the whole catalogue.
107#[derive(Debug, Clone, Copy)]
108#[non_exhaustive]
109pub struct ChatRequest<'a> {
110 /// The system preamble; empty for none.
111 pub preamble: &'a str,
112 /// The conversation so far, oldest first.
113 pub messages: &'a [ChatMessage],
114 /// The tools the model may call.
115 pub tools: &'a [ToolSpec],
116}
117
118impl<'a> ChatRequest<'a> {
119 /// A request from its three parts.
120 #[must_use]
121 pub const fn new(
122 preamble: &'a str,
123 messages: &'a [ChatMessage],
124 tools: &'a [ToolSpec],
125 ) -> Self {
126 Self {
127 preamble,
128 messages,
129 tools,
130 }
131 }
132}
133
134/// The tokens one turn used, as the provider reported them.
135#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
136#[non_exhaustive]
137pub struct TokenUsage {
138 /// Tokens in the request.
139 pub input_tokens: Option<u64>,
140 /// Tokens in the reply.
141 pub output_tokens: Option<u64>,
142}
143
144impl TokenUsage {
145 /// Usage from the two counts, either of which a provider may omit.
146 #[must_use]
147 pub const fn new(input_tokens: Option<u64>, output_tokens: Option<u64>) -> Self {
148 Self {
149 input_tokens,
150 output_tokens,
151 }
152 }
153}
154
155/// What one turn produced.
156#[derive(Debug, Clone, Default, PartialEq, Eq)]
157#[non_exhaustive]
158pub struct ModelTurn {
159 /// The turn's text.
160 pub text: String,
161 /// The calls the model asked for; empty when it answered.
162 pub tool_calls: Vec<ToolCall>,
163 /// Token usage, when the provider reported it.
164 pub usage: Option<TokenUsage>,
165 /// The model that answered, when the provider named it.
166 pub response_model: Option<String>,
167 /// The provider's id for the completion, when it gave one; recorded as
168 /// `gen_ai.response.id`.
169 pub response_id: Option<String>,
170 /// Why the model stopped, as the provider spelled it (`stop`,
171 /// `tool_calls`, `length`, …); recorded as
172 /// `gen_ai.response.finish_reasons`.
173 pub finish_reason: Option<String>,
174}
175
176impl ModelTurn {
177 /// A turn of `text` and `tool_calls`.
178 #[must_use]
179 pub fn new(text: impl Into<String>, tool_calls: Vec<ToolCall>) -> Self {
180 Self {
181 text: text.into(),
182 tool_calls,
183 usage: None,
184 response_model: None,
185 response_id: None,
186 finish_reason: None,
187 }
188 }
189
190 /// Sets the token usage.
191 #[must_use]
192 pub const fn with_usage(mut self, usage: TokenUsage) -> Self {
193 self.usage = Some(usage);
194 self
195 }
196
197 /// Sets the model the provider says answered.
198 #[must_use]
199 pub fn with_response_model(mut self, model: impl Into<String>) -> Self {
200 self.response_model = Some(model.into());
201 self
202 }
203
204 /// Sets the provider's id for the completion.
205 #[must_use]
206 pub fn with_response_id(mut self, id: impl Into<String>) -> Self {
207 self.response_id = Some(id.into());
208 self
209 }
210
211 /// Sets why the model stopped, as the provider spelled it.
212 #[must_use]
213 pub fn with_finish_reason(mut self, reason: impl Into<String>) -> Self {
214 self.finish_reason = Some(reason.into());
215 self
216 }
217}
218
219/// Why a turn produced nothing. Each is the provider's failure, not the
220/// model's: a model's mistakes are fed back to it by the loop.
221#[derive(Debug, Clone, PartialEq, Eq)]
222#[non_exhaustive]
223pub enum ModelError {
224 /// The provider answered with a status outside 2xx.
225 Status {
226 /// The HTTP status.
227 status: u16,
228 /// At most 512 bytes of the response body, cut on a character
229 /// boundary.
230 body: String,
231 },
232 /// The provider refused the turn as over its rate limit (HTTP 429),
233 /// saying when to come back if it did. Until 0.16.0 this was
234 /// [`Status`](Self::Status) with `status: 429`; it is a variant of its
235 /// own so the delay can travel with it (audit H17, ADR 0048).
236 /// [`ToolLoop::with_model_retry`](super::ToolLoop::with_model_retry)
237 /// retries it.
238 RateLimited {
239 /// The provider's `Retry-After`, read as delta-seconds or an HTTP
240 /// date, and `None` when it sent none that could be read.
241 retry_after: Option<Duration>,
242 /// At most 512 bytes of the response body, cut on a character
243 /// boundary.
244 body: String,
245 },
246 /// No complete answer within the request timeout.
247 Timeout(Duration),
248 /// The request could not be sent, or the connection failed.
249 Transport(String),
250 /// The answer was not a chat completion this client can read.
251 InvalidResponse(String),
252 /// The answer's body was larger than the configured cap, in bytes.
253 ResponseTooLarge(usize),
254 /// The client is configured in a way that cannot work, such as an
255 /// `https://` endpoint in a build without TLS.
256 Config(String),
257 /// Any other failure, from a [`ToolModel`] the integrator wrote.
258 Other(String),
259}
260
261impl ModelError {
262 /// The low-cardinality `error.type` a span records for this failure:
263 /// the status code for [`Status`](Self::Status), as the HTTP
264 /// conventions do, and a fixed word for the rest.
265 #[must_use]
266 pub fn error_type(&self) -> String {
267 match self {
268 Self::Status { status, .. } => status.to_string(),
269 Self::RateLimited { .. } => "429".to_owned(),
270 Self::Timeout(_) => "timeout".to_owned(),
271 Self::Transport(_) => "transport".to_owned(),
272 Self::InvalidResponse(_) => "invalid_response".to_owned(),
273 Self::ResponseTooLarge(_) => "response_too_large".to_owned(),
274 Self::Config(_) => "configuration".to_owned(),
275 Self::Other(_) => "_OTHER".to_owned(),
276 }
277 }
278}
279
280impl fmt::Display for ModelError {
281 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
282 match self {
283 Self::Status { status, body } if body.is_empty() => {
284 write!(f, "the model provider answered HTTP {status}")
285 }
286 Self::Status { status, body } => {
287 write!(f, "the model provider answered HTTP {status}: {body}")
288 }
289 Self::RateLimited { body, .. } if body.is_empty() => {
290 f.write_str("the model provider answered HTTP 429")
291 }
292 Self::RateLimited { body, .. } => {
293 write!(f, "the model provider answered HTTP 429: {body}")
294 }
295 Self::Timeout(after) => {
296 write!(f, "the model provider did not answer within {after:?}")
297 }
298 Self::Transport(e) => write!(f, "could not reach the model provider: {e}"),
299 Self::InvalidResponse(e) => {
300 write!(f, "the model provider's answer could not be read: {e}")
301 }
302 Self::ResponseTooLarge(cap) => write!(
303 f,
304 "the model provider's answer is larger than the {cap}-byte cap"
305 ),
306 Self::Config(e) | Self::Other(e) => f.write_str(e),
307 }
308 }
309}
310
311impl std::error::Error for ModelError {}
312
313/// Where a streaming turn sends its text as it arrives: see
314/// [`ToolModel::complete_streaming`]. Cheap to call for every piece; a piece
315/// sent after the run ended is dropped.
316#[derive(Debug, Clone)]
317pub struct TextSink {
318 turn: usize,
319 tx: tokio::sync::mpsc::UnboundedSender<(usize, String)>,
320}
321
322impl TextSink {
323 /// A sink for `turn`'s pieces, sent on `tx` with the turn number: what
324 /// the loop hands a streaming turn, and what a test of a model's
325 /// [`complete_streaming`](ToolModel::complete_streaming) can build.
326 #[must_use]
327 pub const fn new(turn: usize, tx: tokio::sync::mpsc::UnboundedSender<(usize, String)>) -> Self {
328 Self { turn, tx }
329 }
330
331 /// Hands on `piece`, the next stretch of the turn's answer text. An
332 /// empty piece is ignored.
333 pub fn push(&self, piece: &str) {
334 if !piece.is_empty() {
335 let _ = self.tx.send((self.turn, piece.to_owned()));
336 }
337 }
338}
339
340/// One completion turn of a model that can call tools.
341///
342/// Object-safe, with boxed futures, like [`AgentExecutor`](crate::AgentExecutor):
343/// [`ToolLoop`](super::ToolLoop) holds it as a `Box<dyn ToolModel>`.
344///
345/// An implementation sends the request once and reports what came back. It
346/// does not run tools, retry or loop; [`ToolLoop`](super::ToolLoop) does.
347/// [`LimitedModel`](super::LimitedModel) wraps one to bound how many turns
348/// are in flight at once.
349pub trait ToolModel: Send + Sync + 'static {
350 /// The model asked for, recorded as `gen_ai.request.model` and in the
351 /// name of each turn's span (`chat {model}`).
352 fn model_name(&self) -> &str;
353
354 /// The provider, recorded as `gen_ai.provider.name`: one of the
355 /// `GenAI` conventions' well-known values (`openai`, `anthropic`,
356 /// `gcp.gemini`, …) when one applies.
357 fn provider_name(&self) -> &str;
358
359 /// Where the provider is served, as a host and port, recorded as
360 /// `server.address` and `server.port`. `None`, the default, records
361 /// neither: a model running in this process has no server.
362 fn server(&self) -> Option<(&str, u16)> {
363 None
364 }
365
366 /// Runs one turn.
367 ///
368 /// # Errors
369 ///
370 /// A [`ModelError`] when the provider failed. The loop ends the task on
371 /// it, except that a loop given
372 /// [`with_model_retry`](super::ToolLoop::with_model_retry) sends the
373 /// turn again after a [`RateLimited`](ModelError::RateLimited).
374 fn complete<'a>(
375 &'a self,
376 request: ChatRequest<'a>,
377 ) -> Pin<Box<dyn Future<Output = Result<ModelTurn, ModelError>> + Send + 'a>>;
378
379 /// Runs one turn as [`complete`](Self::complete) does, and hands
380 /// `text` each piece of the turn's text as the provider sends it, so a
381 /// caller can watch a long answer arrive (audit L5). The turn it
382 /// returns is the whole of it, its text the pieces joined.
383 ///
384 /// The default runs [`complete`](Self::complete) and sends no piece: a
385 /// model that cannot stream still works, and its turns arrive whole.
386 /// [`OpenAiChatModel`](super::OpenAiChatModel) streams.
387 ///
388 /// # Errors
389 ///
390 /// As [`complete`](Self::complete).
391 fn complete_streaming<'a>(
392 &'a self,
393 request: ChatRequest<'a>,
394 text: &'a TextSink,
395 ) -> Pin<Box<dyn Future<Output = Result<ModelTurn, ModelError>> + Send + 'a>> {
396 let _ = text;
397 self.complete(request)
398 }
399}
400
401#[cfg(test)]
402mod tests {
403 use super::*;
404
405 /// A status with no body says only the status; with one, both. The
406 /// mutation gate found the empty case untested: printing `: ` after the
407 /// status survived.
408 #[test]
409 fn a_status_error_names_its_body_only_when_it_has_one() {
410 let bare = ModelError::Status {
411 status: 503,
412 body: String::new(),
413 };
414 assert_eq!(bare.to_string(), "the model provider answered HTTP 503");
415 let with_body = ModelError::Status {
416 status: 429,
417 body: "slow down".to_owned(),
418 };
419 assert_eq!(
420 with_body.to_string(),
421 "the model provider answered HTTP 429: slow down"
422 );
423 }
424
425 /// A rate-limited turn reads as the 429 it was, with or without a body,
426 /// and records the `error.type` a `Status { status: 429 }` recorded, so
427 /// dashboards keyed on it keep counting.
428 #[test]
429 fn a_rate_limited_turn_reads_and_records_as_a_429() {
430 let bare = ModelError::RateLimited {
431 retry_after: Some(Duration::from_secs(2)),
432 body: String::new(),
433 };
434 assert_eq!(bare.to_string(), "the model provider answered HTTP 429");
435 assert_eq!(bare.error_type(), "429");
436 let with_body = ModelError::RateLimited {
437 retry_after: None,
438 body: "slow down".to_owned(),
439 };
440 assert_eq!(
441 with_body.to_string(),
442 "the model provider answered HTTP 429: slow down"
443 );
444 }
445}