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}]}
相关推荐
byxdaz11 分钟前
Qt中绘制不规则控件
开发语言·qt
繁星蓝雨12 分钟前
Qt使用QGraphicsView绘制线路图————附带详细实现代码
开发语言·qt
martian66515 分钟前
《Spring Boot全栈开发指南:从入门到生产实践》
java·开发语言·spring boot
规划GIS会26 分钟前
ima知识库第二弹,Python for ArcGIS Pro | 简简单单写个脚本工具
开发语言·python·arcgis
tpoog30 分钟前
[MySQL]数据类型
android·开发语言·数据库·mysql·算法·adb·贪心算法
louisgeek32 分钟前
Android View TouchDelegate
android
fengchengwu201234 分钟前
python下载m3u8格式视频
开发语言·python·m3u8
VBA63371 小时前
VBA代码解决方案第二十三讲 EXCEL中,如何删除工作表中的空白行
开发语言
sukida1001 小时前
Firefox 浏览器同步一个账户和书签网址
android·linux·firefox
每次的天空1 小时前
Android 单例模式全解析:从基础实现到最佳实践
android·单例模式