GptService.php
2.0 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<?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;
}
}
}