Skip to main content

mockforge_openapi/response/
ai_assisted.rs

1//! AI-assisted response generation for MockForge
2//!
3//! Contains the `generate_ai_response` method and related helpers.
4
5use super::*;
6
7impl ResponseGenerator {
8    /// Generate an AI-assisted response using LLM
9    ///
10    /// This method generates a dynamic response based on request context
11    /// using the configured LLM provider (OpenAI, Anthropic, etc.)
12    ///
13    /// # Arguments
14    /// * `ai_config` - The AI response configuration
15    /// * `context` - The request context for prompt expansion
16    /// * `generator` - Optional AI generator implementation (if None, returns placeholder)
17    ///
18    /// # Returns
19    /// A JSON value containing the generated response
20    pub async fn generate_ai_response(
21        ai_config: &AiResponseConfig,
22        context: &RequestContext,
23        generator: Option<&dyn AiGenerator>,
24    ) -> Result<Value> {
25        // Get the prompt template and expand it with request context
26        let prompt_template = ai_config
27            .prompt
28            .as_ref()
29            .ok_or_else(|| mockforge_foundation::error::Error::internal("AI prompt is required"))?;
30
31        // Note: expand_prompt_template is now in mockforge-template-expansion crate
32        // For now, we'll do a simple string replacement as a fallback
33        // In the future, this should be refactored to use the template expansion crate
34        let expanded_prompt = prompt_template
35            .replace("{{method}}", &context.method)
36            .replace("{{path}}", &context.path);
37
38        tracing::info!("AI response generation requested with prompt: {}", expanded_prompt);
39
40        // Use the provided generator if available
41        if let Some(gen) = generator {
42            tracing::debug!("Using provided AI generator for response");
43            return gen.generate(&expanded_prompt, ai_config).await;
44        }
45
46        // No generator available — return an error so callers know AI is not configured
47        tracing::warn!(
48            "No AI generator provided; configure MOCKFORGE_AI_PROVIDER to enable AI responses"
49        );
50        Err(mockforge_foundation::error::Error::internal(
51            "AI response generation is not available: no AI generator configured. \
52             Set MOCKFORGE_AI_PROVIDER and MOCKFORGE_AI_API_KEY environment variables to enable AI-assisted responses.",
53        ))
54    }
55}