Skip to main content

graphrt_llm/
types.rs

1//! Provider-neutral chat types.
2//!
3//! Every provider translates [`ChatRequest`] into its wire format and its
4//! streaming response into [`ChatDelta`]s. [`collect`] folds a delta stream
5//! into a [`ChatResponse`].
6
7use std::collections::BTreeMap;
8use std::fmt;
9use std::pin::Pin;
10
11use futures::future::BoxFuture;
12use futures::{Stream, StreamExt};
13use graphrt_core::event::Usage;
14use graphrt_core::tool::ToolSpec;
15use serde::{Deserialize, Serialize};
16
17use crate::error::LlmError;
18
19/// Author of a message.
20#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
21#[serde(rename_all = "lowercase")]
22#[non_exhaustive]
23pub enum Role {
24    System,
25    User,
26    Assistant,
27    Tool,
28}
29
30/// One piece of message content.
31#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
32#[serde(tag = "type", rename_all = "snake_case")]
33#[non_exhaustive]
34pub enum ContentPart {
35    Text {
36        text: String,
37    },
38    /// An image by URL (`https://...` or a `data:<mime>;base64,...` URL).
39    Image {
40        url: String,
41        #[serde(default, skip_serializing_if = "Option::is_none")]
42        detail: Option<String>,
43    },
44}
45
46/// A tool call requested by the model. `arguments` is the raw JSON text.
47#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
48pub struct ToolCall {
49    pub id: String,
50    pub name: String,
51    pub arguments: String,
52}
53
54/// Tool-call arguments that are not a JSON object.
55#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
56#[error("tool call `{name}` has invalid JSON arguments: {reason}")]
57pub struct InvalidToolArguments {
58    /// Tool name of the offending call.
59    pub name: String,
60    pub reason: String,
61}
62
63impl ToolCall {
64    /// Arguments parsed as a JSON object. Empty text means "no arguments" and
65    /// yields an empty object; anything that is not a JSON object is an error
66    /// (it usually means the model output was truncated or malformed).
67    pub fn arguments_json(&self) -> Result<serde_json::Map<String, serde_json::Value>, InvalidToolArguments> {
68        if self.arguments.trim().is_empty() {
69            return Ok(serde_json::Map::new());
70        }
71        let invalid = |reason: String| InvalidToolArguments { name: self.name.clone(), reason };
72        match serde_json::from_str::<serde_json::Value>(&self.arguments) {
73            Ok(serde_json::Value::Object(map)) => Ok(map),
74            Ok(other) => Err(invalid(format!("expected a JSON object, got {}", json_kind(&other)))),
75            Err(e) => Err(invalid(e.to_string())),
76        }
77    }
78}
79
80fn json_kind(v: &serde_json::Value) -> &'static str {
81    match v {
82        serde_json::Value::Null => "null",
83        serde_json::Value::Bool(_) => "a boolean",
84        serde_json::Value::Number(_) => "a number",
85        serde_json::Value::String(_) => "a string",
86        serde_json::Value::Array(_) => "an array",
87        serde_json::Value::Object(_) => "an object",
88    }
89}
90
91/// A chat message.
92#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
93pub struct Message {
94    pub role: Role,
95    #[serde(default)]
96    pub content: Vec<ContentPart>,
97    /// Tool calls made by an assistant message.
98    #[serde(default, skip_serializing_if = "Vec::is_empty")]
99    pub tool_calls: Vec<ToolCall>,
100    /// For `tool` messages: the call this message answers.
101    #[serde(default, skip_serializing_if = "Option::is_none")]
102    pub tool_call_id: Option<String>,
103    /// Opaque provider state attached to an assistant message (e.g. signed
104    /// reasoning blocks) that must be sent back verbatim on the next turn.
105    #[serde(default, skip_serializing_if = "Option::is_none")]
106    pub provider_state: Option<serde_json::Value>,
107}
108
109impl Message {
110    fn with_text(role: Role, text: impl Into<String>) -> Self {
111        Self {
112            role,
113            content: vec![ContentPart::Text { text: text.into() }],
114            tool_calls: Vec::new(),
115            tool_call_id: None,
116            provider_state: None,
117        }
118    }
119
120    pub fn system(text: impl Into<String>) -> Self {
121        Self::with_text(Role::System, text)
122    }
123
124    pub fn user(text: impl Into<String>) -> Self {
125        Self::with_text(Role::User, text)
126    }
127
128    pub fn assistant(text: impl Into<String>) -> Self {
129        Self::with_text(Role::Assistant, text)
130    }
131
132    /// A tool result answering `call_id`.
133    pub fn tool(call_id: impl Into<String>, text: impl Into<String>) -> Self {
134        let mut m = Self::with_text(Role::Tool, text);
135        m.tool_call_id = Some(call_id.into());
136        m
137    }
138
139    /// A tool result answering `call_id` with images (`https://` or `data:`
140    /// URLs) after the text. Providers that cannot put images in a tool
141    /// result send them in a user turn right after the tool results.
142    pub fn tool_with_images(
143        call_id: impl Into<String>,
144        text: impl Into<String>,
145        image_urls: impl IntoIterator<Item = String>,
146    ) -> Self {
147        let mut m = Self::tool(call_id, text);
148        m.content.extend(image_urls.into_iter().map(|url| ContentPart::Image { url, detail: None }));
149        m
150    }
151
152    /// Image parts, in order.
153    pub fn images(&self) -> impl Iterator<Item = &ContentPart> {
154        self.content.iter().filter(|p| matches!(p, ContentPart::Image { .. }))
155    }
156
157    /// Concatenated text parts.
158    pub fn text(&self) -> String {
159        let mut out = String::new();
160        for part in &self.content {
161            if let ContentPart::Text { text } = part {
162                out.push_str(text);
163            }
164        }
165        out
166    }
167}
168
169/// Text of a tool message for providers whose tool results are text-only:
170/// the message text plus a note saying how many images follow.
171#[cfg(feature = "openai")]
172pub(crate) fn tool_text_with_image_note(m: &Message) -> String {
173    let text = m.text();
174    let count = m.images().count();
175    if count == 0 {
176        return text;
177    }
178    let note = if count == 1 {
179        "[1 image attached after the tool results]".to_owned()
180    } else {
181        format!("[{count} images attached after the tool results]")
182    };
183    if text.is_empty() { note } else { format!("{text}\n{note}") }
184}
185
186/// Text introducing the images of one tool result in the fallback user turn.
187#[cfg(any(feature = "openai", feature = "gemini", feature = "bedrock"))]
188pub(crate) fn tool_images_intro(name: Option<&str>, call_id: &str) -> String {
189    match name {
190        Some(name) => format!("Images returned by tool `{name}` (call {call_id}):"),
191        None => format!("Images returned by tool call {call_id}:"),
192    }
193}
194
195/// How the model may use tools.
196#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
197#[serde(rename_all = "snake_case")]
198#[non_exhaustive]
199pub enum ToolChoice {
200    Auto,
201    None,
202    /// The model must call some tool.
203    Required,
204    /// The model must call this tool.
205    Tool(String),
206}
207
208/// Requested output format.
209#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
210#[serde(tag = "type", rename_all = "snake_case")]
211#[non_exhaustive]
212pub enum ResponseFormat {
213    Text,
214    JsonObject,
215    JsonSchema {
216        name: String,
217        schema: serde_json::Value,
218        #[serde(default)]
219        strict: bool,
220    },
221}
222
223/// A provider-neutral chat request.
224#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
225pub struct ChatRequest {
226    pub model: String,
227    pub messages: Vec<Message>,
228    #[serde(default, skip_serializing_if = "Vec::is_empty")]
229    pub tools: Vec<ToolSpec>,
230    #[serde(default, skip_serializing_if = "Option::is_none")]
231    pub tool_choice: Option<ToolChoice>,
232    #[serde(default, skip_serializing_if = "Option::is_none")]
233    pub temperature: Option<f64>,
234    #[serde(default, skip_serializing_if = "Option::is_none")]
235    pub top_p: Option<f64>,
236    #[serde(default, skip_serializing_if = "Option::is_none")]
237    pub max_tokens: Option<u32>,
238    /// The most output the run's budget leaves for this call, set by the node
239    /// before the call. Providers ask for the lower of it and `max_tokens` (or
240    /// their own default), so it never raises an output limit.
241    #[serde(default, skip_serializing_if = "Option::is_none")]
242    pub budget_max_tokens: Option<u32>,
243    #[serde(default, skip_serializing_if = "Vec::is_empty")]
244    pub stop: Vec<String>,
245    #[serde(default, skip_serializing_if = "Option::is_none")]
246    pub response_format: Option<ResponseFormat>,
247    /// Provider-specific parameters merged into the request body as-is.
248    #[serde(default, skip_serializing_if = "serde_json::Map::is_empty")]
249    pub extra: serde_json::Map<String, serde_json::Value>,
250}
251
252impl ChatRequest {
253    pub fn new(model: impl Into<String>, messages: Vec<Message>) -> Self {
254        Self { model: model.into(), messages, ..Self::default() }
255    }
256
257    /// The output limit to send: the lower of `max_tokens` and `budget_max_tokens`.
258    pub fn output_limit(&self) -> Option<u32> {
259        match (self.max_tokens, self.budget_max_tokens) {
260            (Some(asked), Some(budget)) => Some(asked.min(budget)),
261            (asked, budget) => asked.or(budget),
262        }
263    }
264
265    /// Set the tools offered to the model.
266    pub fn with_tools(mut self, tools: Vec<ToolSpec>) -> Self {
267        self.tools = tools;
268        self
269    }
270
271    /// Set how the model may use tools.
272    pub fn with_tool_choice(mut self, choice: ToolChoice) -> Self {
273        self.tool_choice = Some(choice);
274        self
275    }
276
277    pub fn with_temperature(mut self, temperature: f64) -> Self {
278        self.temperature = Some(temperature);
279        self
280    }
281
282    pub fn with_top_p(mut self, top_p: f64) -> Self {
283        self.top_p = Some(top_p);
284        self
285    }
286
287    pub fn with_max_tokens(mut self, max_tokens: u32) -> Self {
288        self.max_tokens = Some(max_tokens);
289        self
290    }
291
292    pub fn with_stop(mut self, stop: Vec<String>) -> Self {
293        self.stop = stop;
294        self
295    }
296
297    pub fn with_response_format(mut self, format: ResponseFormat) -> Self {
298        self.response_format = Some(format);
299        self
300    }
301
302    /// Add a provider-specific body parameter.
303    pub fn with_extra(mut self, key: impl Into<String>, value: serde_json::Value) -> Self {
304        self.extra.insert(key.into(), value);
305        self
306    }
307}
308
309/// Body keys owned by the providers; [`ChatRequest::extra`] must not set them.
310pub const RESERVED_EXTRA_KEYS: &[&str] = &["model", "messages", "stream", "stream_options", "tools", "tool_choice"];
311
312/// Reject `extra` keys that would silently override provider-managed fields.
313/// Custom [`ChatModel`] implementations should call this before building a body.
314pub fn check_extra(req: &ChatRequest) -> Result<(), LlmError> {
315    for key in req.extra.keys() {
316        if RESERVED_EXTRA_KEYS.contains(&key.as_str()) {
317            return Err(LlmError::Config(format!(
318                "parameter `{key}` cannot be set through extra parameters; use the dedicated request field"
319            )));
320        }
321    }
322    Ok(())
323}
324
325/// Why generation stopped.
326#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
327#[serde(rename_all = "snake_case")]
328#[non_exhaustive]
329pub enum FinishReason {
330    Stop,
331    Length,
332    ToolCalls,
333    ContentFilter,
334    Other(String),
335}
336
337impl FinishReason {
338    /// Stable wire name.
339    pub fn as_str(&self) -> &str {
340        match self {
341            FinishReason::Stop => "stop",
342            FinishReason::Length => "length",
343            FinishReason::ToolCalls => "tool_calls",
344            FinishReason::ContentFilter => "content_filter",
345            FinishReason::Other(s) => s,
346        }
347    }
348}
349
350/// One streamed increment.
351#[derive(Clone, Debug, PartialEq)]
352#[non_exhaustive]
353pub enum ChatDelta {
354    /// Visible answer text.
355    Text(String),
356    /// Reasoning / thinking text.
357    Reasoning(String),
358    /// Fragment of a tool call. Fragments sharing `index` belong to the same call;
359    /// `id` and `name` usually arrive on the first fragment only.
360    ToolCall {
361        index: usize,
362        id: Option<String>,
363        name: Option<String>,
364        arguments: String,
365    },
366    /// Cumulative usage snapshot; the last one wins.
367    Usage(Usage),
368    Finish(FinishReason),
369    /// Opaque provider state for the assistant message; the last one wins.
370    ProviderState(serde_json::Value),
371    /// Something the provider adapter changed or dropped while translating the
372    /// request (e.g. unsupported JSON Schema keywords). Surfaced in node metadata.
373    Warning(String),
374    /// The call failed over: the model that answers and the ones left before
375    /// it (first delta of a [`crate::failover::FailoverModel`] stream).
376    Failover(crate::failover::FailoverReport),
377}
378
379/// Stream of deltas returned by [`ChatModel::chat`].
380pub type ChatStream = Pin<Box<dyn Stream<Item = Result<ChatDelta, LlmError>> + Send>>;
381
382/// A chat-capable model endpoint.
383pub trait ChatModel: Send + Sync + fmt::Debug {
384    /// Start a streaming chat completion.
385    fn chat(&self, request: ChatRequest) -> BoxFuture<'_, Result<ChatStream, LlmError>>;
386
387    /// The output limit this model sends when a request sets none (a
388    /// providers file's `defaults.max_tokens`), so a node can tell whether the
389    /// run's budget or this default limits its call.
390    fn default_max_tokens(&self) -> Option<u32> {
391        None
392    }
393}
394
395/// A fully collected response.
396#[derive(Clone, Debug, Default, PartialEq)]
397pub struct ChatResponse {
398    pub text: String,
399    pub reasoning: String,
400    pub tool_calls: Vec<ToolCall>,
401    pub usage: Usage,
402    pub finish_reason: Option<FinishReason>,
403    pub provider_state: Option<serde_json::Value>,
404    /// Adapter warnings (see [`ChatDelta::Warning`]).
405    pub warnings: Vec<String>,
406    /// Set when a fallback model answered (see [`ChatDelta::Failover`]).
407    pub failover: Option<crate::failover::FailoverReport>,
408}
409
410impl ChatResponse {
411    /// The assistant message to append to the conversation.
412    pub fn to_message(&self) -> Message {
413        let content =
414            if self.text.is_empty() { Vec::new() } else { vec![ContentPart::Text { text: self.text.clone() }] };
415        Message {
416            role: Role::Assistant,
417            content,
418            tool_calls: self.tool_calls.clone(),
419            tool_call_id: None,
420            provider_state: self.provider_state.clone(),
421        }
422    }
423}
424
425#[derive(Default)]
426struct PartialCall {
427    id: Option<String>,
428    name: String,
429    arguments: String,
430}
431
432/// Collect a delta stream. `on_delta` receives every delta as it arrives, by
433/// value, after it has been added to the response (used for streaming chunks to
434/// the run's event stream): a text delta can become a chunk without copying.
435///
436/// Tool-call fragments are grouped by their `index`, so interleaved parallel
437/// calls are assembled correctly. A call that has an id or arguments but never
438/// received a name is a decode error rather than being dropped.
439///
440/// Detecting a truncated stream is the transport's job: the built-in providers
441/// fail with a retryable [`LlmError::Network`] when the connection closes
442/// before the provider's end-of-stream marker.
443///
444/// ```
445/// # use graphrt_llm::{ChatDelta, ChatStream, collect};
446/// # let runtime = tokio::runtime::Builder::new_current_thread().build()?;
447/// # runtime.block_on(async {
448/// let stream: ChatStream =
449///     Box::pin(futures::stream::iter(["Hel", "lo"].map(|t| Ok(ChatDelta::Text(t.into())))));
450/// let mut chunks = Vec::new();
451/// let response = collect(stream, |delta| {
452///     if let ChatDelta::Text(text) = delta {
453///         chunks.push(text); // moved, not copied
454///     }
455/// })
456/// .await?;
457/// assert_eq!((response.text.as_str(), chunks.len()), ("Hello", 2));
458/// # Ok::<(), graphrt_llm::LlmError>(())
459/// # })?;
460/// # Ok::<(), Box<dyn std::error::Error>>(())
461/// ```
462pub async fn collect(mut stream: ChatStream, mut on_delta: impl FnMut(ChatDelta)) -> Result<ChatResponse, LlmError> {
463    let mut response = ChatResponse::default();
464    let mut calls: BTreeMap<usize, PartialCall> = BTreeMap::new();
465    while let Some(delta) = stream.next().await {
466        let delta = delta?;
467        // Text is copied into the response and the delta handed on; the rare
468        // non-text deltas are cloned instead.
469        match &delta {
470            ChatDelta::Text(t) => response.text.push_str(t),
471            ChatDelta::Reasoning(t) => response.reasoning.push_str(t),
472            ChatDelta::ToolCall { index, id, name, arguments } => {
473                let call = calls.entry(*index).or_default();
474                if let Some(id) = id.as_ref().filter(|s| !s.is_empty()) {
475                    call.id = Some(id.clone());
476                }
477                if let Some(name) = name.as_ref().filter(|s| !s.is_empty()) {
478                    call.name.clone_from(name);
479                }
480                call.arguments.push_str(arguments);
481            }
482            ChatDelta::Usage(u) => response.usage = *u,
483            ChatDelta::Finish(r) => response.finish_reason = Some(r.clone()),
484            ChatDelta::ProviderState(s) => response.provider_state = Some(s.clone()),
485            ChatDelta::Warning(w) => response.warnings.push(w.clone()),
486            ChatDelta::Failover(report) => response.failover = Some(report.clone()),
487        }
488        on_delta(delta);
489    }
490    let mut tool_calls = Vec::with_capacity(calls.len());
491    for (index, call) in calls {
492        if call.name.is_empty() {
493            if call.id.is_none() && call.arguments.trim().is_empty() {
494                // An empty fragment carries no information; nothing is lost.
495                continue;
496            }
497            return Err(LlmError::Decode(format!("tool call #{index} has arguments or an id but no name")));
498        }
499        tool_calls.push(ToolCall {
500            id: call.id.unwrap_or_else(|| format!("call_{index}")),
501            name: call.name,
502            arguments: call.arguments,
503        });
504    }
505    response.tool_calls = tool_calls;
506    if response.usage.total_tokens == 0 {
507        response.usage.total_tokens = response.usage.prompt_tokens.saturating_add(response.usage.completion_tokens);
508    }
509    Ok(response)
510}
511
512#[cfg(test)]
513mod tests {
514    use super::*;
515
516    #[cfg(feature = "replay")]
517    #[test]
518    fn the_budget_left_never_changes_which_recording_is_replayed() {
519        let request = ChatRequest::new("m", vec![Message::user("hi")]);
520        let mut capped = request.clone();
521        capped.budget_max_tokens = Some(300);
522        assert_eq!(crate::replay::cassette_key(&request).ok(), crate::replay::cassette_key(&capped).ok());
523    }
524
525    #[test]
526    fn the_budget_lowers_an_output_limit_and_never_raises_one() {
527        let mut request = ChatRequest::new("m", Vec::new());
528        assert_eq!(request.output_limit(), None);
529        request.budget_max_tokens = Some(300);
530        assert_eq!(request.output_limit(), Some(300));
531        // A limit of the node or of the providers file's defaults (filled into `max_tokens`) stays when lower.
532        request.max_tokens = Some(100);
533        assert_eq!(request.output_limit(), Some(100));
534        request.max_tokens = Some(1024);
535        assert_eq!(request.output_limit(), Some(300));
536    }
537
538    fn stream(deltas: Vec<ChatDelta>) -> ChatStream {
539        Box::pin(futures::stream::iter(deltas.into_iter().map(Ok)))
540    }
541
542    #[tokio::test]
543    async fn interleaved_parallel_tool_calls_assemble_by_index() {
544        let deltas = vec![
545            ChatDelta::ToolCall {
546                index: 0,
547                id: Some("a".into()),
548                name: Some("search".into()),
549                arguments: "{\"q\":".into(),
550            },
551            ChatDelta::ToolCall {
552                index: 1,
553                id: Some("b".into()),
554                name: Some("fetch".into()),
555                arguments: "{\"url\":".into(),
556            },
557            ChatDelta::ToolCall { index: 0, id: None, name: None, arguments: "\"rust\"}".into() },
558            ChatDelta::ToolCall { index: 1, id: None, name: None, arguments: "\"x\"}".into() },
559            ChatDelta::Usage(Usage { prompt_tokens: 3, completion_tokens: 4, total_tokens: 0 }),
560            ChatDelta::Finish(FinishReason::ToolCalls),
561        ];
562        let r = collect(stream(deltas), |_| {}).await.unwrap();
563        assert_eq!(r.tool_calls.len(), 2);
564        assert_eq!(r.tool_calls[0].arguments, "{\"q\":\"rust\"}");
565        assert_eq!(r.tool_calls[1].id, "b");
566        assert_eq!(r.tool_calls[1].arguments_json().unwrap()["url"], "x");
567        assert_eq!(r.usage.total_tokens, 7);
568        assert_eq!(r.finish_reason, Some(FinishReason::ToolCalls));
569    }
570
571    #[tokio::test]
572    async fn nameless_tool_call_is_an_error() {
573        let deltas = vec![ChatDelta::ToolCall { index: 0, id: Some("a".into()), name: None, arguments: "{}".into() }];
574        let err = collect(stream(deltas), |_| {}).await.unwrap_err();
575        assert!(matches!(err, LlmError::Decode(_)), "{err:?}");
576        // An empty fragment is harmless.
577        let deltas = vec![ChatDelta::ToolCall { index: 0, id: None, name: None, arguments: String::new() }];
578        assert!(collect(stream(deltas), |_| {}).await.unwrap().tool_calls.is_empty());
579    }
580
581    #[test]
582    fn arguments_json_rejects_malformed_input() {
583        let call = |args: &str| ToolCall { id: "1".into(), name: "t".into(), arguments: args.into() };
584        assert!(call("").arguments_json().unwrap().is_empty());
585        assert_eq!(call("{\"a\":1}").arguments_json().unwrap()["a"], 1);
586        assert!(call("{\"a\":").arguments_json().is_err());
587        let err = call("[1]").arguments_json().unwrap_err();
588        assert!(err.to_string().contains("an array"), "{err}");
589    }
590
591    #[test]
592    fn reserved_extra_keys_are_rejected() {
593        let req = ChatRequest::new("m", vec![]).with_extra("stream", serde_json::json!(false));
594        assert!(matches!(check_extra(&req), Err(LlmError::Config(_))));
595        let req = ChatRequest::new("m", vec![]).with_extra("seed", serde_json::json!(1)).with_temperature(0.1);
596        assert!(check_extra(&req).is_ok());
597        assert_eq!(req.temperature, Some(0.1));
598    }
599
600    #[cfg(feature = "openai")]
601    #[test]
602    fn tool_messages_with_images() {
603        let m = Message::tool_with_images("c1", "shot", ["data:image/png;base64,AAAA".to_owned()]);
604        assert_eq!(m.text(), "shot");
605        assert_eq!(m.images().count(), 1);
606        assert_eq!(tool_text_with_image_note(&m), "shot\n[1 image attached after the tool results]");
607        let m = Message::tool_with_images("c1", "", vec!["https://x/a.png".to_owned(); 2]);
608        assert_eq!(tool_text_with_image_note(&m), "[2 images attached after the tool results]");
609        assert_eq!(tool_text_with_image_note(&Message::tool("c1", "plain")), "plain");
610        assert_eq!(tool_images_intro(Some("screenshot"), "c1"), "Images returned by tool `screenshot` (call c1):");
611    }
612
613    #[tokio::test]
614    async fn text_and_reasoning_accumulate() {
615        let deltas =
616            vec![ChatDelta::Reasoning("hm".into()), ChatDelta::Text("he".into()), ChatDelta::Text("llo".into())];
617        let mut seen = 0;
618        let r = collect(stream(deltas), |_| seen += 1).await.unwrap();
619        assert_eq!(seen, 3);
620        assert_eq!(r.text, "hello");
621        assert_eq!(r.reasoning, "hm");
622        assert!(r.tool_calls.is_empty());
623    }
624}