sse.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. // 强制禁用所有缓冲
  3. while (ob_get_level()) ob_end_clean();
  4. header('X-Accel-Buffering: no');
  5. // 设置 SSE 头部
  6. header("Content-Type: text/event-stream");
  7. header("Cache-Control: no-cache");
  8. header("Connection: keep-alive");
  9. header("Access-Control-Allow-Origin: *");
  10. // 配置执行环境
  11. set_time_limit(0);
  12. ignore_user_abort(true);
  13. $content = $_GET['question'];
  14. $decodedData = strtr($content, '-_', '+/');
  15. // 使用 base64_decode 解码数据
  16. $content = base64_decode($decodedData).'请务必用中文回答我的问题。';
  17. $url = "http://8.137.127.56:5000/v1/chat/completions";
  18. $headers = array(
  19. "Content-Type: application/json"
  20. );
  21. $data = array(
  22. "messages" => array(
  23. array(
  24. "role" => "user",
  25. "content" => $content,
  26. )
  27. ),
  28. "mode" => "instruct",
  29. "instruction_template" => "Alpaca",
  30. "stream" => true,
  31. );
  32. $ch = curl_init();
  33. curl_setopt($ch, CURLOPT_URL, $url);
  34. curl_setopt($ch, CURLOPT_POST, true);
  35. curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
  36. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  37. curl_setopt($ch, CURLOPT_RETURNTRANSFER, false); // 保持直接输出模式
  38. curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($ch, $data) {
  39. // 处理流式响应数据
  40. $lines = explode("\n", $data);
  41. foreach ($lines as $line) {
  42. if (strpos($line, 'data:') === 0) {
  43. // 转发原始SSE格式数据
  44. echo $line . "\n\n";
  45. ob_flush();
  46. flush();
  47. }
  48. }
  49. return strlen($data); // 必须返回处理的数据长度
  50. });
  51. // 错误处理
  52. curl_setopt($ch, CURLOPT_TIMEOUT, 86400);
  53. curl_setopt($ch, CURLOPT_FAILONERROR, true);
  54. // 执行请求
  55. try {
  56. curl_exec($ch);
  57. // 检查HTTP状态码
  58. $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  59. if ($statusCode !== 200) {
  60. echo "event: error\ndata: HTTP Status {$statusCode}\n\n";
  61. ob_flush();
  62. flush();
  63. }
  64. } catch (Exception $e) {
  65. echo "event: error\ndata: " . $e->getMessage() . "\n\n";
  66. ob_flush();
  67. flush();
  68. }
  69. // 清理资源
  70. curl_close($ch);
  71. // 显式结束流
  72. echo "event: end\ndata: Stream ended\n\n";
  73. ob_flush();
  74. flush();
  75. exit;