|
@@ -11,37 +11,56 @@ class SseController extends AbstractController
|
|
|
{
|
|
|
public function stream(RequestInterface $request, ResponseInterface $response)
|
|
|
{
|
|
|
- var_dump("===");
|
|
|
-
|
|
|
- $response = $response
|
|
|
- ->withAddedHeader('Access-Control-Allow-Origin', '*')
|
|
|
- ->withAddedHeader('Access-Control-Allow-Methods', 'GET')
|
|
|
- ->withAddedHeader('Content-Type', 'text/event-stream')
|
|
|
- ->withAddedHeader('Cache-Control', 'no-cache')
|
|
|
- ->withAddedHeader('Connection', 'keep-alive');
|
|
|
- var_dump("bbbbbbb");
|
|
|
- $origin = $request->getHeaderLine('Origin');
|
|
|
- if ($this->isAllowedOrigin($origin)) {
|
|
|
- var_dump("nicde");
|
|
|
- $response = $response->withAddedHeader('Access-Control-Allow-Origin', $origin);
|
|
|
- $response = $response->withAddedHeader('Access-Control-Allow-Credentials', 'true');
|
|
|
- }
|
|
|
+ $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);
|
|
|
- for ($i = 0; $i < 10; $i++) {
|
|
|
- $data = json_encode(['message' => "Event $i"]);
|
|
|
- var_dump("测试数据");
|
|
|
- $response->write("data: $data\n\n");
|
|
|
+ foreach ($arr as $val){
|
|
|
+ $response->write("$val\n\n");
|
|
|
usleep(1000000);
|
|
|
}
|
|
|
return $response;
|
|
|
}
|
|
|
- protected function isAllowedOrigin(string $origin): bool
|
|
|
+
|
|
|
+
|
|
|
+ function callApi($url, $method = 'GET', $data = null, $headers = [])
|
|
|
{
|
|
|
-
|
|
|
-
|
|
|
- $allowedOrigins = ['http://localhost:3000', 'http://192.168.1.100:3000'];
|
|
|
+ $ch = curl_init();
|
|
|
|
|
|
- return in_array($origin, $allowedOrigins, true);
|
|
|
+
|
|
|
+ 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;
|
|
|
}
|
|
|
+
|
|
|
}
|