rkljw 4 ヶ月 前
コミット
ce15684639

+ 1 - 72
app/Controller/CollectorController.php

@@ -581,19 +581,7 @@ class CollectorController extends AbstractController
 
     }
 
-    /**
-     * 发送请求
-     * @param $data
-     * @return array
-     */
 
-
-    public function goSendCrawler($data=[])
-    {
-        var_dump("我要开始采集了!!!");
-        $this->collectorServiceClient->sendCrawler($data);
-        return Result::success([]);
-    }
     /**
      * 获取并搜索资讯
      * @return array
@@ -670,66 +658,6 @@ class CollectorController extends AbstractController
         return $result['code']==200?Result::success($result['data']):Result::error($result['message']);
     }
 
-    /**
-     * 智普demo
-     * @return void
-     */
-    public function zhipu()
-    {
-        $requireData = $this->request->all();
-        // 接口URL
-        $apiUrl = 'https://open.bigmodel.cn/api/paas/v4/chat/completions';
-        // API密钥
-        $apiKey = 'be1856920c54ac537b530d69bc2eda73.gOO2BMq9NXavzEMq';
-        // 请求参数
-        $params = [
-            "model"=>"glm-4",
-            "messages"=>[
-                [
-                    "role"=>"user",
-                    "content"=>$requireData['message']
-                ]
-
-            ]
-        ];
-        // 构建请求头部
-        $headers = [
-            'Content-Type: application/json',
-            'Authorization: Bearer ' . $apiKey
-        ];
-
-        // 将参数转换为JSON格式
-        $jsonParams = json_encode($params);
-        var_dump("看看:",$jsonParams);
-        // 初始化cURL会话
-        $ch = curl_init($apiUrl);
-        // 设置cURL选项
-        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
-        curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
-        curl_setopt($ch, CURLOPT_POST, true);
-        curl_setopt($ch, CURLOPT_POSTFIELDS,$jsonParams);
-
-        // 执行cURL会话
-        $response = curl_exec($ch);
-
-        // 检查是否有错误发生
-        if (curl_errno($ch)) {
-            echo 'cURL error: ' . curl_error($ch);
-        } else {
-            // 处理响应
-            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
-            if ($httpCode == 200) {
-                // 解码JSON响应
-                $responseData = json_decode($response, true);
-                Result::success($responseData);
-            } else {
-                echo "HTTP error: $httpCode\n";
-                echo "Response: $response\n";
-            }
-        }
-        // 关闭cURL会话
-        curl_close($ch);
-    }
     /**
      * 获取某个资讯
      * @return array
@@ -901,4 +829,5 @@ class CollectorController extends AbstractController
         return Result::success($result);
     }
    
+
 }

+ 66 - 0
app/Controller/SseController.php

@@ -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"=>"你是一个乐于解答各种问题的助手,你的任务是为用户提供专业、准确、有见地的建议。"//$requireData['message']
+                  ],
+                  [
+                      "role"=>"user",
+                      "content"=>"我是一个初级程序员,如何快速的提升自己"//$requireData['message']
+                  ]
+              ],
+              "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); // 暂停1秒
+        }
+        return $response;
+    }
+
+
+    function callApi($url, $method = 'GET', $data = null, $headers = [])
+    {
+        $ch = curl_init();
+
+        // 配置 CURL
+        curl_setopt($ch, CURLOPT_URL, $url);
+        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
+        // 如果是 POST/PUT 请求,附加数据
+        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;
+    }
+
+}

+ 2 - 1
app/Middleware/CorsMiddleware.php

@@ -15,7 +15,8 @@ class CorsMiddleware implements MiddlewareInterface
     public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
     {
         $response = Context::get(ResponseInterface::class);
-        $response = $response->withHeader('Access-Control-Allow-Origin', '*')
+        $response = $response
+            ->withHeader('Access-Control-Allow-Origin', '*')
             ->withHeader('Access-Control-Allow-Credentials', 'true')
             // Headers 可以根据实际情况进行改写。
             ->withHeader('Access-Control-Allow-Headers', '*');

+ 41 - 0
app/Service/Server/StreamServer.php

@@ -0,0 +1,41 @@
+<?php
+
+
+namespace App\Service\Server;
+
+
+use Hyperf\Dispatcher\HttpDispatcher;
+use Hyperf\ExceptionHandler\ExceptionHandlerDispatcher;
+use Hyperf\HttpServer\ResponseEmitter;
+use Hyperf\HttpServer\Server;
+use Psr\Container\ContainerInterface;
+use Swoole\Http\Request;
+use Swoole\Http\Response;
+
+class StreamServer extends Server
+{
+    const STREAM_URL = [
+        '/chat/stream'
+    ];
+    public function __construct(ContainerInterface $container, HttpDispatcher $dispatcher, ExceptionHandlerDispatcher $exceptionHandlerDispatcher, ResponseEmitter $responseEmitter)
+    {
+        parent::__construct($container, $dispatcher, $exceptionHandlerDispatcher, $responseEmitter);
+    }
+
+    /**
+     * @param Request $request
+     * @param Response $response
+     */
+    public function onRequest($request, $response): void
+    {
+        $pathInfo = $request->server['path_info'];
+        if (in_array($pathInfo, self::STREAM_URL)) {
+            $response->header('Content-Type', 'text/event-stream');
+            $response->header('Access-Control-Allow-Origin', '*');
+            $response->header('Access-Control-Allow-Methods', 'GET');
+            $response->header('Cache-Control', 'no-cache');
+            $response->header('Connection', 'keep-alive');
+        }
+        parent::onRequest($request, $response);
+    }
+}

+ 6 - 1
composer.json

@@ -16,6 +16,7 @@
         "death_satan/hyperf-validate": "^3.71",
         "doctrine/annotations": "^2.0",
         "easyswoole/verifycode": "3.x",
+        "friendsofhyperf/openai-client": "^3.1",
         "hyperf/amqp": "^3.1",
         "hyperf/async-queue": "^3.1",
         "hyperf/cache": "~3.1.0",
@@ -47,6 +48,7 @@
         "hyperf/utils": "^3.1",
         "hyperf/validation": "^3.1",
         "hyperf/websocket-server": "^3.1",
+        "openai-php/client": "^0.10.3",
         "phper666/jwt-auth": "^4.0"
     },
     "require-dev": {
@@ -81,7 +83,10 @@
     "prefer-stable": true,
     "config": {
         "optimize-autoloader": true,
-        "sort-packages": true
+        "sort-packages": true,
+        "allow-plugins": {
+            "php-http/discovery": true
+        }
     },
     "extra": [],
     "scripts": {

ファイルの差分が大きいため隠しています
+ 414 - 119
composer.lock


+ 5 - 2
config/api/collector.php

@@ -2,10 +2,13 @@
 
 declare(strict_types=1);
 
-use App\Controller\CollectorController;
+
 use App\Middleware\Auth\FooMiddleware;
 use Hyperf\HttpServer\Router\Router;
-
+//智普测试接口
+Router::addGroup('/chat', function () {
+    Router::get('/stream', 'App\Controller\SseController@stream');
+});
 Router::addGroup(
     '/collector', function () {
         Router::get('/index', [CollectorController::class, 'index']);

+ 1 - 1
config/autoload/middlewares.php

@@ -1,7 +1,7 @@
 <?php
 return [
     'http' => [
-        \App\Middleware\CorsMiddleware::class,
+//        \App\Middleware\CorsMiddleware::class,
 //        \App\Middleware\Auth\FooMiddleware::class,
         \Hyperf\Validation\Middleware\ValidationMiddleware::class,
     ],

+ 1 - 1
config/autoload/server.php

@@ -23,7 +23,7 @@ return [
             'port' => 9501,
             'sock_type' => SWOOLE_SOCK_TCP,
             'callbacks' => [
-                Event::ON_REQUEST => [Hyperf\HttpServer\Server::class, 'onRequest'],
+                Event::ON_REQUEST => [App\Service\Server\StreamServer::class, 'onRequest'],
             ],
         ],
         [

この差分においてかなりの量のファイルが変更されているため、一部のファイルを表示していません