trusty_code/llm/response.rs
1//! Response-side wire types for the OpenRouter / OpenAI chat-completions API.
2//!
3//! Why: Keeping `AssistantMessage`, `ChatChoice`, and `ChatResponse` in their
4//! own module separates the deserialisation surface from request construction
5//! and makes response-handling logic easy to find and test.
6//! What: Defines the response hierarchy returned by `POST /v1/chat/completions`
7//! and helper methods on `ChatResponse` for accessing common fields.
8//! Test: `chat_response_deserialises_fixture`, `tool_call_deserialises_from_fixture`,
9//! `chat_response_first_text_content`, `chat_response_first_tool_calls`,
10//! `chat_response_usage_into_token_usage`.
11
12use serde::{Deserialize, Serialize};
13
14use crate::perf::TokenUsage;
15
16use super::request::ToolCall;
17use super::usage::UsageBlock;
18
19/// The assistant message within a choice.
20///
21/// Why: Mirrors `ChatMessage` but uses explicit struct rather than re-using the
22/// request type to keep request/response paths cleanly separated and avoid
23/// accidental mis-serialisation. `Serialize` (#2264) lets the debug-capture
24/// transcript (`llm::debug_capture`) dump the FULL response — including
25/// tool-call arguments, not just names — verbatim to JSONL.
26/// What: `content` is the text (or `None` for tool-only turns); `tool_calls`
27/// carries any function invocations.
28/// Test: `assistant_message_text_and_tool_calls`.
29#[derive(Debug, Clone, Serialize, Deserialize)]
30pub struct AssistantMessage {
31 /// Text content; `None` when the turn consists solely of tool calls.
32 pub content: Option<String>,
33
34 /// Tool calls emitted this turn.
35 #[serde(default)]
36 pub tool_calls: Vec<ToolCall>,
37}
38
39/// One choice in the model response.
40///
41/// Why: The API returns a `choices` array (allowing `n > 1`); we always request
42/// a single choice but the struct must match the wire schema.
43/// What: `message` holds the assistant turn (text and/or tool calls);
44/// `finish_reason` carries the stop condition.
45/// Test: `chat_response_deserialises_fixture`.
46#[derive(Debug, Clone, Serialize, Deserialize)]
47pub struct ChatChoice {
48 /// The assistant message produced for this choice.
49 pub message: AssistantMessage,
50
51 /// Why the model stopped: `"stop"`, `"tool_calls"`, `"length"`, `"content_filter"`.
52 pub finish_reason: Option<String>,
53}
54
55/// The top-level response from `POST /v1/chat/completions`.
56///
57/// Why: Wraps the `choices` array and `usage` block so callers receive a single
58/// typed value from `LlmClient::chat`.
59/// What: `id` is the response ID; `choices` contains the generated turns;
60/// `usage` carries token accounting. `model` (#1475 bug 2) is the RESOLVED
61/// model slug the provider actually served the request with — OpenRouter
62/// (and the underlying OpenAI-compatible API) echoes this at the top level
63/// of every response, which can differ from the request's `model` field
64/// when routing/fallback resolves to a concrete backing model (e.g. an
65/// `:auto` or multi-model routing slug). `#[serde(default)]` so fixtures
66/// and mocks that omit it still deserialise — see
67/// [`Self::resolved_model`] for the fallback this enables.
68/// Test: `chat_response_deserialises_fixture`,
69/// `resolved_model_prefers_response_model_over_requested`,
70/// `resolved_model_falls_back_to_requested_when_absent`.
71#[derive(Debug, Clone, Serialize, Deserialize)]
72pub struct ChatResponse {
73 /// Opaque response identifier from the provider.
74 pub id: String,
75
76 /// The resolved model slug the provider actually used (#1475 bug 2).
77 /// Empty when the response omits it (older fixtures, some mocks) —
78 /// callers should use [`Self::resolved_model`] rather than this field
79 /// directly.
80 #[serde(default)]
81 pub model: String,
82
83 /// Generated choices (one per `n`; we always request `n = 1`).
84 pub choices: Vec<ChatChoice>,
85
86 /// Token accounting for this request.
87 #[serde(default)]
88 pub usage: UsageBlock,
89}
90
91impl ChatResponse {
92 /// Extract the first choice's text content, if any.
93 ///
94 /// Why: The vast majority of calls want the assistant's text response; this
95 /// convenience method avoids repetitive indexing at every call site.
96 /// What: Returns `choices[0].message.content.clone()` or `None` when the
97 /// response has no choices or the content is absent.
98 /// Test: `chat_response_first_text_content`.
99 pub fn first_text(&self) -> Option<String> {
100 self.choices.first()?.message.content.clone()
101 }
102
103 /// Extract the first choice's tool calls.
104 ///
105 /// Why: Tool-call workflows need quick access to the emitted calls without
106 /// indexing into nested fields each time.
107 /// What: Returns a reference to `choices[0].message.tool_calls`, or an empty
108 /// slice when there are no choices.
109 /// Test: `chat_response_first_tool_calls`.
110 pub fn first_tool_calls(&self) -> &[ToolCall] {
111 self.choices
112 .first()
113 .map(|c| c.message.tool_calls.as_slice())
114 .unwrap_or(&[])
115 }
116
117 /// Extract the finish reason from the first choice.
118 ///
119 /// Why: Callers need the stop condition to decide whether to continue the
120 /// tool-call loop or surface the response.
121 /// What: Returns `choices[0].finish_reason.as_deref()` or `None`.
122 /// Test: `chat_response_deserialises_fixture`.
123 pub fn finish_reason(&self) -> Option<&str> {
124 self.choices.first()?.finish_reason.as_deref()
125 }
126
127 /// Convert the response's `usage` block into `TokenUsage`.
128 ///
129 /// Why: `PerfCollector::record_phase` accepts `&TokenUsage`; this method
130 /// keeps the conversion at one place.
131 /// What: Delegates to `UsageBlock::into_token_usage`.
132 /// Test: `chat_response_usage_into_token_usage`.
133 pub fn token_usage(self) -> TokenUsage {
134 self.usage.into_token_usage()
135 }
136
137 /// The model slug to attribute this turn to for recording/pricing
138 /// (#1475 bug 2): the RESOLVED model the provider reports, falling back
139 /// to the originally `requested` slug when the response didn't carry
140 /// one.
141 ///
142 /// Why: `run_task::recorder::RecordingLlmClient` and any future
143 /// transcript recorder must record what the provider actually ran, not
144 /// merely what was asked for — a routing/fallback slug (`:auto`, a
145 /// multi-model alias) can resolve to a different concrete model.
146 /// What: Returns `&self.model` when non-empty, else `requested`.
147 /// Test: `resolved_model_prefers_response_model_over_requested`,
148 /// `resolved_model_falls_back_to_requested_when_absent`.
149 pub fn resolved_model<'a>(&'a self, requested: &'a str) -> &'a str {
150 if self.model.is_empty() {
151 requested
152 } else {
153 &self.model
154 }
155 }
156}
157
158// ── Tests ─────────────────────────────────────────────────────────────────────
159
160#[cfg(test)]
161mod tests {
162 use super::*;
163
164 /// A representative API response fixture deserialises correctly.
165 ///
166 /// Why: Ensures the struct layout matches the real OpenRouter wire format.
167 /// What: Parse a JSON string modelled on an actual response; assert all
168 /// top-level fields are populated.
169 /// Test: this test.
170 #[test]
171 fn chat_response_deserialises_fixture() {
172 let fixture = r#"{
173 "id": "gen-abc123",
174 "choices": [
175 {
176 "message": {
177 "role": "assistant",
178 "content": "Hello, world!",
179 "tool_calls": []
180 },
181 "finish_reason": "stop"
182 }
183 ],
184 "usage": {
185 "prompt_tokens": 10,
186 "completion_tokens": 4,
187 "total_tokens": 14
188 }
189 }"#;
190 let resp: ChatResponse = serde_json::from_str(fixture).expect("deserialise fixture");
191 assert_eq!(resp.id, "gen-abc123");
192 assert_eq!(resp.first_text().as_deref(), Some("Hello, world!"));
193 assert_eq!(resp.finish_reason(), Some("stop"));
194 assert!(resp.first_tool_calls().is_empty());
195 }
196
197 /// A response with a tool call deserialises `tool_calls`.
198 ///
199 /// Why: Tool-calling workflow depends on correctly parsing `tool_calls` from
200 /// the response.
201 /// What: Parse a fixture with `tool_calls` populated; assert name and args.
202 /// Test: this test.
203 #[test]
204 fn tool_call_deserialises_from_fixture() {
205 let fixture = r#"{
206 "id": "gen-xyz",
207 "choices": [
208 {
209 "message": {
210 "role": "assistant",
211 "content": null,
212 "tool_calls": [
213 {
214 "id": "call_001",
215 "type": "function",
216 "function": {
217 "name": "get_weather",
218 "arguments": "{\"location\":\"Seattle\"}"
219 }
220 }
221 ]
222 },
223 "finish_reason": "tool_calls"
224 }
225 ],
226 "usage": {
227 "prompt_tokens": 25,
228 "completion_tokens": 15,
229 "total_tokens": 40
230 }
231 }"#;
232 let resp: ChatResponse = serde_json::from_str(fixture).expect("deserialise");
233 assert!(resp.first_text().is_none());
234 let calls = resp.first_tool_calls();
235 assert_eq!(calls.len(), 1);
236 assert_eq!(calls[0].id, "call_001");
237 assert_eq!(calls[0].function.name, "get_weather");
238 assert_eq!(resp.finish_reason(), Some("tool_calls"));
239 }
240
241 /// `ChatResponse::token_usage` delegates to `UsageBlock::into_token_usage`.
242 ///
243 /// Why: Callers use `response.token_usage()` rather than digging into
244 /// `response.usage`; this test ensures the method works end-to-end.
245 /// What: Build a full response fixture, call `token_usage()`, assert counts.
246 /// Test: this test.
247 #[test]
248 fn chat_response_usage_into_token_usage() {
249 let fixture = r#"{
250 "id": "gen-zzz",
251 "choices": [{"message": {"role": "assistant", "content": "ok"}, "finish_reason": "stop"}],
252 "usage": {"prompt_tokens": 8, "completion_tokens": 3, "total_tokens": 11,
253 "cache_read_input_tokens": 5, "cache_creation_input_tokens": 2}
254 }"#;
255 let resp: ChatResponse = serde_json::from_str(fixture).expect("deserialise");
256 let usage = resp.token_usage();
257 assert_eq!(usage.prompt_tokens, 8);
258 assert_eq!(usage.completion_tokens, 3);
259 assert_eq!(usage.cache_read_tokens, 5);
260 assert_eq!(usage.cache_creation_tokens, 2);
261 }
262
263 /// `ChatResponse::first_text` returns `None` for an empty choices list.
264 ///
265 /// Why: Callers must handle missing text gracefully; validate the `None`
266 /// path without panicking.
267 /// What: Deserialise a response with an empty `choices` array, assert
268 /// `first_text()` is `None`.
269 /// Test: this test.
270 #[test]
271 fn chat_response_first_text_content_empty_choices() {
272 let fixture = r#"{"id":"x","choices":[],"usage":{}}"#;
273 let resp: ChatResponse = serde_json::from_str(fixture).expect("deserialise");
274 assert!(resp.first_text().is_none());
275 assert!(resp.first_tool_calls().is_empty());
276 assert!(resp.finish_reason().is_none());
277 }
278
279 /// `resolved_model` prefers the response's own `model` field when
280 /// present, even if it differs from what was requested (#1475 bug 2).
281 #[test]
282 fn resolved_model_prefers_response_model_over_requested() {
283 let fixture =
284 r#"{"id":"x","model":"openai/gpt-4o-mini-2024-07-18","choices":[],"usage":{}}"#;
285 let resp: ChatResponse = serde_json::from_str(fixture).expect("deserialise");
286 assert_eq!(
287 resp.resolved_model("openai/gpt-4o-mini"),
288 "openai/gpt-4o-mini-2024-07-18"
289 );
290 }
291
292 /// `resolved_model` falls back to the requested slug when the response
293 /// omits `model` (older fixtures, some mocks) (#1475 bug 2).
294 #[test]
295 fn resolved_model_falls_back_to_requested_when_absent() {
296 let fixture = r#"{"id":"x","choices":[],"usage":{}}"#;
297 let resp: ChatResponse = serde_json::from_str(fixture).expect("deserialise");
298 assert_eq!(
299 resp.resolved_model("openai/gpt-4o-mini"),
300 "openai/gpt-4o-mini"
301 );
302 }
303}