diff --git a/ai/config.php b/ai/config.php index 2816213..bb62004 100644 --- a/ai/config.php +++ b/ai/config.php @@ -1,268 +1,87 @@ 'Method not allowed']); - exit; -} - -// Get POST data -$input = json_decode(file_get_contents('php://input'), true); - -if (!$input) { - http_response_code(400); - echo json_encode(['error' => 'Invalid JSON input']); - exit; -} - -// Include your config -require_once 'config.php'; -$config = include 'config.php'; - -try { - // Prepare AI prompt based on questionnaire answers - $prompt = generateAIPrompt($input); +/** + * Load environment variables from .env file if not already set + * This ensures compatibility with both CLI and web environments + */ +function loadEnvIfNeeded() { + // Check if required environment variables are missing + $projectUuid = getenv('PROJECT_UUID'); + $projectId = getenv('PROJECT_ID'); - // Call AI service (using your configured endpoint) - $aiResponse = callAIService($prompt, $config); - - // Process and format the response - $result = processAIResponse($aiResponse, $input); - - echo json_encode([ - 'success' => true, - 'data' => $result, - 'timestamp' => date('Y-m-d H:i:s') - ]); - -} catch (Exception $e) { - http_response_code(500); - echo json_encode([ - 'error' => 'AI processing failed', - 'message' => $e->getMessage() - ]); -} - -// ===== HELPER FUNCTIONS ===== - -function generateAIPrompt(array $answers): string { - $prompt = "Analysiere diese KI-Readiness-Bewertung eines Unternehmens und erstelle eine persönliche Auswertung:\n\n"; - - // Add company info - $prompt .= "Unternehmensinformationen:\n"; - if (isset($answers['q2'])) { - $prompt .= "- Branche: " . htmlspecialchars($answers['q2']) . "\n"; - } - if (isset($answers['q1'])) { - $prompt .= "- Größe: " . htmlspecialchars($answers['q1']) . "\n"; - } - - // Add goals - if (isset($answers['q4'])) { - $prompt .= "\nPrimäres KI-Ziel: " . htmlspecialchars($answers['q4']) . "\n"; - } - - // Add challenges - if (isset($answers['q12'])) { - $prompt .= "\nGrößte Herausforderung: " . htmlspecialchars($answers['q12']) . "\n"; - } - - // Add time-consuming tasks - if (isset($answers['q6']) && is_array($answers['q6'])) { - $prompt .= "\nZeitintensive Aufgaben:\n"; - foreach ($answers['q6'] as $task) { - $prompt .= "- " . htmlspecialchars($task) . "\n"; + if ( + ($projectUuid === false || $projectUuid === null || $projectUuid === '') || + ($projectId === false || $projectId === null || $projectId === '') + ) { + $envPath = realpath(__DIR__ . '/../../.env'); // executor/.env + if ($envPath && is_readable($envPath)) { + $lines = @file($envPath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: []; + foreach ($lines as $line) { + $line = trim($line); + if ($line === '' || $line[0] === '#') { + continue; + } + if (!str_contains($line, '=')) { + continue; + } + [$key, $value] = array_map('trim', explode('=', $line, 2)); + if ($key === '') { + continue; + } + $value = trim($value, "\"' "); + if (getenv($key) === false || getenv($key) === '') { + putenv("{$key}={$value}"); + } + } } } - - // Add current automation - if (isset($answers['q7'])) { - $prompt .= "\nAktuelle Automatisierung:\n" . htmlspecialchars($answers['q7']) . "\n"; - } - - // Add budget - if (isset($answers['q9'])) { - $prompt .= "\nKI-Budget: " . htmlspecialchars($answers['q9']) . "\n"; - } - - // Add technical affinity - if (isset($answers['q10'])) { - $prompt .= "\nTechnische Affinität: " . htmlspecialchars($answers['q10']) . "/5\n"; - } - - // Add timeline - if (isset($answers['q13'])) { - $prompt .= "\nUmsetzungszeitraum: " . htmlspecialchars($answers['q13']) . "\n"; - } - - $prompt .= "\n---\n"; - $prompt .= "Erstelle eine strukturierte Analyse mit:\n"; - $prompt .= "1. KI-Readiness Score (0-100)\n"; - $prompt .= "2. 3 konkrete Empfehlungen für KI-Tools\n"; - $prompt .= "3. Zeit- und Kosteneinsparungspotenzial\n"; - $prompt .= "4. Schritt-für-Schritt Umsetzungsplan\n"; - $prompt .= "Antworte in Deutsch, formell und professionell.\n"; - - return $prompt; } -function callAIService(string $prompt, array $config): array { - // Use your configured endpoint - $url = $config['base_url'] . $config['responses_path']; - - $headers = [ - 'Content-Type: application/json', - $config['project_header'] . ': ' . $config['project_uuid'] - ]; - - $data = [ - 'model' => $config['default_model'], - 'messages' => [ - [ - 'role' => 'system', - 'content' => 'Du bist ein KI-Beratungsexperte für kleine und mittlere Unternehmen. Analysiere KI-Readiness-Bewertungen und gebe maßgeschneiderte Empfehlungen.' - ], - [ - 'role' => 'user', - 'content' => $prompt - ] - ], - 'max_tokens' => 2000, - 'temperature' => 0.7 - ]; - - $ch = curl_init($url); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); - curl_setopt($ch, CURLOPT_POST, true); - curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); - curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); - curl_setopt($ch, CURLOPT_TIMEOUT, $config['timeout']); - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $config['verify_tls']); - - $response = curl_exec($ch); - $error = curl_error($ch); - $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); - curl_close($ch); - - if ($error) { - throw new Exception("cURL Error: " . $error); - } - - if ($httpCode !== 200) { - throw new Exception("API Error: HTTP $httpCode - " . $response); - } - - return json_decode($response, true); -} +// Load environment variables if needed +loadEnvIfNeeded(); -function processAIResponse(array $aiResponse, array $answers): array { - $content = $aiResponse['choices'][0]['message']['content'] ?? ''; - - // Parse the AI response into structured data - return [ - 'score' => extractScore($content), - 'recommendations' => extractRecommendations($content), - 'time_saving' => calculateTimeSaving($answers), - 'cost_saving' => calculateCostSaving($answers), - 'tools' => extractTools($content), - 'full_analysis' => $content, - 'email' => $answers['q14'] ?? '', - 'company_name' => extractCompanyName($answers), - 'report_id' => generateReportId() - ]; -} +// Get configuration values +$projectUuid = getenv('PROJECT_UUID'); +$projectId = getenv('PROJECT_ID'); -function extractScore(string $content): int { - preg_match('/Score[\s:]*(\d+)/i', $content, $matches); - return isset($matches[1]) ? (int)$matches[1] : rand(60, 85); -} +// Set defaults if not found +$projectUuid = ($projectUuid === false || $projectUuid === '') ? null : $projectUuid; +$projectId = ($projectId === false || $projectId === '') ? null : $projectId; -function extractRecommendations(string $content): array { - $recommendations = []; - $lines = explode("\n", $content); - - foreach ($lines as $line) { - if (preg_match('/^\d+\.\s+(.+)$/', $line, $matches)) { - $recommendations[] = $matches[1]; - } - } - - if (empty($recommendations)) { - return [ - 'Beginnen Sie mit einfachen KI-Tools wie ChatGPT für Content-Erstellung', - 'Automatisieren Sie Kundenkommunikation mit Chatbots', - 'Implementieren Sie ein KI-gestütztes CRM-System' - ]; - } - - return array_slice($recommendations, 0, 3); -} +// Base configuration +$baseUrl = 'https://flatlogic.com'; +$responsesPath = $projectId ? "/projects/{$projectId}/ai-request" : null; -function calculateTimeSaving(array $answers): string { - if (!isset($answers['q8'])) return '10-20h/Woche'; +// Return configuration array +return [ + 'base_url' => $baseUrl, + 'responses_path' => $responsesPath, + 'project_id' => $projectId, + 'project_uuid' => $projectUuid, + 'project_header' => 'project-uuid', + 'default_model' => 'gpt-5-mini', + 'timeout' => 30, + 'verify_tls' => true, - $map = [ - 'unter-5h' => '5-10h/Woche', - '5-10h' => '10-20h/Woche', - '11-15h' => '15-25h/Woche', - '16-20h' => '20-30h/Woche', - '20plus' => '30-40h/Woche' - ]; + // Additional settings for Appwizzy compatibility + 'debug' => getenv('APP_ENV') === 'development' || getenv('APP_DEBUG') === 'true', + 'max_retries' => 3, + 'retry_delay' => 2, - return $map[$answers['q8']] ?? '10-20h/Woche'; -} - -function calculateCostSaving(array $answers): string { - if (!isset($answers['q9'])) return '1.000-2.000€/Monat'; + // Feature flags + 'features' => [ + 'async_polling' => true, + 'json_response' => true, + 'streaming' => false, + ], - $map = [ - 'unter-50' => '500-1.000€/Monat', - '50-100' => '1.000-2.000€/Monat', - '100-300' => '2.000-3.000€/Monat', - '300-500' => '3.000-5.000€/Monat', - '500plus' => '5.000-10.000€/Monat' - ]; - - return $map[$answers['q9']] ?? '1.000-2.000€/Monat'; -} - -function extractTools(string $content): array { - $tools = []; - $keywords = ['ChatGPT', 'Zapier', 'Notion', 'Canva', 'Pipedrive', 'QuickBooks', 'Calendly']; - - foreach ($keywords as $tool) { - if (stripos($content, $tool) !== false) { - $tools[] = $tool; - } - } - - if (empty($tools)) { - $tools = ['ChatGPT', 'Zapier', 'Notion AI']; - } - - return array_slice($tools, 0, 3); -} - -function extractCompanyName(array $answers): string { - if (isset($answers['q2']) && !empty($answers['q2'])) { - return $answers['q2']; - } - return 'Ihr Unternehmen'; -} - -function generateReportId(): string { - return 'KI-' . date('Ymd') . '-' . strtoupper(substr(md5(uniqid()), 0, 8)); -} -?> \ No newline at end of file + // Cache settings + 'cache' => [ + 'enabled' => getenv('AI_CACHE_ENABLED') === 'true', + 'ttl' => 3600, // 1 hour + 'path' => __DIR__ . '/../cache/ai-responses', + ], +]; \ No newline at end of file