chatbot.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. require_once 'CSVReader.php';
  3. require_once 'PDFReader.php';
  4. require_once 'PromptBuilder.php';
  5. // 2 Minuten erlauben
  6. set_time_limit(2500);
  7. header('Content-Type: application/json');
  8. // only accept POST requests
  9. if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
  10. http_response_code(405);
  11. echo json_encode(['error' => 'Only POST allowed']);
  12. exit;
  13. }
  14. // Build prompt for deepseek
  15. $input = json_decode(file_get_contents('php://input'), true);
  16. $question = isset($input['question']) ? $input['question'] : '';
  17. $roleFile = __DIR__ . '/data/role.txt';
  18. $role = file_exists($roleFile) ? file_get_contents($roleFile) : '';
  19. // Reading CSV data
  20. $csvReader = new CSVReader(__DIR__ . '/data/csv');
  21. $csvRows = $csvReader->readAll();
  22. $contextText = $csvReader->toString($csvRows);
  23. // Reading PDF data
  24. $pdfReader = new PDFReader(__DIR__ . '/data/pdf');
  25. $pdfData = $pdfReader->readAll();
  26. $pdfContext = $pdfReader->toString($pdfData);
  27. // TODO: Read HTML data
  28. $htmlContext = '';
  29. $prompt = new PromptBuilder();
  30. $prompt->setRole($role);
  31. $prompt->setQuestion($question);
  32. $promptContext = "\nCSV-Kontext:\n" . $contextText;
  33. $promptContext .= "\nPDF-Kontext:\n" . $pdfContext;
  34. $promptContext .= "\nHTML-Wissensdatenbank:\n" . $htmlContext;
  35. $prompt->setContext($contextText);
  36. $fullPrompt = $prompt->buildPromptString();
  37. error_log("System prompt length: " . strlen($fullPrompt));
  38. $payload = $prompt->buildPromptData();
  39. //Starting Prompt Generation
  40. $start = microtime(true);
  41. $ch = curl_init('http://localhost:1234/api/v0/chat/completions');
  42. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  43. curl_setopt($ch, CURLOPT_POST, true);
  44. curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
  45. curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
  46. $response = curl_exec($ch);
  47. curl_close($ch);
  48. $data = json_decode($response, true);
  49. $end = microtime(true);
  50. $responseText = isset($data['choices'][0]['message']['content']) ? $data['choices'][0]['message']['content'] : '';
  51. $responseText = trim($responseText);
  52. echo json_encode([
  53. 'reply' => $responseText,
  54. 'duration_seconds' => round($end - $start, 3)
  55. ]);