1.注册deepseek并新建密钥
2 php服务端代码
$json = file_get_contents('php://input');
$jsonData = json_decode($json, true);
$datas= ['model'=>'deepseek-chat','messages'=>[['role'=>'user','content'=>$jsonData['content']]],'stream'=>true];
send('https://api.deepseek.com/chat/completions',$datas,'handleResponseData');
function send(string $url,$postdata,callable $callback){$curl = curl_init();curl_setopt($curl, CURLOPT_URL, $url);curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // 返回结果而不是直接输出$headers = ["Content-Type: application/json", // 设置内容类型为JSON"Authorization: Bearer sk-69**************9d" // 设置认证头信息,例如Bearer Token];curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); // 设置头信息curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($postdata));curl_setopt($curl, CURLOPT_WRITEFUNCTION, function ($curl, $data) use ($callback) {// 调用回调函数处理数据$callback($data);return strlen($data); // 返回接收到的数据长度});$response = curl_exec($curl); // 执行请求并获取响应if ($response === false) {echo 'Curl error: ' . curl_error($curl); // 检查是否有错误发生}curl_close($curl); // 关闭cURL会话//echo "123";
}function handleResponseData($data) {echo $data;flush(); // 刷新输出缓冲区
}
流式输出有几个关键点
1.报文stream为true
2.curl 开启 CURLOPT_RETURNTRANSFER,使用CURLOPT_WRITEFUNCTION处理返回数据
3前端代码
<body>
<div id="app"></div>
</body>
<script>
reading();
async function reading(){const resp =await fetch('http://localhost/test.php',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({content:'如何评价自由高达的机设'}),dataType:"text/event-stream"})const reader=resp.body.getReader()const decoder=new TextDecoder()let container = document.getElementById('app');while(1){const {done,value}=await reader.read()if(done){break;}let txt=decoder.decode(value)let output = handleData(txt);container.innerHTML+=output;}
}function handleData(dataString){const regex = /"content":"([^"]*)"/g;let matches;let finalStr='';while ((matches = regex.exec(dataString)) !== null) {finalStr+=matches[1];}//转换行let s = finalStr.replace(/\\n/g, '<br>');return s;}</script>
前端难点是处理报文,因为deepseek返回的块状数据是这样,我不知道这种具体是什么格式,所以只能用正则把它取下来
data: {"id":"bbadf0e5-3ed5-417a-89f7-146a4869c15d","object":"chat.completion.chunk","created":1743091685,"model":"deepseek-chat","system_fingerprint":"fp_3d5141a69a_prod0225","choices":[{"index":0,"delta":{"content":"am"},"logprobs":null,"finish_reason":null}]}