causa_protocol/translation/render_options.rs
1//! Renderer options: the renderer-specific argument each pure renderer takes.
2//!
3//! The renderers in this module tree are pure functions with a fixed argument
4//! list; these values are the one renderer-specific argument they accept. They
5//! live here (translation, transport-free) and are hosted by the matching
6//! gateway configuration in `causa-provider`, which exposes one `with_*`
7//! builder per option next to its existing builders. The configurations keep
8//! `Default`, so the documented defaults hold with no setter call.
9//!
10//! Options are per gateway value, not per request. A host that needs different
11//! behavior for one request holds a second gateway value; the configuration is
12//! cheap to clone and the HTTP client, base URL and media resolver can be
13//! shared, so the cost is one extra value, not a second connection pool.
14//!
15//! These types represent configuration, not context: they are outside the
16//! stable serialized set, and their serialized shape follows the field names
17//! and carries no compatibility promise. Which servers and models support an
18//! option is for the host to decide; an option a server does not support may
19//! be rejected by it or silently ignored.
20
21use serde::{Deserialize, Serialize};
22
23use super::anthropic::INLINE_TOOLS_BETA;
24
25/// Anthropic Messages render options.
26///
27/// Configuration, not context: see the module docs for what the serialized form
28/// promises and who decides support.
29///
30/// Settings of the `thinking` object, including `block_binding`, are not
31/// here: they are part of the object the host sends in
32/// `GenerationOptions::extra_body`.
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
34#[serde(default, deny_unknown_fields)]
35#[non_exhaustive]
36pub struct AnthropicRenderOptions {
37 /// Render tool changes in place (default `false`). `tools` stays at the
38 /// frame's declaration followed by a deferred placeholder tool, and each
39 /// later change renders at its position as a `system` message of
40 /// `tool_removal` and `tool_addition` blocks, so a change keeps the cached
41 /// prefix. The API needs the [`INLINE_TOOLS_BETA`] beta for it (reported by
42 /// [`Self::beta_values`]), which the gateway adds. Off, `tools` carries the
43 /// current tool state and a change rewrites it. Enable only for a server
44 /// known to support it: a server without support may reject the request, or
45 /// ignore the change so the model never sees the added tool.
46 pub native_tool_changes: bool,
47}
48
49impl AnthropicRenderOptions {
50 /// Values for the `anthropic-beta` header required by the enabled options.
51 ///
52 /// A request rendered with these options is only valid when the HTTP
53 /// request carries each returned value. The `causa-provider` gateway adds
54 /// them to its `anthropic-beta` header; a host that sends requests itself
55 /// must add them.
56 pub fn beta_values(&self) -> Vec<&'static str> {
57 let mut values = Vec::new();
58 if self.native_tool_changes {
59 values.push(INLINE_TOOLS_BETA);
60 }
61 values
62 }
63}
64
65/// OpenAI Responses render options.
66///
67/// Configuration, not context: see the module docs for what the serialized form
68/// promises and who decides support.
69///
70/// `Default` sends `include: ["reasoning.encrypted_content"]` and
71/// `store: false`, as Codex and `pi-ai` do: encrypted reasoning is what makes
72/// a reasoning item replayable under `store: false` or zero data retention.
73#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
74#[serde(default, deny_unknown_fields)]
75#[non_exhaustive]
76pub struct ResponsesRenderOptions {
77 /// Send `include: ["reasoning.encrypted_content"]` (default `true`).
78 /// Turning it off leaves the field out entirely, so the response carries
79 /// no encrypted reasoning and a reasoning item cannot be meaningfully
80 /// replayed under `store: false`.
81 pub include_encrypted_reasoning: bool,
82 /// Value rendered as `store`; `None` omits the field (default
83 /// `Some(false)`). The host owns the data-retention choice this
84 /// represents.
85 ///
86 /// When deserializing, a missing key yields the default `Some(false)`,
87 /// while an explicit JSON `null` yields `None` (omits the field).
88 /// Formats without `null`, such as TOML, use `with_store(None)` instead.
89 pub store: Option<bool>,
90 /// Render added tools in place (default `false`). `tools` stays at the
91 /// frame's declaration and each later change renders at its position as
92 /// an `additional_tools` input item, so an addition keeps the cached
93 /// prefix. A frame with a removal or a second definition of one name
94 /// renders as if this were off: `tools` carries the current tool state.
95 /// Enable only for a server known to support it: a server without support
96 /// may reject the request, or ignore the change so the model never sees
97 /// the added tool.
98 pub additional_tools: bool,
99}
100
101impl Default for ResponsesRenderOptions {
102 fn default() -> Self {
103 Self {
104 include_encrypted_reasoning: true,
105 store: Some(false),
106 additional_tools: false,
107 }
108 }
109}
110
111/// OpenAI Chat Completions render options.
112///
113/// Configuration, not context: see the module docs for what the serialized form
114/// promises and who decides support.
115///
116/// `Default` replays sealed `reasoning_content` and writes the output limit
117/// as `max_completion_tokens`.
118#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
119#[serde(default, deny_unknown_fields)]
120#[non_exhaustive]
121pub struct ChatRenderOptions {
122 /// Replay the frame's own-format sealed `reasoning_content` message-level
123 /// items (default `true`). DeepSeek requires `reasoning_content` back on
124 /// every request that carries `tools` and ignores it otherwise; other
125 /// compatible providers differ, which is what this option is for. When it
126 /// is off, the renderer removes the `reasoning_content` key from its own
127 /// sealed items — dropping an item that carries nothing else — and changes
128 /// nothing else. Other sealed message fields still replay.
129 pub replay_reasoning_content: bool,
130 /// The request field that carries `GenerationOptions::max_tokens`
131 /// (default [`ChatMaxTokensField::MaxCompletionTokens`]). Only the chosen
132 /// field is written. A server that does not read the chosen field
133 /// applies no limit and reports no error, so the response can run past
134 /// the host's limit.
135 pub max_tokens_field: ChatMaxTokensField,
136}
137
138impl Default for ChatRenderOptions {
139 fn default() -> Self {
140 Self {
141 replay_reasoning_content: true,
142 max_tokens_field: ChatMaxTokensField::default(),
143 }
144 }
145}
146
147/// The Chat Completions request field that carries the output limit.
148///
149/// Serialized as the wire field name. Exhaustive: the Chat renderer is total
150/// over it, so a new variant is a breaking change.
151#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
152#[serde(rename_all = "snake_case")]
153pub enum ChatMaxTokensField {
154 /// `max_completion_tokens`, the field OpenAI documents. It counts
155 /// reasoning tokens as well as visible output.
156 #[default]
157 MaxCompletionTokens,
158 /// `max_tokens`, the older name, which OpenAI has deprecated and which
159 /// some compatible servers still read in its place.
160 MaxTokens,
161}
162
163impl ChatMaxTokensField {
164 /// The request field name this value writes.
165 pub fn field_name(self) -> &'static str {
166 match self {
167 Self::MaxCompletionTokens => "max_completion_tokens",
168 Self::MaxTokens => "max_tokens",
169 }
170 }
171}
172
173#[cfg(test)]
174mod tests {
175 use super::*;
176
177 fn round_trip<T: Serialize + serde::de::DeserializeOwned + PartialEq + std::fmt::Debug>(
178 value: T,
179 ) {
180 let json = serde_json::to_string(&value).unwrap();
181 let back: T = serde_json::from_str(&json).unwrap();
182 assert_eq!(value, back);
183 }
184
185 #[test]
186 fn empty_json_deserializes_to_default() {
187 let anthropic: AnthropicRenderOptions = serde_json::from_str("{}").unwrap();
188 assert_eq!(anthropic, AnthropicRenderOptions::default());
189
190 let responses: ResponsesRenderOptions = serde_json::from_str("{}").unwrap();
191 assert_eq!(responses, ResponsesRenderOptions::default());
192
193 let chat: ChatRenderOptions = serde_json::from_str("{}").unwrap();
194 assert_eq!(chat, ChatRenderOptions::default());
195 }
196
197 #[test]
198 fn serialize_deserialize_round_trip_is_identity() {
199 round_trip(AnthropicRenderOptions::default());
200 round_trip(AnthropicRenderOptions {
201 native_tool_changes: true,
202 });
203
204 round_trip(ResponsesRenderOptions::default());
205 round_trip(ResponsesRenderOptions {
206 include_encrypted_reasoning: false,
207 store: None,
208 additional_tools: true,
209 });
210 round_trip(ResponsesRenderOptions {
211 include_encrypted_reasoning: true,
212 store: Some(true),
213 additional_tools: false,
214 });
215
216 round_trip(ChatRenderOptions::default());
217 round_trip(ChatRenderOptions {
218 replay_reasoning_content: false,
219 max_tokens_field: ChatMaxTokensField::MaxTokens,
220 });
221 }
222
223 #[test]
224 fn chat_max_tokens_field_uses_the_wire_names() {
225 let chat: ChatRenderOptions =
226 serde_json::from_str(r#"{"max_tokens_field": "max_tokens"}"#).unwrap();
227 assert_eq!(chat.max_tokens_field, ChatMaxTokensField::MaxTokens);
228 assert!(chat.replay_reasoning_content);
229 for field in [
230 ChatMaxTokensField::MaxCompletionTokens,
231 ChatMaxTokensField::MaxTokens,
232 ] {
233 assert_eq!(
234 serde_json::to_value(field).unwrap(),
235 serde_json::Value::from(field.field_name())
236 );
237 }
238
239 let err = serde_json::from_str::<ChatRenderOptions>(
240 r#"{"max_tokens_field": "max_output_tokens"}"#,
241 )
242 .unwrap_err();
243 assert!(
244 err.to_string()
245 .contains("unknown variant `max_output_tokens`")
246 );
247 }
248
249 #[test]
250 fn unknown_field_is_rejected() {
251 let err =
252 serde_json::from_str::<AnthropicRenderOptions>(r#"{"unknown": true}"#).unwrap_err();
253 assert!(err.to_string().contains("unknown field `unknown`"));
254
255 let err = serde_json::from_str::<ResponsesRenderOptions>(r#"{"typo": 123}"#).unwrap_err();
256 assert!(err.to_string().contains("unknown field `typo`"));
257
258 let err =
259 serde_json::from_str::<ChatRenderOptions>(r#"{"unrecognized": false}"#).unwrap_err();
260 assert!(err.to_string().contains("unknown field `unrecognized`"));
261 }
262
263 #[test]
264 fn cross_protocol_field_is_rejected() {
265 let err = serde_json::from_str::<AnthropicRenderOptions>(r#"{"additional_tools": true}"#)
266 .unwrap_err();
267 assert!(err.to_string().contains("unknown field `additional_tools`"));
268
269 let err = serde_json::from_str::<ChatRenderOptions>(r#"{"native_tool_changes": true}"#)
270 .unwrap_err();
271 assert!(
272 err.to_string()
273 .contains("unknown field `native_tool_changes`")
274 );
275
276 let err =
277 serde_json::from_str::<ResponsesRenderOptions>(r#"{"replay_reasoning_content": true}"#)
278 .unwrap_err();
279 assert!(
280 err.to_string()
281 .contains("unknown field `replay_reasoning_content`")
282 );
283 }
284
285 #[test]
286 fn responses_store_null_gives_none_and_missing_gives_some_false() {
287 let missing: ResponsesRenderOptions = serde_json::from_str("{}").unwrap();
288 assert_eq!(missing.store, Some(false));
289
290 let null_store: ResponsesRenderOptions =
291 serde_json::from_str(r#"{"store": null}"#).unwrap();
292 assert_eq!(null_store.store, None);
293
294 let true_store: ResponsesRenderOptions =
295 serde_json::from_str(r#"{"store": true}"#).unwrap();
296 assert_eq!(true_store.store, Some(true));
297
298 let false_store: ResponsesRenderOptions =
299 serde_json::from_str(r#"{"store": false}"#).unwrap();
300 assert_eq!(false_store.store, Some(false));
301 }
302
303 #[test]
304 fn anthropic_beta_values_reflect_enabled_options() {
305 let default_options = AnthropicRenderOptions::default();
306 assert!(default_options.beta_values().is_empty());
307
308 let native_options = AnthropicRenderOptions {
309 native_tool_changes: true,
310 };
311 assert_eq!(native_options.beta_values(), [INLINE_TOOLS_BETA]);
312 }
313}