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
61
62
63
64
<?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";
}
}