SseController.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Controller;
  4. use Hyperf\HttpServer\Contract\RequestInterface;
  5. use Hyperf\HttpServer\Contract\ResponseInterface;
  6. use Psr\Http\Message\ServerRequestInterface;
  7. class SseController extends AbstractController
  8. {
  9. public function stream(RequestInterface $request, ResponseInterface $response)
  10. {
  11. $params = [
  12. "model"=>"glm-4",
  13. "messages"=>[
  14. [
  15. "role"=>"system",
  16. "content"=>"你是一个乐于解答各种问题的助手,你的任务是为用户提供专业、准确、有见地的建议。"//$requireData['message']
  17. ],
  18. [
  19. "role"=>"user",
  20. "content"=>"我是一个初级程序员,如何快速的提升自己"//$requireData['message']
  21. ]
  22. ],
  23. "stream"=>true
  24. ];
  25. $apiUrl = "https://open.bigmodel.cn/api/paas/v4/chat/completions";
  26. $result= $this->callApi($apiUrl, 'POST', $params, ['Authorization: Bearer be1856920c54ac537b530d69bc2eda73.gOO2BMq9NXavzEMq']);
  27. $arr = preg_split('/\n\s*\n/', $result);
  28. // 开始流式传输
  29. $this->container->get(\Swoole\Http\Response::class)->status(200);
  30. foreach ($arr as $val){
  31. $response->write("$val\n\n");
  32. usleep(1000000); // 暂停1秒
  33. }
  34. return $response;
  35. }
  36. function callApi($url, $method = 'GET', $data = null, $headers = [])
  37. {
  38. $ch = curl_init();
  39. // 配置 CURL
  40. curl_setopt($ch, CURLOPT_URL, $url);
  41. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  42. curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
  43. // 如果是 POST/PUT 请求,附加数据
  44. if ($data && ($method === 'POST' || $method === 'PUT')) {
  45. curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
  46. $headers[] = 'Content-Type: application/json';
  47. }
  48. // 附加头部信息
  49. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  50. // 执行请求
  51. $response = curl_exec($ch);
  52. // 错误处理
  53. if (curl_errno($ch)) {
  54. $response = json_encode(['error' => curl_error($ch)]);
  55. }
  56. curl_close($ch);
  57. return $response;
  58. }
  59. }