62 lines
2.2 KiB
PHP
62 lines
2.2 KiB
PHP
<?php
|
|
|
|
namespace app\mzl\common\org;
|
|
|
|
use support\Log;
|
|
|
|
class XunfeiSpark
|
|
{
|
|
const apiPassword = 'NWoTmfLkvGNyNwEeRBat:gojsysouMrXbsfLNgcRU';
|
|
|
|
public static function comment($param,int $max_tokens = 300){
|
|
foreach ($param as $k=>$v){
|
|
$param[$k]["content"] .= "模拟网络用户做出回答,引导客户购车,回答长度不要超过三百字";
|
|
}
|
|
return self::chat($param,$max_tokens);
|
|
}
|
|
|
|
/**
|
|
* 调用讯飞星火API
|
|
* @param array $messages 消息内容,格式为[['role' => 'user', 'content' => 'xxx'], ...]
|
|
* @param int $max_tokens 回复长度
|
|
* @param string $model 模型,默认generalv3.5
|
|
* @param bool $stream 是否流式,默认true
|
|
* @return string|false API响应内容,失败返回false
|
|
*/
|
|
public static function chat(array $messages,int $max_tokens = 300, string $model = '4.0Ultra', bool $stream = false)
|
|
{
|
|
$url = 'https://spark-api-open.xf-yun.com/v1/chat/completions';
|
|
$headers = [
|
|
'Authorization: Bearer ' . self::apiPassword,
|
|
'Content-Type: application/json',
|
|
];
|
|
$data = [
|
|
'model' => $model,
|
|
'messages' => $messages,
|
|
'stream' => $stream,
|
|
'max_tokens' => 300,
|
|
];
|
|
$ch = curl_init();
|
|
curl_setopt($ch, CURLOPT_URL, $url);
|
|
curl_setopt($ch, CURLOPT_POST, true);
|
|
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
|
|
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
|
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data, JSON_UNESCAPED_UNICODE));
|
|
// 如需跳过SSL验证(不推荐生产环境使用)
|
|
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
|
|
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
|
|
$response = curl_exec($ch);
|
|
if (curl_errno($ch)) {
|
|
curl_close($ch);
|
|
return false;
|
|
}
|
|
curl_close($ch);
|
|
// 处理API返回结果,只返回content内容
|
|
$data = json_decode($response, true);
|
|
if ($data['code'] == 0 && isset($data['choices'][0]['message']['content'])) {
|
|
return $data['choices'][0]['message']['content'];
|
|
}
|
|
log::info('调用讯飞星火失败',$data);
|
|
return false;
|
|
}
|
|
} |