PHP/WordPress 调用阿里云通义千问 API

一开始我就问一下通义千问自己,能不能自己给自己写个代码。通义千问当然给了答案,但是无法使用,接口地址什么都是错误的。同样的问题丢字节旗下的豆包,及百度的一言,结果都是错的。最后还是自己手工写了一个:


/**
 * @link https://help.aliyun.com/zh/dashscope/developer-reference/api-details
 * 
 */
$url = 'https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation';
$headers = [
    'Content-Type' => 'application/json',
    'Authorization' => 'Bearer {apikey}',
];

$body = [
    'model' => 'qwen-v1',
    // 'model' => 'qwen-plus-v1',
    'input' => ['prompt' => '你是谁?'],
];

$res = wp_remote_post($url, ['headers' => $headers, 'body' => json_encode($body, JSON_UNESCAPED_UNICODE)]);

$data = json_decode($res['body'], true);
if (isset($data['code'])) {
    $msg  = $data['code'] . ' : ' . $data['message'];
    throw new Exception($msg);
}

$answer = $data['output']['text'];
echo $answer;

这个请求倒是异常简单,连常用的签名都不需要了,直接就是在头部添加一个秘钥就行了。