GptService.php 2.0 KB
<?php
/**
 * @remark :
 * @name   :GptService.php
 * @author :lyh
 * @method :post
 * @time   :2025/4/1 17:58
 */

namespace App\Services;

use Hbb\CmerLlmChat\CmerClient;
use Hbb\CmerLlmChat\models\ChatModel;
use Illuminate\Support\Facades\Log;

class GptService
{
    /**
     * @remark :大模型会话
     * @name   :get_ai_chat
     * @author :lyh
     * @method :post
     * @time   :2025/4/2 9:38
     *
     */
    public function get_ai_chat($data,$type = 0){
        $apikey = env('AI_CREATE_KEY')??'7yn!We6$&NnVA38bpGy*A@4TQ5iYLJcW';
        $client = new CmerClient($apikey);
        // 修改超时时间,默认60秒
        $client->timeout = 300;
        $payload = new ChatModel($data['message']);
        // 修改模型名称,豆包,Gpt,Claude
        $payload->model = env('CHAT_GTP_MODEL','gpt-4o-mini');;
        $payload->supplier = isset($data['supplier'])?$data['supplier']:"azure";
        //发送请求
        if($type == 1){//返回数据
            $response = $client->chat($payload);
            $result = $response->getBody()->getContents();
            @file_put_contents(storage_path('logs/lyh_error.log'), var_export($result, true) . PHP_EOL, FILE_APPEND);
            if(!$result){
                Log::info('ai接口返回错误信息:'.$result. PHP_EOL);
                return false;
            }
            return json_decode($result,true);
        }else {
            // **流式请求**
            $payload->stream = true;
            $response = $client->chat($payload);
            $stream = $response->getBody();
            return $stream;
        }
    }

    /**
     * @remark :返回格式
     * @name   :en_sse_data
     * @author :lyh
     * @method :post
     * @time   :2025/4/2 16:56
     */
    public function en_sse_data($body, string $type='text'){
        return 'data:'.json_encode(['id'    =>  md5(is_array($body) ? json_encode($body) : $body), 'data'  =>  $body, 'type'  =>  $type],JSON_UNESCAPED_UNICODE)."\n\n";
    }
}