trusty_code/llm/request.rs
1//! Request-side wire types for the OpenRouter / OpenAI chat-completions API.
2//!
3//! Why: Keeping tool definitions, tool-call types, and the request body in one
4//! module lets the serialisation surface evolve without touching response or
5//! message logic.
6//! What: Defines `ToolCall`, `FunctionCall`, `ToolDefinition`,
7//! `FunctionDefinition`, and `ChatRequest` — everything needed to construct
8//! and serialise a `POST /v1/chat/completions` payload.
9//! Test: `chat_request_serialises_required_fields`,
10//! `chat_request_with_tools_serialises`, `tool_definition_serialises`,
11//! `function_definition_round_trip`.
12
13use serde::{Deserialize, Serialize};
14
15use super::message::ChatMessage;
16
17// ── Prompt-caching types (#2156) ────────────────────────────────────────────────
18
19/// An Anthropic-style ephemeral prompt-cache breakpoint.
20///
21/// Why: Anthropic (and OpenRouter's passthrough for `anthropic/*` slugs) prices
22/// everything up to and including a `cache_control` marker as one cached
23/// prefix — a cache HIT on a later turn bills at roughly 0.1x the normal input
24/// price instead of re-billing the full prefix. `agent_loop::build_request`
25/// places this marker on the byte-stable tools+system-prompt prefix it
26/// resends every turn, which is the make-or-break cost lever for #2156.
27/// What: `kind` is always `"ephemeral"` — the only breakpoint type Anthropic
28/// currently supports. Serialises to `{"type":"ephemeral"}`.
29/// Test: `cache_control_ephemeral_serialises_expected_shape`.
30#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
31pub struct CacheControl {
32 /// Always `"ephemeral"`.
33 #[serde(rename = "type")]
34 pub kind: String,
35}
36
37impl CacheControl {
38 /// Construct the (only) ephemeral cache-breakpoint marker.
39 ///
40 /// Why: Every call site wants the identical `{"type":"ephemeral"}` value;
41 /// naming the constructor after the wire concept avoids a stringly-typed
42 /// literal at each use site.
43 /// What: Returns `CacheControl { kind: "ephemeral".into() }`.
44 /// Test: `cache_control_ephemeral_serialises_expected_shape`.
45 pub fn ephemeral() -> Self {
46 Self {
47 kind: "ephemeral".into(),
48 }
49 }
50}
51
52/// OpenRouter's request-side "return detailed usage" directive (response-side
53/// cache-usage fix).
54///
55/// Why: Requesting detailed usage accounting is what makes OpenRouter return
56/// its authoritative, already cache-discount-aware `usage.cost` field (and
57/// the nested `prompt_tokens_details` cache counters) on the response —
58/// without it, only the bare prompt/completion/total counts are guaranteed.
59/// Sent only for the OpenRouter provider (`agent_loop::build_request`); other
60/// providers (direct/Bedrock) never see this field.
61/// What: `include: true` serialises to the wire shape `{"include":true}`
62/// under the request's top-level `usage` key.
63/// Test: `request_usage_config_detailed_serialises_expected_shape`,
64/// `chat_request_with_detailed_usage_serialises`.
65#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
66pub struct RequestUsageConfig {
67 /// Whether to request detailed (cost + cache-breakdown) usage accounting.
68 pub include: bool,
69}
70
71impl RequestUsageConfig {
72 /// Construct the "include detailed usage" directive.
73 ///
74 /// Why: Every call site wants the identical `{"include":true}` value;
75 /// naming the constructor after the wire concept avoids a bare `true`
76 /// literal scattered at call sites.
77 /// What: Returns `RequestUsageConfig { include: true }`.
78 /// Test: `request_usage_config_detailed_serialises_expected_shape`.
79 pub fn detailed() -> Self {
80 Self { include: true }
81 }
82}
83
84// ── Tool-calling types ─────────────────────────────────────────────────────────
85
86/// A tool call emitted by the model.
87///
88/// Why: The model may decide to invoke one or more functions before producing a
89/// final text response; callers must handle these before the conversation can
90/// continue.
91/// What: `id` is the opaque call identifier used when submitting the result
92/// back; `r#type` is always `"function"`; `function` carries the name and
93/// JSON-encoded arguments.
94/// Test: `tool_call_deserialises_from_fixture` (in `response.rs` tests).
95#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
96pub struct ToolCall {
97 /// Unique call identifier; echoed in the subsequent `tool` result message.
98 pub id: String,
99
100 /// Always `"function"` for the current OpenAI schema.
101 #[serde(rename = "type")]
102 pub kind: String,
103
104 /// The function being called.
105 pub function: FunctionCall,
106}
107
108/// The function name and arguments within a tool call.
109///
110/// Why: Separating this from `ToolCall` keeps the struct layout consistent with
111/// the wire format (OpenAI wraps function details in a nested object).
112/// What: `name` is the registered function name; `arguments` is a JSON string
113/// (not a parsed value) exactly as emitted by the model.
114/// Test: `tool_call_deserialises_from_fixture` (in `response.rs` tests).
115#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
116pub struct FunctionCall {
117 /// Registered function name.
118 pub name: String,
119
120 /// JSON-encoded argument object; parse with `serde_json::from_str` at the
121 /// call site.
122 pub arguments: String,
123}
124
125/// A tool definition submitted with the request.
126///
127/// Why: Providing tool definitions tells the model which functions are available
128/// so it can decide when and how to call them.
129/// What: `r#type` is always `"function"`; `function` carries the JSON Schema
130/// describing the callable function.
131/// Test: `tool_definition_serialises`.
132#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
133pub struct ToolDefinition {
134 /// Always `"function"`.
135 #[serde(rename = "type")]
136 pub kind: String,
137
138 /// The function schema.
139 pub function: FunctionDefinition,
140}
141
142impl ToolDefinition {
143 /// Construct a function-type tool definition.
144 ///
145 /// Why: All current OpenAI-compatible tools are function tools; this
146 /// constructor bakes in that invariant.
147 /// What: Sets `kind = "function"` and wraps the provided `FunctionDefinition`.
148 /// Test: `tool_definition_serialises`.
149 pub fn function(function: FunctionDefinition) -> Self {
150 Self {
151 kind: "function".into(),
152 function,
153 }
154 }
155}
156
157/// JSON Schema description of a callable function.
158///
159/// Why: The model needs the name, a description, and parameter schema to decide
160/// when and how to call the function correctly.
161/// What: `name` is the call target; `description` guides model selection;
162/// `parameters` is a raw `serde_json::Value` holding the JSON Schema object
163/// for flexibility (different tools may use different schema shapes).
164/// Test: `function_definition_round_trip`.
165#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
166pub struct FunctionDefinition {
167 /// The function name as registered with the model.
168 pub name: String,
169
170 /// Human-readable description guiding the model's decision to call it.
171 #[serde(skip_serializing_if = "Option::is_none")]
172 pub description: Option<String>,
173
174 /// JSON Schema object describing the function's parameter shape.
175 #[serde(skip_serializing_if = "Option::is_none")]
176 pub parameters: Option<serde_json::Value>,
177
178 /// Prompt-cache breakpoint (#2156). When set, serialises as a sibling
179 /// `"cache_control":{"type":"ephemeral"}` field alongside this function's
180 /// schema — the shape `block/goose`'s (verified, production) OpenRouter
181 /// provider uses to cache Claude tool definitions via the OpenAI-compat
182 /// endpoint. `agent_loop::build_request` sets this on the LAST tool
183 /// definition only: Anthropic caches everything up to and including a
184 /// breakpoint, so marking just the last tool caches the entire
185 /// (byte-stable) tools array as a single prefix.
186 #[serde(skip_serializing_if = "Option::is_none")]
187 pub cache_control: Option<CacheControl>,
188}
189
190// ── Request type ───────────────────────────────────────────────────────────────
191
192/// The full request body for `POST /v1/chat/completions`.
193///
194/// Why: A dedicated struct keeps the serialisation surface explicit and avoids
195/// ad-hoc `serde_json::json!` construction scattered across call sites.
196/// What: All standard OpenAI chat-completions fields; optional fields use
197/// `skip_serializing_if` so the wire payload stays minimal.
198/// Test: `chat_request_serialises_required_fields`,
199/// `chat_request_with_tools_serialises`.
200#[derive(Debug, Clone, Serialize, Deserialize)]
201pub struct ChatRequest {
202 /// OpenRouter / OpenAI model slug, e.g. `"anthropic/claude-sonnet-4-5"`.
203 pub model: String,
204
205 /// Conversation history, including the new user turn.
206 pub messages: Vec<ChatMessage>,
207
208 /// Sampling temperature in `[0.0, 2.0]`.
209 #[serde(skip_serializing_if = "Option::is_none")]
210 pub temperature: Option<f32>,
211
212 /// Maximum tokens to generate.
213 #[serde(skip_serializing_if = "Option::is_none")]
214 pub max_tokens: Option<u32>,
215
216 /// Tools the model may call.
217 #[serde(skip_serializing_if = "Option::is_none")]
218 pub tools: Option<Vec<ToolDefinition>>,
219
220 /// Tool-choice policy: `"none"`, `"auto"`, `"required"`, or a specific
221 /// function selector.
222 #[serde(skip_serializing_if = "Option::is_none")]
223 pub tool_choice: Option<serde_json::Value>,
224
225 /// Request OpenRouter's detailed usage accounting (response-side
226 /// cache-usage fix). `Some(RequestUsageConfig::detailed())` for the
227 /// OpenRouter provider; `None` (omitted from the wire payload) for every
228 /// other provider/path.
229 #[serde(skip_serializing_if = "Option::is_none")]
230 pub usage: Option<RequestUsageConfig>,
231}
232
233// ── Tests ─────────────────────────────────────────────────────────────────────
234
235#[cfg(test)]
236mod tests {
237 use super::*;
238
239 /// Minimal `ChatRequest` serialises required fields only.
240 ///
241 /// Why: Verify that optional fields with `None` values are omitted from the
242 /// JSON payload, keeping requests lean.
243 /// What: Build a minimal request, serialise it, check required fields present
244 /// and optional fields absent.
245 /// Test: this test.
246 #[test]
247 fn chat_request_serialises_required_fields() {
248 let req = ChatRequest {
249 model: "anthropic/claude-haiku-4-5".into(),
250 messages: vec![ChatMessage::user("hello")],
251 temperature: None,
252 max_tokens: None,
253 tools: None,
254 tool_choice: None,
255 usage: None,
256 };
257 let v: serde_json::Value = serde_json::to_value(&req).expect("serialise");
258 assert_eq!(v["model"], "anthropic/claude-haiku-4-5");
259 assert_eq!(v["messages"][0]["role"], "user");
260 assert_eq!(v["messages"][0]["content"], "hello");
261 assert!(v.get("temperature").is_none() || v["temperature"].is_null());
262 assert!(v.get("tools").is_none() || v["tools"].is_null());
263 assert!(
264 v.get("usage").is_none() || v["usage"].is_null(),
265 "usage must be omitted when unset"
266 );
267 }
268
269 /// `ChatRequest` with tools serialises the `tools` and `tool_choice` fields.
270 ///
271 /// Why: Tool-calling requests must include the tool schema; validate that
272 /// the serialised payload matches the OpenAI wire format.
273 /// What: Build a request with one `ToolDefinition`, serialise, assert schema
274 /// structure.
275 /// Test: this test.
276 #[test]
277 fn chat_request_with_tools_serialises() {
278 let tool = ToolDefinition::function(FunctionDefinition {
279 name: "get_weather".into(),
280 description: Some("Returns weather data".into()),
281 parameters: Some(serde_json::json!({
282 "type": "object",
283 "properties": { "location": { "type": "string" } },
284 "required": ["location"]
285 })),
286 cache_control: None,
287 });
288 let req = ChatRequest {
289 model: "openai/gpt-4o-mini".into(),
290 messages: vec![ChatMessage::user("What's the weather?")],
291 temperature: Some(0.0),
292 max_tokens: Some(256),
293 tools: Some(vec![tool]),
294 tool_choice: Some(serde_json::json!("auto")),
295 usage: None,
296 };
297 let v: serde_json::Value = serde_json::to_value(&req).expect("serialise");
298 assert_eq!(v["tools"][0]["type"], "function");
299 assert_eq!(v["tools"][0]["function"]["name"], "get_weather");
300 assert_eq!(v["tool_choice"], "auto");
301 assert_eq!(v["temperature"], 0.0_f32);
302 assert_eq!(v["max_tokens"], 256);
303 }
304
305 /// `RequestUsageConfig::detailed` serialises to the exact
306 /// `{"include":true}` shape OpenRouter expects.
307 ///
308 /// Why: A typo (wrong key, wrong value) would silently disable detailed
309 /// usage accounting without any test noticing — the same failure mode
310 /// `cache_control_ephemeral_serialises_expected_shape` guards against.
311 /// What: Serialise `RequestUsageConfig::detailed()`, assert the exact
312 /// object.
313 /// Test: this test.
314 #[test]
315 fn request_usage_config_detailed_serialises_expected_shape() {
316 let v = serde_json::to_value(RequestUsageConfig::detailed()).expect("serialise");
317 assert_eq!(v, serde_json::json!({"include": true}));
318 }
319
320 /// A `ChatRequest` with `usage` set serialises the top-level `"usage"`
321 /// key; a request with `usage: None` omits it entirely (response-side
322 /// cache-usage fix — gated to the OpenRouter provider only).
323 ///
324 /// Why: `agent_loop::build_request` must only attach this directive for
325 /// OpenRouter; verifying both the present and absent cases in one test
326 /// pins the exact wire contract other providers must never see.
327 /// What: Serialise a request with `usage: Some(...)`, assert the field;
328 /// serialise one with `usage: None`, assert it's absent.
329 /// Test: this test.
330 #[test]
331 fn chat_request_with_detailed_usage_serialises() {
332 let with_usage = ChatRequest {
333 model: "anthropic/claude-sonnet-4-5".into(),
334 messages: vec![ChatMessage::user("hi")],
335 temperature: None,
336 max_tokens: None,
337 tools: None,
338 tool_choice: None,
339 usage: Some(RequestUsageConfig::detailed()),
340 };
341 let v: serde_json::Value = serde_json::to_value(&with_usage).expect("serialise");
342 assert_eq!(v["usage"], serde_json::json!({"include": true}));
343
344 let without_usage = ChatRequest {
345 usage: None,
346 ..with_usage
347 };
348 let v: serde_json::Value = serde_json::to_value(&without_usage).expect("serialise");
349 assert!(
350 v.get("usage").is_none() || v["usage"].is_null(),
351 "usage must be omitted when None"
352 );
353 }
354
355 /// `ToolDefinition::function` sets `kind = "function"`.
356 ///
357 /// Why: The wire format requires `type: "function"`; verify the constructor
358 /// bakes in that invariant.
359 /// What: Build via `ToolDefinition::function`, serialise, assert `type` field.
360 /// Test: this test.
361 #[test]
362 fn tool_definition_serialises() {
363 let tool = ToolDefinition::function(FunctionDefinition {
364 name: "ping".into(),
365 description: None,
366 parameters: None,
367 cache_control: None,
368 });
369 let v: serde_json::Value = serde_json::to_value(&tool).expect("serialise");
370 assert_eq!(v["type"], "function");
371 assert_eq!(v["function"]["name"], "ping");
372 assert!(
373 v["function"].get("cache_control").is_none(),
374 "cache_control must be omitted when unset"
375 );
376 }
377
378 /// `FunctionDefinition` round-trips through JSON.
379 ///
380 /// Why: Parameter schemas are `serde_json::Value`; verify the round-trip
381 /// preserves structure.
382 /// What: Build a `FunctionDefinition` with a parameters schema, serialise
383 /// and deserialise, assert fields match.
384 /// Test: this test.
385 #[test]
386 fn function_definition_round_trip() {
387 let params = serde_json::json!({"type": "object", "properties": {}});
388 let def = FunctionDefinition {
389 name: "my_fn".into(),
390 description: Some("does stuff".into()),
391 parameters: Some(params.clone()),
392 cache_control: None,
393 };
394 let serialised = serde_json::to_string(&def).expect("serialise");
395 let de: FunctionDefinition = serde_json::from_str(&serialised).expect("deserialise");
396 assert_eq!(de.name, "my_fn");
397 assert_eq!(de.description.as_deref(), Some("does stuff"));
398 assert_eq!(de.parameters.as_ref(), Some(¶ms));
399 assert!(de.cache_control.is_none());
400 }
401
402 /// `CacheControl::ephemeral` serialises to the exact Anthropic-ephemeral
403 /// shape (#2156).
404 ///
405 /// Why: This is the literal JSON marker OpenRouter's Claude passthrough
406 /// looks for; a typo (wrong key name, wrong value) would silently disable
407 /// caching without any test noticing.
408 /// What: Serialise `CacheControl::ephemeral()`, assert the exact object.
409 /// Test: this test.
410 #[test]
411 fn cache_control_ephemeral_serialises_expected_shape() {
412 let v = serde_json::to_value(CacheControl::ephemeral()).expect("serialise");
413 assert_eq!(v, serde_json::json!({"type": "ephemeral"}));
414 }
415
416 /// A `FunctionDefinition` with `cache_control` set serialises the marker
417 /// nested inside the function object (#2156), matching the shape
418 /// `block/goose`'s verified OpenRouter provider uses.
419 ///
420 /// Why: The breakpoint must land on the tool's `function` object, not on
421 /// the wrapping `ToolDefinition` — placing it at the wrong nesting level
422 /// would mean OpenRouter's OpenAI→Anthropic conversion drops the marker
423 /// entirely and caching silently never activates.
424 /// What: Build a `ToolDefinition` whose `FunctionDefinition.cache_control`
425 /// is `Some`, serialise, assert `tools[0].function.cache_control` matches
426 /// the ephemeral shape.
427 /// Test: this test.
428 #[test]
429 fn function_definition_with_cache_control_serialises_marker() {
430 let tool = ToolDefinition::function(FunctionDefinition {
431 name: "write_file".into(),
432 description: Some("Write a file".into()),
433 parameters: None,
434 cache_control: Some(CacheControl::ephemeral()),
435 });
436 let v: serde_json::Value = serde_json::to_value(&tool).expect("serialise");
437 assert_eq!(
438 v["function"]["cache_control"],
439 serde_json::json!({"type": "ephemeral"})
440 );
441 }
442}