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 = 1){
        // 组装请求体参数
        //        $data['message'] = [
        //            ['role' => 'system', 'content' => "You are now the marketing customer service of 深圳创贸集团"],
        //            ['role' => 'user', 'content' => '创贸集团有多少技术?'],
        //            ['role' => 'assistant', 'content' => '创贸集团有200+技术。'],
        //            ['role' => 'user', 'content' => '今天天气怎么样']
        //        ];
        $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']:"openai";
        //发送请求
        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);
            $body = $response->getBody();
            return $body;
        }
    }
}