Skip to main content

llm_trait/
request.rs

1//! Chat request types.
2
3use serde_json::Value;
4
5use super::message::ChatMessage;
6use super::reasoning::ReasoningConfig;
7
8/// Response format configuration.
9#[derive(Clone, Debug)]
10pub enum ResponseFormat {
11    JsonObject,
12    JsonSchema { name: String, schema: Value },
13}
14
15impl ResponseFormat {
16    pub fn to_api_value(&self) -> Value {
17        match self {
18            ResponseFormat::JsonObject => {
19                serde_json::json!({ "type": "json_object" })
20            }
21            ResponseFormat::JsonSchema { name, schema } => {
22                serde_json::json!({
23                    "type": "json_schema",
24                    "json_schema": {
25                        "name": name,
26                        "schema": schema,
27                    }
28                })
29            }
30        }
31    }
32}
33
34/// Unified chat request format.
35#[derive(Debug, Clone)]
36pub struct ChatRequest {
37    /// Message list (supports multimodal content)
38    pub messages: Vec<ChatMessage>,
39
40    /// Available tools
41    pub tools: Vec<Value>,
42
43    /// Reasoning/thinking configuration
44    pub reasoning: Option<ReasoningConfig>,
45
46    /// Response format configuration
47    pub response_format: Option<ResponseFormat>,
48
49    /// Optional model override.
50    ///
51    /// - `None`: Use the provider's default model
52    /// - `Some(name)`: Use the specified model for this request
53    ///
54    /// This enables multi-model routing: the application can set different
55    /// models for different scenes (e.g., "lite" for sub-agents, "advanced"
56    /// for architecture decisions) without creating multiple providers.
57    pub model: Option<String>,
58
59    /// Cache through message index `n` (inclusive): the system prompt, the
60    /// tool definitions and `messages[0..=n]` repeat verbatim on the next call
61    /// — a conversation appends, it does not rewrite its own prefix.
62    ///
63    /// This is a *claim about stability*, not a protocol instruction. Each
64    /// provider exploits it as its protocol allows: Anthropic marks a
65    /// `cache_control` breakpoint at the last cached block, OpenAI caches
66    /// prefixes automatically and needs no marker at all, and a provider
67    /// without caching ignores this. `None` means the caller makes no
68    /// stability claim and nothing is cached on purpose.
69    ///
70    /// Move `n` forward as the conversation grows (the standard shape: the
71    /// breakpoint trails the newest complete turn).
72    pub cache_through: Option<usize>,
73
74    /// Whether the model may issue several tool calls in one response.
75    ///
76    /// This is a *permission*, not a request for parallelism: it says the
77    /// harness can execute the calls concurrently and the caller will not be
78    /// confused by interleaved results. Each provider carries it as its
79    /// protocol allows — OpenAI sends `parallel_tool_calls`, Anthropic has no
80    /// such field and the model batches on its own, and a provider without it
81    /// ignores this. `None` makes no claim and the provider applies its own
82    /// default.
83    ///
84    /// Nothing here guarantees the model *will* batch. It only stops the
85    /// harness from forbidding it — measured on phimint session
86    /// 20261115_2fbff82e, models that may batch still averaged 1.41 calls per
87    /// turn, so the turn-count win is a bet, not a promise.
88    pub parallel_tool_calls: Option<bool>,
89}
90
91impl ChatRequest {
92    /// Create a simple text request.
93    pub fn new(messages: Vec<ChatMessage>) -> Self {
94        Self {
95            messages,
96            tools: Vec::new(),
97            reasoning: None,
98            response_format: None,
99            model: None,
100            cache_through: None,
101            parallel_tool_calls: None,
102        }
103    }
104
105    /// Claim that the request's prefix repeats verbatim on the next call, and
106    /// ask the provider to cache through message index `n`. See the field docs
107    /// for what each protocol does with it.
108    pub fn with_cache_through(mut self, n: usize) -> Self {
109        self.cache_through = Some(n);
110        self
111    }
112
113    /// Declare whether the model may batch tool calls in one response. See the
114    /// field docs for what each protocol does with it.
115    pub fn with_parallel_tool_calls(mut self, allow: bool) -> Self {
116        self.parallel_tool_calls = Some(allow);
117        self
118    }
119
120    /// Set model override.
121    pub fn with_model(mut self, model: impl Into<String>) -> Self {
122        self.model = Some(model.into());
123        self
124    }
125
126    /// Add tools.
127    pub fn with_tools(mut self, tools: Vec<Value>) -> Self {
128        self.tools = tools;
129        self
130    }
131
132    /// Add reasoning configuration.
133    pub fn with_reasoning(mut self, reasoning: ReasoningConfig) -> Self {
134        self.reasoning = Some(reasoning);
135        self
136    }
137
138    /// Set response format.
139    pub fn with_response_format(mut self, format: ResponseFormat) -> Self {
140        self.response_format = Some(format);
141        self
142    }
143}
144
145#[cfg(test)]
146mod response_format_tests {
147    use super::*;
148
149    #[test]
150    fn json_object_to_api_value() {
151        assert_eq!(
152            ResponseFormat::JsonObject.to_api_value(),
153            serde_json::json!({ "type": "json_object" })
154        );
155    }
156
157    #[test]
158    fn json_schema_to_api_value() {
159        let schema = serde_json::json!({"type": "object"});
160        let value = ResponseFormat::JsonSchema {
161            name: "answer".to_string(),
162            schema: schema.clone(),
163        }
164        .to_api_value();
165
166        assert_eq!(value["type"], "json_schema");
167        assert_eq!(value["json_schema"]["name"], "answer");
168        assert_eq!(value["json_schema"]["schema"], schema);
169    }
170
171    #[test]
172    fn with_response_format_stores_the_format() {
173        let req = ChatRequest::new(vec![ChatMessage::user("hi")])
174            .with_response_format(ResponseFormat::JsonObject);
175        assert!(matches!(
176            req.response_format,
177            Some(ResponseFormat::JsonObject)
178        ));
179    }
180}
181
182#[cfg(test)]
183mod tests {
184    use super::*;
185
186    #[test]
187    fn chat_request_new() {
188        let req = ChatRequest::new(vec![ChatMessage::user("hello")]);
189        assert_eq!(req.messages.len(), 1);
190        assert!(req.tools.is_empty());
191        assert!(req.reasoning.is_none());
192        assert!(req.response_format.is_none());
193        assert!(req.model.is_none());
194    }
195
196    #[test]
197    fn chat_request_with_model() {
198        let req = ChatRequest::new(vec![ChatMessage::user("hello")]).with_model("mimo-v2.5-pro");
199        assert_eq!(req.model.as_deref(), Some("mimo-v2.5-pro"));
200    }
201
202    #[test]
203    fn chat_request_with_tools() {
204        let tools = vec![serde_json::json!({"type": "function", "function": {"name": "test"}})];
205        let req = ChatRequest::new(vec![ChatMessage::user("hello")]).with_tools(tools.clone());
206        assert_eq!(req.tools.len(), 1);
207        assert_eq!(req.tools[0], tools[0]);
208    }
209
210    #[test]
211    fn chat_request_with_reasoning() {
212        let reasoning = ReasoningConfig {
213            enabled: Some(true),
214            budget_tokens: Some(4096),
215            effort: None,
216        };
217        let req = ChatRequest::new(vec![ChatMessage::user("hello")]).with_reasoning(reasoning);
218        assert!(req.reasoning.is_some());
219        assert_eq!(req.reasoning.as_ref().unwrap().budget_tokens, Some(4096));
220    }
221
222    #[test]
223    fn chat_request_builder_chain() {
224        let tools = vec![serde_json::json!({"name": "tool1"})];
225        let reasoning = ReasoningConfig {
226            enabled: Some(true),
227            ..Default::default()
228        };
229        let req = ChatRequest::new(vec![ChatMessage::user("hello")])
230            .with_tools(tools)
231            .with_reasoning(reasoning);
232        assert_eq!(req.tools.len(), 1);
233        assert!(req.reasoning.is_some());
234    }
235}