chatbot.php 2.0 KB

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