|
@@ -0,0 +1,66 @@
|
|
|
+<?php
|
|
|
+declare(strict_types=1);
|
|
|
+
|
|
|
+namespace App\Controller;
|
|
|
+
|
|
|
+use Hyperf\HttpServer\Contract\RequestInterface;
|
|
|
+use Hyperf\HttpServer\Contract\ResponseInterface;
|
|
|
+use Psr\Http\Message\ServerRequestInterface;
|
|
|
+
|
|
|
+class SseController extends AbstractController
|
|
|
+{
|
|
|
+ public function stream(RequestInterface $request, ResponseInterface $response)
|
|
|
+ {
|
|
|
+ $params = [
|
|
|
+ "model"=>"glm-4",
|
|
|
+ "messages"=>[
|
|
|
+ [
|
|
|
+ "role"=>"system",
|
|
|
+ "content"=>"你是一个乐于解答各种问题的助手,你的任务是为用户提供专业、准确、有见地的建议。"
|
|
|
+ ],
|
|
|
+ [
|
|
|
+ "role"=>"user",
|
|
|
+ "content"=>"我是一个初级程序员,如何快速的提升自己"
|
|
|
+ ]
|
|
|
+ ],
|
|
|
+ "stream"=>true
|
|
|
+ ];
|
|
|
+ $apiUrl = "https://open.bigmodel.cn/api/paas/v4/chat/completions";
|
|
|
+ $result= $this->callApi($apiUrl, 'POST', $params, ['Authorization: Bearer be1856920c54ac537b530d69bc2eda73.gOO2BMq9NXavzEMq']);
|
|
|
+ $arr = preg_split('/\n\s*\n/', $result);
|
|
|
+
|
|
|
+ $this->container->get(\Swoole\Http\Response::class)->status(200);
|
|
|
+ foreach ($arr as $val){
|
|
|
+ $response->write("$val\n\n");
|
|
|
+ usleep(1000000);
|
|
|
+ }
|
|
|
+ return $response;
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
+ function callApi($url, $method = 'GET', $data = null, $headers = [])
|
|
|
+ {
|
|
|
+ $ch = curl_init();
|
|
|
+
|
|
|
+
|
|
|
+ curl_setopt($ch, CURLOPT_URL, $url);
|
|
|
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
|
|
+ curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
|
|
|
+
|
|
|
+ if ($data && ($method === 'POST' || $method === 'PUT')) {
|
|
|
+ curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
|
|
|
+ $headers[] = 'Content-Type: application/json';
|
|
|
+ }
|
|
|
+
|
|
|
+ curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
|
|
|
+
|
|
|
+ $response = curl_exec($ch);
|
|
|
+
|
|
|
+ if (curl_errno($ch)) {
|
|
|
+ $response = json_encode(['error' => curl_error($ch)]);
|
|
|
+ }
|
|
|
+ curl_close($ch);
|
|
|
+ return $response;
|
|
|
+ }
|
|
|
+
|
|
|
+}
|