Skip to main content

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`.
117#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
118#[serde(default, deny_unknown_fields)]
119#[non_exhaustive]
120pub struct ChatRenderOptions {
121    /// Replay the frame's own-format sealed `reasoning_content` message-level
122    /// items (default `true`). DeepSeek requires `reasoning_content` back on
123    /// every request that carries `tools` and ignores it otherwise; other
124    /// compatible providers differ, which is what this option is for. When it
125    /// is off, the renderer removes the `reasoning_content` key from its own
126    /// sealed items — dropping an item that carries nothing else — and changes
127    /// nothing else. Other sealed message fields still replay.
128    pub replay_reasoning_content: bool,
129}
130
131impl Default for ChatRenderOptions {
132    fn default() -> Self {
133        Self {
134            replay_reasoning_content: true,
135        }
136    }
137}
138
139#[cfg(test)]
140mod tests {
141    use super::*;
142
143    fn round_trip<T: Serialize + serde::de::DeserializeOwned + PartialEq + std::fmt::Debug>(
144        value: T,
145    ) {
146        let json = serde_json::to_string(&value).unwrap();
147        let back: T = serde_json::from_str(&json).unwrap();
148        assert_eq!(value, back);
149    }
150
151    #[test]
152    fn empty_json_deserializes_to_default() {
153        let anthropic: AnthropicRenderOptions = serde_json::from_str("{}").unwrap();
154        assert_eq!(anthropic, AnthropicRenderOptions::default());
155
156        let responses: ResponsesRenderOptions = serde_json::from_str("{}").unwrap();
157        assert_eq!(responses, ResponsesRenderOptions::default());
158
159        let chat: ChatRenderOptions = serde_json::from_str("{}").unwrap();
160        assert_eq!(chat, ChatRenderOptions::default());
161    }
162
163    #[test]
164    fn serialize_deserialize_round_trip_is_identity() {
165        round_trip(AnthropicRenderOptions::default());
166        round_trip(AnthropicRenderOptions {
167            native_tool_changes: true,
168        });
169
170        round_trip(ResponsesRenderOptions::default());
171        round_trip(ResponsesRenderOptions {
172            include_encrypted_reasoning: false,
173            store: None,
174            additional_tools: true,
175        });
176        round_trip(ResponsesRenderOptions {
177            include_encrypted_reasoning: true,
178            store: Some(true),
179            additional_tools: false,
180        });
181
182        round_trip(ChatRenderOptions::default());
183        round_trip(ChatRenderOptions {
184            replay_reasoning_content: false,
185        });
186    }
187
188    #[test]
189    fn unknown_field_is_rejected() {
190        let err =
191            serde_json::from_str::<AnthropicRenderOptions>(r#"{"unknown": true}"#).unwrap_err();
192        assert!(err.to_string().contains("unknown field `unknown`"));
193
194        let err = serde_json::from_str::<ResponsesRenderOptions>(r#"{"typo": 123}"#).unwrap_err();
195        assert!(err.to_string().contains("unknown field `typo`"));
196
197        let err =
198            serde_json::from_str::<ChatRenderOptions>(r#"{"unrecognized": false}"#).unwrap_err();
199        assert!(err.to_string().contains("unknown field `unrecognized`"));
200    }
201
202    #[test]
203    fn cross_protocol_field_is_rejected() {
204        let err = serde_json::from_str::<AnthropicRenderOptions>(r#"{"additional_tools": true}"#)
205            .unwrap_err();
206        assert!(err.to_string().contains("unknown field `additional_tools`"));
207
208        let err = serde_json::from_str::<ChatRenderOptions>(r#"{"native_tool_changes": true}"#)
209            .unwrap_err();
210        assert!(
211            err.to_string()
212                .contains("unknown field `native_tool_changes`")
213        );
214
215        let err =
216            serde_json::from_str::<ResponsesRenderOptions>(r#"{"replay_reasoning_content": true}"#)
217                .unwrap_err();
218        assert!(
219            err.to_string()
220                .contains("unknown field `replay_reasoning_content`")
221        );
222    }
223
224    #[test]
225    fn responses_store_null_gives_none_and_missing_gives_some_false() {
226        let missing: ResponsesRenderOptions = serde_json::from_str("{}").unwrap();
227        assert_eq!(missing.store, Some(false));
228
229        let null_store: ResponsesRenderOptions =
230            serde_json::from_str(r#"{"store": null}"#).unwrap();
231        assert_eq!(null_store.store, None);
232
233        let true_store: ResponsesRenderOptions =
234            serde_json::from_str(r#"{"store": true}"#).unwrap();
235        assert_eq!(true_store.store, Some(true));
236
237        let false_store: ResponsesRenderOptions =
238            serde_json::from_str(r#"{"store": false}"#).unwrap();
239        assert_eq!(false_store.store, Some(false));
240    }
241
242    #[test]
243    fn anthropic_beta_values_reflect_enabled_options() {
244        let default_options = AnthropicRenderOptions::default();
245        assert!(default_options.beta_values().is_empty());
246
247        let native_options = AnthropicRenderOptions {
248            native_tool_changes: true,
249        };
250        assert_eq!(native_options.beta_values(), [INLINE_TOOLS_BETA]);
251    }
252}