无依赖接入讯飞大模型

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', // appId
    '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);
}

/**
 * 构建文本向量化embedding的完整url 和 请求头信息
 * @param string $url 接口
 * @param string $appKey key
 * @param string $appSecret secret
 * @return array
 */
function BuiltReq($url = "", $appKey = "", $appSecret = "") {
    $urlInfo = parse_url($url);
    // 设定为0时区
    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];
}

/**
 * 通用的签名:按指定格式,生成验证签名
 * 部分模型仅在http下使用;部分模型仅在wss下使用
 * @param string $appKey
 * @param string $appSecret
 * @param string $host
 * @param string $path
 * @param string $date 请求时的时间;之后需要在限定间隔内完成请求,否则超时。
 * @return string
 */
function CreateAuth($appKey = "", $appSecret = "", $host = "", $path = "",$date = "") {
	// 此处注意请求方式POST/GET,按需修改
    $signatureTemp = "host: %s\ndate: %s\nPOST %s HTTP/1.1";
    $signature = sprintf($signatureTemp, $host, $date, $path);
    // 将加密后的二进制,用64进制表示
    $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);
}

/**
 * 构建文本向量化embedding的参数结构
 * 不同模型的body结构不同,可自行修改
 * @param string $appId
 * @param string $messages
 * @param string $domain
 * @return array
 */
function BuiltParams($appId = "", $messages = "", $domain = "para")
{
    $content = json_encode(['messages' => $messages]);

    $header = [
        'app_id' => $appId,
        'uid' => uniqid(),
        'status' => 3,
    ];
    $parameter = [
        'emb' => [
            'domain' => $domain, // query
            'feature' => [
                'encoding' => 'utf8',
            ],
        ],
    ];
    $payload = [
        'messages' => [
            'format' => 'plain',
            'text' => base64_encode($content),
        ],
    ];
    return [
        'header' => $header,
        'parameter' => $parameter,
        'payload' => $payload
    ];
}

/**
 * 用于辅助构建消息体
 * @param string $content
 * @param string $role
 * @return array|string[]
 */
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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值