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
176///
177/// This function is re-exported from mockforge-template-expansion crate.
178/// Import it directly from that crate to avoid Send issues.
179///
180/// For backwards compatibility, you can also use:
181/// ```rust
182/// use mockforge_template_expansion::expand_prompt_template;
183/// ```
184pub fn expand_prompt_template(_template: &str, _context: &RequestContext) -> String {
185    // This is a placeholder - the actual implementation is in mockforge-template-expansion
186    // This function should not be called directly. Use mockforge_template_expansion::expand_prompt_template instead.
187    unimplemented!("expand_prompt_template has been moved to mockforge-template-expansion crate. Use mockforge_template_expansion::expand_prompt_template instead.")
188}
189
190#[cfg(test)]
191mod tests {
192    use super::*;
193    use mockforge_template_expansion::{
194        expand_prompt_template, RequestContext as TemplateRequestContext,
195    };
196    use serde_json::json;
197
198    // Helper to convert core RequestContext to template expansion RequestContext
199    fn to_template_context(context: &RequestContext) -> TemplateRequestContext {
200        TemplateRequestContext {
201            method: context.method.clone(),
202            path: context.path.clone(),
203            path_params: context.path_params.clone(),
204            query_params: context.query_params.clone(),
205            headers: context.headers.clone(),
206            body: context.body.clone(),
207            multipart_fields: context.multipart_fields.clone(),
208            multipart_files: context.multipart_files.clone(),
209        }
210    }
211
212    #[test]
213    fn test_ai_response_config_default() {
214        let config = AiResponseConfig::default();
215        assert!(!config.enabled);
216        assert_eq!(config.mode, AiResponseMode::Static);
217        assert!(!config.is_active());
218    }
219
220    #[test]
221    fn test_ai_response_config_is_active() {
222        let config =
223            AiResponseConfig::new(true, AiResponseMode::Intelligent, "Test prompt".to_string());
224        assert!(config.is_active());
225
226        let config_disabled = AiResponseConfig {
227            enabled: false,
228            mode: AiResponseMode::Intelligent,
229            prompt: Some("Test".to_string()),
230            ..Default::default()
231        };
232        assert!(!config_disabled.is_active());
233    }
234
235    #[test]
236    fn test_request_context_builder() {
237        let mut path_params = HashMap::new();
238        path_params.insert("id".to_string(), json!("123"));
239
240        let context = RequestContext::new("POST".to_string(), "/users/123".to_string())
241            .with_path_params(path_params)
242            .with_body(json!({"name": "John"}));
243
244        assert_eq!(context.method, "POST");
245        assert_eq!(context.path, "/users/123");
246        assert_eq!(context.path_params.get("id"), Some(&json!("123")));
247        assert_eq!(context.body, Some(json!({"name": "John"})));
248    }
249
250    #[test]
251    fn test_expand_prompt_template_basic() {
252        let context = RequestContext::new("GET".to_string(), "/users".to_string());
253        let template = "Method: {{method}}, Path: {{path}}";
254        let template_context = to_template_context(&context);
255        let expanded = expand_prompt_template(template, &template_context);
256        assert_eq!(expanded, "Method: GET, Path: /users");
257    }
258
259    #[test]
260    fn test_expand_prompt_template_body() {
261        let body = json!({
262            "message": "Hello",
263            "user": "Alice"
264        });
265        let context = RequestContext::new("POST".to_string(), "/chat".to_string()).with_body(body);
266
267        let template = "User {{body.user}} says: {{body.message}}";
268        let template_context = to_template_context(&context);
269        let expanded = expand_prompt_template(template, &template_context);
270        assert_eq!(expanded, "User Alice says: Hello");
271    }
272
273    #[test]
274    fn test_expand_prompt_template_path_params() {
275        let mut path_params = HashMap::new();
276        path_params.insert("id".to_string(), json!("456"));
277        path_params.insert("name".to_string(), json!("test"));
278
279        let context = RequestContext::new("GET".to_string(), "/users/456".to_string())
280            .with_path_params(path_params);
281
282        let template = "Get user {{path.id}} with name {{path.name}}";
283        let template_context = to_template_context(&context);
284        let expanded = expand_prompt_template(template, &template_context);
285        assert_eq!(expanded, "Get user 456 with name test");
286    }
287
288    #[test]
289    fn test_expand_prompt_template_query_params() {
290        let mut query_params = HashMap::new();
291        query_params.insert("search".to_string(), json!("term"));
292        query_params.insert("limit".to_string(), json!(10));
293
294        let context = RequestContext::new("GET".to_string(), "/search".to_string())
295            .with_query_params(query_params);
296
297        let template = "Search for {{query.search}} with limit {{query.limit}}";
298        let template_context = to_template_context(&context);
299        let expanded = expand_prompt_template(template, &template_context);
300        assert_eq!(expanded, "Search for term with limit 10");
301    }
302
303    #[test]
304    fn test_expand_prompt_template_headers() {
305        let mut headers = HashMap::new();
306        headers.insert("user-agent".to_string(), json!("TestClient/1.0"));
307
308        let context =
309            RequestContext::new("GET".to_string(), "/api".to_string()).with_headers(headers);
310
311        let template = "Request from {{headers.user-agent}}";
312        let template_context = to_template_context(&context);
313        let expanded = expand_prompt_template(template, &template_context);
314        assert_eq!(expanded, "Request from TestClient/1.0");
315    }
316
317    #[test]
318    fn test_expand_prompt_template_complex() {
319        let mut path_params = HashMap::new();
320        path_params.insert("id".to_string(), json!("789"));
321
322        let mut query_params = HashMap::new();
323        query_params.insert("format".to_string(), json!("json"));
324
325        let body = json!({"action": "update", "value": 42});
326
327        let context = RequestContext::new("PUT".to_string(), "/api/items/789".to_string())
328            .with_path_params(path_params)
329            .with_query_params(query_params)
330            .with_body(body);
331
332        let template = "{{method}} item {{path.id}} with action {{body.action}} and value {{body.value}} in format {{query.format}}";
333        let template_context = to_template_context(&context);
334        let expanded = expand_prompt_template(template, &template_context);
335        assert_eq!(expanded, "PUT item 789 with action update and value 42 in format json");
336    }
337}