mockforge_core/
ai_response.rs

1//! AI-assisted response generation for dynamic mock endpoints
2//!
3//! This module provides configuration and utilities for generating
4//! dynamic mock responses using LLMs based on request context.
5
6use serde::{Deserialize, Serialize};
7use serde_json::Value;
8use std::collections::HashMap;
9
10/// AI response generation mode
11#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
12#[serde(rename_all = "lowercase")]
13pub enum AiResponseMode {
14    /// Static response (no AI)
15    Static,
16    /// Generate response using LLM
17    Intelligent,
18    /// Use static template enhanced with LLM
19    Hybrid,
20}
21
22impl Default for AiResponseMode {
23    fn default() -> Self {
24        Self::Static
25    }
26}
27
28/// Configuration for AI-assisted response generation per endpoint
29/// This is parsed from the `x-mockforge-ai` OpenAPI extension
30#[derive(Debug, Clone, Serialize, Deserialize)]
31pub struct AiResponseConfig {
32    /// Whether AI response generation is enabled
33    #[serde(default)]
34    pub enabled: bool,
35
36    /// Response generation mode
37    #[serde(default)]
38    pub mode: AiResponseMode,
39
40    /// Prompt template for LLM generation
41    /// Supports template variables: {{body.field}}, {{path.param}}, {{query.param}}, {{headers.name}}
42    pub prompt: Option<String>,
43
44    /// Additional context for generation
45    pub context: Option<String>,
46
47    /// Temperature for LLM (0.0 to 2.0)
48    #[serde(default = "default_temperature")]
49    pub temperature: f32,
50
51    /// Max tokens for LLM response
52    #[serde(default = "default_max_tokens")]
53    pub max_tokens: usize,
54
55    /// Schema that the response should conform to (JSON Schema)
56    pub schema: Option<Value>,
57
58    /// Enable caching for identical requests
59    #[serde(default = "default_true")]
60    pub cache_enabled: bool,
61}
62
63fn default_temperature() -> f32 {
64    0.7
65}
66
67fn default_max_tokens() -> usize {
68    1024
69}
70
71fn default_true() -> bool {
72    true
73}
74
75impl Default for AiResponseConfig {
76    fn default() -> Self {
77        Self {
78            enabled: false,
79            mode: AiResponseMode::Static,
80            prompt: None,
81            context: None,
82            temperature: default_temperature(),
83            max_tokens: default_max_tokens(),
84            schema: None,
85            cache_enabled: true,
86        }
87    }
88}
89
90impl AiResponseConfig {
91    /// Create a new AI response configuration
92    pub fn new(enabled: bool, mode: AiResponseMode, prompt: String) -> Self {
93        Self {
94            enabled,
95            mode,
96            prompt: Some(prompt),
97            ..Default::default()
98        }
99    }
100
101    /// Check if AI generation is enabled and configured
102    pub fn is_active(&self) -> bool {
103        self.enabled && self.mode != AiResponseMode::Static && self.prompt.is_some()
104    }
105}
106
107/// Request context for prompt template expansion
108#[derive(Debug, Clone, Default)]
109pub struct RequestContext {
110    /// HTTP method (GET, POST, etc.)
111    pub method: String,
112    /// Request path
113    pub path: String,
114    /// Path parameters
115    pub path_params: HashMap<String, Value>,
116    /// Query parameters
117    pub query_params: HashMap<String, Value>,
118    /// Request headers
119    pub headers: HashMap<String, Value>,
120    /// Request body (if JSON)
121    pub body: Option<Value>,
122    /// Multipart form fields (for multipart/form-data requests)
123    pub multipart_fields: HashMap<String, Value>,
124    /// Multipart file uploads (filename -> file path)
125    pub multipart_files: HashMap<String, String>,
126}
127
128impl RequestContext {
129    /// Create a new request context
130    pub fn new(method: String, path: String) -> Self {
131        Self {
132            method,
133            path,
134            ..Default::default()
135        }
136    }
137
138    /// Set path parameters
139    pub fn with_path_params(mut self, params: HashMap<String, Value>) -> Self {
140        self.path_params = params;
141        self
142    }
143
144    /// Set query parameters
145    pub fn with_query_params(mut self, params: HashMap<String, Value>) -> Self {
146        self.query_params = params;
147        self
148    }
149
150    /// Set headers
151    pub fn with_headers(mut self, headers: HashMap<String, Value>) -> Self {
152        self.headers = headers;
153        self
154    }
155
156    /// Set body
157    pub fn with_body(mut self, body: Value) -> Self {
158        self.body = Some(body);
159        self
160    }
161
162    /// Set multipart form fields
163    pub fn with_multipart_fields(mut self, fields: HashMap<String, Value>) -> Self {
164        self.multipart_fields = fields;
165        self
166    }
167
168    /// Set multipart file uploads
169    pub fn with_multipart_files(mut self, files: HashMap<String, String>) -> Self {
170        self.multipart_files = files;
171        self
172    }
173}
174
175/// Expand template variables in a prompt string using request context
176pub fn expand_prompt_template(template: &str, context: &RequestContext) -> String {
177    let mut result = template.to_string();
178
179    // Replace {{method}}
180    result = result.replace("{{method}}", &context.method);
181
182    // Replace {{path}}
183    result = result.replace("{{path}}", &context.path);
184
185    // Replace {{body.*}} variables
186    if let Some(body) = &context.body {
187        result = expand_json_variables(&result, "body", body);
188    }
189
190    // Replace {{path.*}} variables
191    result = expand_map_variables(&result, "path", &context.path_params);
192
193    // Replace {{query.*}} variables
194    result = expand_map_variables(&result, "query", &context.query_params);
195
196    // Replace {{headers.*}} variables
197    result = expand_map_variables(&result, "headers", &context.headers);
198
199    // Replace {{multipart.*}} variables for form fields
200    result = expand_map_variables(&result, "multipart", &context.multipart_fields);
201
202    result
203}
204
205/// Expand template variables from a JSON value
206fn expand_json_variables(template: &str, prefix: &str, value: &Value) -> String {
207    let mut result = template.to_string();
208
209    // Handle object fields
210    if let Some(obj) = value.as_object() {
211        for (key, val) in obj {
212            let placeholder = format!("{{{{{}.{}}}}}", prefix, key);
213            let replacement = match val {
214                Value::String(s) => s.clone(),
215                Value::Number(n) => n.to_string(),
216                Value::Bool(b) => b.to_string(),
217                Value::Null => "null".to_string(),
218                _ => serde_json::to_string(val).unwrap_or_default(),
219            };
220            result = result.replace(&placeholder, &replacement);
221        }
222    }
223
224    result
225}
226
227/// Expand template variables from a HashMap
228fn expand_map_variables(template: &str, prefix: &str, map: &HashMap<String, Value>) -> String {
229    let mut result = template.to_string();
230
231    for (key, val) in map {
232        let placeholder = format!("{{{{{}.{}}}}}", prefix, key);
233        let replacement = match val {
234            Value::String(s) => s.clone(),
235            Value::Number(n) => n.to_string(),
236            Value::Bool(b) => b.to_string(),
237            Value::Null => "null".to_string(),
238            _ => serde_json::to_string(val).unwrap_or_default(),
239        };
240        result = result.replace(&placeholder, &replacement);
241    }
242
243    result
244}
245
246#[cfg(test)]
247mod tests {
248    use super::*;
249    use serde_json::json;
250
251    #[test]
252    fn test_ai_response_config_default() {
253        let config = AiResponseConfig::default();
254        assert!(!config.enabled);
255        assert_eq!(config.mode, AiResponseMode::Static);
256        assert!(!config.is_active());
257    }
258
259    #[test]
260    fn test_ai_response_config_is_active() {
261        let config =
262            AiResponseConfig::new(true, AiResponseMode::Intelligent, "Test prompt".to_string());
263        assert!(config.is_active());
264
265        let config_disabled = AiResponseConfig {
266            enabled: false,
267            mode: AiResponseMode::Intelligent,
268            prompt: Some("Test".to_string()),
269            ..Default::default()
270        };
271        assert!(!config_disabled.is_active());
272    }
273
274    #[test]
275    fn test_request_context_builder() {
276        let mut path_params = HashMap::new();
277        path_params.insert("id".to_string(), json!("123"));
278
279        let context = RequestContext::new("POST".to_string(), "/users/123".to_string())
280            .with_path_params(path_params)
281            .with_body(json!({"name": "John"}));
282
283        assert_eq!(context.method, "POST");
284        assert_eq!(context.path, "/users/123");
285        assert_eq!(context.path_params.get("id"), Some(&json!("123")));
286        assert_eq!(context.body, Some(json!({"name": "John"})));
287    }
288
289    #[test]
290    fn test_expand_prompt_template_basic() {
291        let context = RequestContext::new("GET".to_string(), "/users".to_string());
292        let template = "Method: {{method}}, Path: {{path}}";
293        let expanded = expand_prompt_template(template, &context);
294        assert_eq!(expanded, "Method: GET, Path: /users");
295    }
296
297    #[test]
298    fn test_expand_prompt_template_body() {
299        let body = json!({
300            "message": "Hello",
301            "user": "Alice"
302        });
303        let context = RequestContext::new("POST".to_string(), "/chat".to_string()).with_body(body);
304
305        let template = "User {{body.user}} says: {{body.message}}";
306        let expanded = expand_prompt_template(template, &context);
307        assert_eq!(expanded, "User Alice says: Hello");
308    }
309
310    #[test]
311    fn test_expand_prompt_template_path_params() {
312        let mut path_params = HashMap::new();
313        path_params.insert("id".to_string(), json!("456"));
314        path_params.insert("name".to_string(), json!("test"));
315
316        let context = RequestContext::new("GET".to_string(), "/users/456".to_string())
317            .with_path_params(path_params);
318
319        let template = "Get user {{path.id}} with name {{path.name}}";
320        let expanded = expand_prompt_template(template, &context);
321        assert_eq!(expanded, "Get user 456 with name test");
322    }
323
324    #[test]
325    fn test_expand_prompt_template_query_params() {
326        let mut query_params = HashMap::new();
327        query_params.insert("search".to_string(), json!("term"));
328        query_params.insert("limit".to_string(), json!(10));
329
330        let context = RequestContext::new("GET".to_string(), "/search".to_string())
331            .with_query_params(query_params);
332
333        let template = "Search for {{query.search}} with limit {{query.limit}}";
334        let expanded = expand_prompt_template(template, &context);
335        assert_eq!(expanded, "Search for term with limit 10");
336    }
337
338    #[test]
339    fn test_expand_prompt_template_headers() {
340        let mut headers = HashMap::new();
341        headers.insert("user-agent".to_string(), json!("TestClient/1.0"));
342
343        let context =
344            RequestContext::new("GET".to_string(), "/api".to_string()).with_headers(headers);
345
346        let template = "Request from {{headers.user-agent}}";
347        let expanded = expand_prompt_template(template, &context);
348        assert_eq!(expanded, "Request from TestClient/1.0");
349    }
350
351    #[test]
352    fn test_expand_prompt_template_complex() {
353        let mut path_params = HashMap::new();
354        path_params.insert("id".to_string(), json!("789"));
355
356        let mut query_params = HashMap::new();
357        query_params.insert("format".to_string(), json!("json"));
358
359        let body = json!({"action": "update", "value": 42});
360
361        let context = RequestContext::new("PUT".to_string(), "/api/items/789".to_string())
362            .with_path_params(path_params)
363            .with_query_params(query_params)
364            .with_body(body);
365
366        let template = "{{method}} item {{path.id}} with action {{body.action}} and value {{body.value}} in format {{query.format}}";
367        let expanded = expand_prompt_template(template, &context);
368        assert_eq!(expanded, "PUT item 789 with action update and value 42 in format json");
369    }
370}