php调用deepseek接口api并流式输出

1.注册deepseek并新建密钥

2 php服务端代码

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前端代码

html 复制代码
<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返回的块状数据是这样,我不知道这种具体是什么格式,所以只能用正则把它取下来

html 复制代码
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}]}
相关推荐
Wish3D44 分钟前
阿里云OSS 上传文件 Python版本
开发语言·python·阿里云
凤年徐44 分钟前
【数据结构初阶】单链表
c语言·开发语言·数据结构·c++·经验分享·笔记·链表
oioihoii1 小时前
C++11 右值引用:从入门到精通
开发语言·c++
痴人说梦梦中人4 小时前
自建 dnslog 回显平台:渗透测试场景下的隐蔽回显利器
web安全·网络安全·渗透测试·php·工具
朝新_4 小时前
【多线程初阶】阻塞队列 & 生产者消费者模型
java·开发语言·javaee
立莹Sir4 小时前
Calendar类日期设置进位问题
java·开发语言
doublelixin4 小时前
AOSP (Android11) 集成Google GMS三件套
android
风逸hhh5 小时前
python打卡day46@浙大疏锦行
开发语言·python
火兮明兮5 小时前
Python训练第四十三天
开发语言·python
ascarl20106 小时前
准确--k8s cgroup问题排查
java·开发语言