Files
useds/app/common/service/SparkService.php
T
2026-01-14 18:37:15 +08:00

82 lines
2.4 KiB
PHP

<?php
namespace app\common\service;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
class SparkService
{
protected Client $client;
protected string $apiPassword;
protected string $model;
public function __construct()
{
$config = config('spark_lite');
$this->apiPassword = $config['api_password'];
$this->model = $config['model'];
// 使用 Guzzle 客户端,base_uri 指向 Spark API
$this->client = new Client([
'base_uri' => $config['base_uri'],
'timeout' => 30,
'verify' => false,
]);
}
/**
* 发送聊天请求
*
* @param string $message 用户输入文本
* @param string|null $userId 可选的用户唯一 ID
* @param array $options 其他可选参数(temperature 等)
* @return 返回 API 解析后的结果
*/
public function chat(string $message, ?string $userId = null, array $options = [],string $file = 'spark')
{
$payload = array_merge([
'model' => $this->model,
'messages' => [
[
'role' => 'user',
'content' => $message,
]
],
// 可根据需要设置
'temperature' => 1.0,
'top_k' => 4,
], $options);
if ($userId !== null) {
$payload['user'] = $userId;
}
try {
$response = $this->client->post('chat/completions', [
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => "Bearer {$this->apiPassword}",
],
'json' => $payload,
]);
$body = (string) $response->getBody();
$result = json_decode($body, true);
if($result['code'] != 0){
flg('spark chat:'.$body,false,$file);
}
return $result['choices'][0]['message']['content'];
} catch (RequestException $e) {
// 错误处理
$message = $e->getMessage();
if ($e->hasResponse()) {
$message .= ' ' . $e->getResponse()->getBody();
}
// log 或抛出异常都可以
error_log("[SparkService] Chat Error: {$message}");
return null;
}
}
}