rkljw преди 4 месеца
родител
ревизия
bcd3dcd363

+ 0 - 38
.env

@@ -1,38 +0,0 @@
-APP_NAME=user_producer
-APP_ENV=dev
-HOST = http://192.168.1.201:9501/
-DB_DRIVER=mysql
-DB_HOST=127.0.0.1
-DB_PORT=3306
-DB_DATABASE=hyperf
-DB_USERNAME=root
-DB_PASSWORD=root123
-DB_CHARSET=utf8mb4
-DB_COLLATION=utf8mb4_unicode_ci
-DB_PREFIX=
-
-#REDIS_HOST=101.254.114.211
-#REDIS_AUTH=YPWWnFnNebc7427B
-#REDIS_PORT=26739
-#REDIS_DB=0
-
-
-REDIS_HOST=192.168.1.201
-REDIS_AUTH=
-REDIS_PORT=6379
-REDIS_DB=0
-
-AMQP_HOST=103.105.201.2
-AMQP_PORT=5673
-AMQP_USER=rabbitmq
-AMQP_PASSWORD=H8eDTAk6LY7EjJ8y
-
-
-#小程序获取openid
-WECHAT = https://api.weixin.qq.com/
-
-#小程序appID
-APPID = wx830ada852dd1707f
-#小程序SECRET
-APP_SECRET = 09d1ac9287cb6f3c5e81aa27a6b7138e
-#12

+ 0 - 69
app/Controller/CollectorController.php

@@ -137,73 +137,4 @@ class CollectorController extends AbstractController
 
     }
 
-    /**
-     * 发送请求
-     * @param $data
-     * @return array
-     */
-//    public function goSendCrawler($data=[])
-//    {
-//        var_dump("我要开始采集了!!!");
-//        $this->collectorServiceClient->sendCrawler($data);
-//        return Result::success([]);
-//    }
-      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);
-      }
-
-
 }

+ 43 - 24
app/Controller/SseController.php

@@ -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"=>"你是一个乐于解答各种问题的助手,你的任务是为用户提供专业、准确、有见地的建议。"//$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);
-        for ($i = 0; $i < 10; $i++) { // 模拟发送10个事件
-            $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); // 暂停1秒
         }
         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
+        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', '*');

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

@@ -31,6 +31,8 @@ class StreamServer extends Server
         $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');
         }

+ 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",
@@ -45,6 +46,7 @@
         "hyperf/translation": "^3.1",
         "hyperf/validation": "^3.1",
         "hyperf/websocket-server": "^3.1",
+        "openai-php/client": "^0.10.3",
         "phper666/jwt-auth": "^4.0"
     },
     "require-dev": {
@@ -79,7 +81,10 @@
     "prefer-stable": true,
     "config": {
         "optimize-autoloader": true,
-        "sort-packages": true
+        "sort-packages": true,
+        "allow-plugins": {
+            "php-http/discovery": true
+        }
     },
     "extra": [],
     "scripts": {

Файловите разлики са ограничени, защото са твърде много
+ 413 - 118
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']);

+ 0 - 10
config/autoload/cors.php

@@ -1,10 +0,0 @@
-<?php
-return [
-    'paths' => ['api/*', 'chat/stream'], // 允许访问的路径
-    'allowed_methods' => ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
-    'allowed_origins' => ['http://localhost:3000', 'http://192.168.1.100:3000'], // 替换为你的前端地址
-    'allowed_headers' => ['Content-Type', 'Authorization'], // 允许的请求头
-    'exposed_headers' => [], // 暴露给前端的响应头
-    'max_age' => 0, // 预检请求的结果可以被缓存的时间
-    'supports_credentials' => false, // 是否支持凭证
-];

+ 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'],
             ],
         ],
         [

Някои файлове не бяха показани, защото твърде много файлове са промени