| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990 |
- <?php
- // 强制禁用所有缓冲
- while (ob_get_level()) ob_end_clean();
- header('X-Accel-Buffering: no');
- // 设置 SSE 头部
- header("Content-Type: text/event-stream");
- header("Cache-Control: no-cache");
- header("Connection: keep-alive");
- header("Access-Control-Allow-Origin: *");
- // 配置执行环境
- set_time_limit(0);
- ignore_user_abort(true);
- $content = $_GET['question'];
- $decodedData = strtr($content, '-_', '+/');
- // 使用 base64_decode 解码数据
- $content = base64_decode($decodedData).'请务必用中文回答我的问题。';
- $url = "http://8.137.127.56:5000/v1/chat/completions";
- $headers = array(
- "Content-Type: application/json"
- );
-
- $data = array(
- "messages" => array(
- array(
- "role" => "user",
- "content" => $content,
- )
- ),
- "mode" => "instruct",
- "instruction_template" => "Alpaca",
- "stream" => true,
- );
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, $url);
- curl_setopt($ch, CURLOPT_POST, true);
- curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
- curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, false); // 保持直接输出模式
- curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($ch, $data) {
- // 处理流式响应数据
- $lines = explode("\n", $data);
- foreach ($lines as $line) {
- if (strpos($line, 'data:') === 0) {
- // 转发原始SSE格式数据
- echo $line . "\n\n";
- ob_flush();
- flush();
- }
- }
- return strlen($data); // 必须返回处理的数据长度
- });
- // 错误处理
- curl_setopt($ch, CURLOPT_TIMEOUT, 86400);
- curl_setopt($ch, CURLOPT_FAILONERROR, true);
- // 执行请求
- try {
- curl_exec($ch);
-
- // 检查HTTP状态码
- $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
- if ($statusCode !== 200) {
- echo "event: error\ndata: HTTP Status {$statusCode}\n\n";
- ob_flush();
- flush();
- }
- } catch (Exception $e) {
- echo "event: error\ndata: " . $e->getMessage() . "\n\n";
- ob_flush();
- flush();
- }
- // 清理资源
- curl_close($ch);
- // 显式结束流
- echo "event: end\ndata: Stream ended\n\n";
- ob_flush();
- flush();
- exit;
|