1 基础
- 讯飞的大模型提供两种请求方式:http,wss;不同的模型支持的请求方式不同。
Spark xxx
系列的http请求鉴权比较简单,按官方文档即可。- wss请求和部分模型如
文本向量化
的http请求,需要构建header的authorization
,逻辑通用。
2 文本向量化接入
<?php
$config = [
'url' => 'https://emb-cn-huabei-1.xf-yun.com/',
'app_id' => '29dc7cfa',
'app_secret' => 'xxxxx',
'app_key' => 'xxxxx',
];
list($url, $header) = BuiltReq($config['url'], $config['app_key'], $config['app_secret']);
$messages[] = getMetaMessage("小明:成绩不好。小红:特长舞蹈生。小黄:街边黄毛。");
$data = BuiltParams($config['app_id'], $messages, "query");
$res = doCurl($url, $data, $header);
if ($res !== false) {
$res = json_decode($res, true);
var_dump($res);
}
function BuiltReq($url = "", $appKey = "", $appSecret = "") {
$urlInfo = parse_url($url);
date_default_timezone_set('UTC');
$date = date(DATE_RFC7231);
$query = [
"authorization" => CreateAuth($appKey, $appSecret, $urlInfo['host'], $urlInfo['path'], $date),
"date" => $date,
"host" => $urlInfo['host'],
];
$header = [
"X-Authorization:{$query['authorization']}",
"X-Date:{$query['date']}",
"X-Host:{$query['host']}",
];
return [$url."?".http_build_query($query), $header];
}
function CreateAuth($appKey = "", $appSecret = "", $host = "", $path = "",$date = "") {
$signatureTemp = "host: %s\ndate: %s\nPOST %s HTTP/1.1";
$signature = sprintf($signatureTemp, $host, $date, $path);
$signature = hash_hmac('sha256', $signature, $appSecret, true);
$signatureBase64 = base64_encode($signature);
$auth = <<<temp
api_key="{$appKey}", algorithm="hmac-sha256", headers="host date request-line", signature="{$signatureBase64}"
temp;
return base64_encode($auth);
}
function BuiltParams($appId = "", $messages = "", $domain = "para")
{
$content = json_encode(['messages' => $messages]);
$header = [
'app_id' => $appId,
'uid' => uniqid(),
'status' => 3,
];
$parameter = [
'emb' => [
'domain' => $domain,
'feature' => [
'encoding' => 'utf8',
],
],
];
$payload = [
'messages' => [
'format' => 'plain',
'text' => base64_encode($content),
],
];
return [
'header' => $header,
'parameter' => $parameter,
'payload' => $payload
];
}
function getMetaMessage($content = "", $role = "user")
{
return [
'content' => $content,
'role' => $role,
];
}
function doCurl($url = "", $data = [], $header = [])
{
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode($data),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array_merge($header, [
'Content-Type:application/json'
]),
]);
$res = curl_exec($ch);
$msg = "";
if ($res === false) {
$msg = curl_error($ch);
}
curl_close($ch);
if ($msg) {
echo $msg, "\n";
return false;
}
return $res;
}