ChatServer.php 3.4 KB
<?php
/**
+-----------------------------------------------------------------------------------------------------------------------
 * 逻辑层:ChatRecord 服务类,处理业务逻辑
+-----------------------------------------------------------------------------------------------------------------------
 *
 * PHP version 7
 *
 * @category  App\Services
 * @package   App\Services
 * @author    Richer <yangzi1028@163.com>
 * @date      2023年4月23日16:38:09
 * @copyright 2021-2022 Richer (http://www.Richer.com/)
 * @license   http://www.Richer.com/ License
 * @link      http://www.Richer.com/
 */
namespace App\Services;

use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use GuzzleHttp\Client;


/**
 * Class ChatServer
 * @package App\Services
 */
class ChatServer implements MessageComponentInterface {
    protected $clients;
    protected $gptApiUrl;
    protected $gptApiKey;

    protected $ai_model = 'gpt-3.5-turbo';
//    protected $ai_model = 'gpt-4'; // AI 模型
    protected $log_channel =  'openai'; // 日志 频道
    protected $log_desc=  '通过 openai 接口发送通知'; // 日志描述
    protected $context_timeout=  60 * 30; // 上下文超时时间
    protected $consumption_times =  1; // 每次请求消耗次数

    public function __construct() {
        $this->clients = new \SplObjectStorage;
        $this->gptApiUrl = 'https://api.openai.com/v1/chat/completions';
        $this->gptApiKey = getenv('OPENAI_API_KEY');;
    }

    public function onOpen(ConnectionInterface $conn) {
        $this->clients->attach($conn);
        echo "New connection! ({$conn->resourceId})\n";
    }

//    public function onMessage(ConnectionInterface $from, $msg) {
//        $client = new Client();
//        $response = $client->request('POST', $this->gptApiUrl, [
//            'headers' => [
//                'Authorization' => 'Bearer ' . $this->gptApiKey,
//                'Content-Type' => 'application/json'
//            ],
//            'json' => [
//                'text' => $msg
//            ]
//        ]);
//        $data = json_decode($response->getBody(), true);
//        $reply = $data['reply'];
//
//        foreach ($this->clients as $client) {
//            $client->send($reply);
//        }
//    }

    public function onMessage(ConnectionInterface $from, $msg) {
        $postData = [
            'text' => $msg
        ];
        $postDataJson = json_encode($postData);

        $headers = [
            'Authorization: Bearer ' . $this->gptApiKey,
            'Content-Type: application/json',
            'Content-Length: ' . strlen($postDataJson)
        ];

        $context = stream_context_create([
            'http' => [
                'method' => 'POST',
                'header' => implode("\r\n", $headers),
                'content' => $postDataJson
            ]
        ]);

        $response = file_get_contents($this->gptApiUrl, false, $context);
        $data = json_decode($response, true);
        $reply = $data['reply'];

        foreach ($this->clients as $client) {
            $client->send($reply);
        }
    }

    public function onClose(ConnectionInterface $conn) {
        $this->clients->detach($conn);
        echo "Connection {$conn->resourceId} has disconnected\n";
    }

    public function onError(ConnectionInterface $conn, \Exception $e) {
        echo "An error has occurred: {$e->getMessage()}\n";
        $conn->close();
    }
}