php请求大模型流的方式输出(打字机方式)
2025-05-21 本文已影响0人
Mracale
这个是nginx的设置,修改 Nginx 配置后,需重启 Nginx 使配置生效:
location ~ \.php(.*)$ {
# 禁用 FastCGI 缓冲(核心)
fastcgi_buffering off;
# 禁用代理缓冲
proxy_buffering off;
# 禁用压缩(避免压缩缓冲)
gzip off;
# 告诉 Nginx 不要缓冲此响应(Nginx 特有头)
add_header X-Accel-Buffering no;
# 其他常规配置(需与实际路径匹配)
root /var/www/html/test2/public;
fastcgi_pass unix:/run/php/php7.4-fpm.sock;
fastcgi_index index.php;
fastcgi_split_path_info ^(.+\.php)(.*)$;
fastcgi_param PATH_INFO $1;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
这个是php的文件
<?php
// 禁用 PHP 输出缓冲
@ini_set('output_buffering', 'off');
@ini_set('zlib.output_compression', 0);
@ini_set('implicit_flush', 1);
// 发送 HTTP 头,声明流式传输(分块编码)
header('Content-Type: text/plain');
header('Transfer-Encoding: chunked');
header('X-Accel-Buffering: no'); // 与 Nginx 配合,禁用缓冲
// Dify API 地址
$apiUrl = 'http://xxxxxxxxxx/v1/chat-messages';
// 你的 API Key
$apiKey = 'xxxxxxxxxxxxxxx';
// 构建请求数据
$requestData = [
'query' => '小区改造主要是指哪些',
'inputs' => [],
'response_mode' => 'streaming', // streaming 或者 blocking
"user" => "longhoocms"
];
if (isset($arr['conversation_id'])) {
$requestData['conversation_id'] = $arr['conversation_id'];
}
// 将请求参数转换为 JSON 格式
$jsonData = json_encode($requestData);
// 初始化 cURL
$ch = curl_init();
ob_end_flush();
flush();
// 设置 cURL 选项
curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false); // 不返回数据到变量
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_NOBODY, false); // 接收响应体
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // 跟随重定向
// 设置请求头
$headers = [
'Content-Type: application/json',
'Authorization: Bearer ' . $apiKey
];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// 设置回调函数处理流式数据
curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($ch, $data) {
echo $data;
ob_flush();
flush();
return strlen($data);
});
// 执行 cURL 请求
$result = curl_exec($ch);
// 检查是否有错误
if (curl_errno($ch)) {
echo 'data: Curl error: ' . curl_error($ch) . "\n\n";
ob_flush();
flush();
}
// 关闭 cURL
curl_close($ch);
?>