<?php
//失败:{"code":"InvalidParameter","message":"Model not exist.","request_id":"7456c1f4-6261-9b4a-a037-e2f752a3ab56"}
//成功:{"output":{"choices":[{"message":{"content":"创建","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":11,"input_tokens":10,"output_tokens":1},"request_id":"e44ed988-45f2-9c6f-9611-6db897243493"}
qianwen();
function qianwen(){
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('X-Accel-Buffering: no');
header('Connection: keep-alive');
set_time_limit(0);
ob_end_clean();
ob_implicit_flush(1);
$openai_api_key = 'sk-********************';//替换为自己的api_key
$url = 'https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation';
$headers = [
'Authorization: Bearer ' . $openai_api_key,
'Content-Type: application/json',
'X-DashScope-SSE: enable'
];
$params = [
'model' => 'qwen-max',
'input' => ['messages' => []],
'parameters' => [
'result_format'=>'message',
'incremental_output'=>true
],
];
$params['input']['messages'][] = [
'role' => 'user',
'content' => '生成劳动合同'
];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//有时候希望返回的内容作为变量储存,而不是直接输出。这个时候就必需设置curl的CURLOPT_RETURNTRANSFER选项为1或true。
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);//设置这个选项为一个非零值(象 “Location: “)的头,服务器会把它当做HTTP头的一部分发送(注意这是递归的,PHP将发送形如 “Location: “的头)。
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//curl_exec()获取的信息以文件流的形式返回,而不是直接输出
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_WRITEFUNCTION, function ($ch, $data) {
$res = substr(explode("\n",$data)[3],5);
$res = json_decode($res,true);
if($res['output']){
echo $res['output']['choices'][0]['message']['content'];
}else{
echo $res['message'];
}
// echo $data;
return strlen($data);
});
curl_exec($ch);
curl_close($ch);
}