Streaming:流式响应
摘要较长时,用户可能等待数秒才能看到内容。流式响应让应用在生成过程中逐段展示结果,改善等待体验;它不保证模型计算更少,也不自动降低费用。
本节延续帖子摘要应用。上游使用 Responses API 的 SSE,Laravel 将其解析为少量业务事件,再以 NDJSON 发给浏览器。两段连接使用不同协议,目的是让页面只处理自己的展示事件。
先认识事件边界
上游 SSE 文本可能是这样:
event: response.output_text.delta
data: {"type":"response.output_text.delta","delta":"需要核对"}
event: response.output_text.delta
data: {"type":"response.output_text.delta","delta":"环境变量。"}
空行结束一条事件。但一次网络读取可能只拿到半行,也可能拿到多条事件。UTF-8 字符也可能跨网络分块,不能对每个分块直接执行 JSON.parse()。官方流式说明
配套 SseDecoder.php 保存未完成的行,兼容 LF 与 CRLF,将多条 data: 行拼接后再交给 JSON 解析。它只实现本例所需的 data 解析,不是包含自动重连、Last-Event-ID 等能力的完整 SSE 客户端。
后端需要识别哪些状态
本例根据 JSON 的 type 字段处理事件:文本增量转成 delta;生成完成后转成 done;失败、不完整或错误转成 error。未知的中间事件忽略,不能把它们误判为完成。流式事件参考
浏览器收到的是本应用定义的逐行 JSON:
{"type":"delta","text":"需要核对"}
{"type":"delta","text":"环境变量。"}
{"type":"done"}
连接断开与生成完成不是同一件事。没有收到完成事件就断流,应保留部分文字并显示“未完成”,不能展示成功提示。
Laravel 接通真实上游
配套 StreamSummaryController.php 使用 PHP cURL 的写入回调接收上游数据,需要启用 ext-curl。它复用上一节的 Key、模型和 Prompt 配置,不设置自动重试。
核心流程如下,实际配置、异常处理、超时和资源清理见配套完整文件:
校验输入与服务配置
↓
开始 Laravel 流式响应
↓
cURL 向上游发送 stream=true 请求
↓
SSE 解码器积累完整事件
↓
识别增量、完成和失败
↓
逐行发送业务 JSON,及时刷新输出
客户端断开时,回调尝试结束上游读取;这不能保证上游没有继续生成或不计费。超时则按未完成处理,不能原地重启一次请求并把新文本接到旧文本后面。
Laravel 响应设置 application/x-ndjson,并发送 X-Accel-Buffering: no。PHP 输出缓冲、反向代理、压缩和 CDN 仍可能影响实际效果,需要在部署链路验证。Laravel 流式响应
页面为什么使用 fetch
浏览器原生 EventSource 适合订阅 GET 事件流;本例需要 POST 提交帖子并携带 CSRF,因此使用 fetch 读取响应体。
配套页面 ai-summary.blade.php 使用 TextDecoder 的流模式解码字节,保存跨分块的不完整行,逐行解析 JSON。下面只展示关键思想:
const decoder = new TextDecoder();
let buffer = '';
// value 来自 response.body.getReader().read()
buffer += decoder.decode(value, {stream: true});
// 从 buffer 中逐个取出以换行结束的完整 JSON;残余留给下一轮。
页面用 textContent 展示文本,不把模型输出直接作为 HTML 插入。若以后展示 Markdown,应使用合适的解析与 HTML 清洗策略。
装入上一节的应用
合并配套控制器、解码器和视图,再把 routes.example.php 中的路由合并到 routes/web.php。已有登录功能的项目,可登录后打开 /ai/summary,提交测试帖子。配套页面包含生成、停止和状态提示。
首次联调先提交一段足以生成多段输出的测试内容;输出很短时,即使启用流式,也可能看不出明显差异。不要用定时拆分完整答案来冒充真实上游流式。
错误发生在响应头以后怎么办
输入校验可以在开始流之前返回正常 HTTP 错误。但响应头已经发出后,再发生上游故障,通常不能改写为新的 502 状态。本例在流内发送 error,由页面更新状态。
这也意味着监控不能只统计 HTTP 200。还要记录流的最终业务状态,以及是否收到上游完成事件。配套示例在完成事件中记录 usage;中断时没有可靠用量,就标记未知,不能记为零。
本节验收
测试正常完成、中途停止、上游失败,以及生成过程中连接意外结束。每一种状态都要能在界面区分;停止或失败后,按钮应恢复,用户不需要刷新页面才能继续。
完整配套代码
以下文件与压缩包中的示例一致。可按标注路径合并到已有项目;配置与登录前提见上文。
app/Support/SseDecoder.php
<?php
namespace App\Support;
use RuntimeException;
// 本章仅解析上游 SSE 的 data 字段,事件类型由 JSON 内的 type 判断。
final class SseDecoder
{
private string $buffer = '';
private array $data = [];
private int $eventBytes = 0;
public function push(string $chunk): array
{
$this->buffer .= $chunk;
$events = [];
while (($position = strpos($this->buffer, "\n")) !== false) {
$line = substr($this->buffer, 0, $position);
$this->buffer = substr($this->buffer, $position + 1);
$line = str_ends_with($line, "\r") ? substr($line, 0, -1) : $line;
$this->eventBytes += strlen($line);
if ($this->eventBytes > 2 * 1024 * 1024) {
throw new RuntimeException('流式事件过大');
}
if ($line === '') {
if ($this->data !== []) {
$events[] = implode("\n", $this->data);
}
$this->data = [];
$this->eventBytes = 0;
} elseif (str_starts_with($line, 'data:')) {
$value = substr($line, 5);
$this->data[] = str_starts_with($value, ' ') ? substr($value, 1) : $value;
}
}
if (strlen($this->buffer) > 2 * 1024 * 1024) {
throw new RuntimeException('流式行过大');
}
return $events;
}
}
app/Http/Controllers/StreamSummaryController.php
<?php
namespace App\Http\Controllers;
use App\Services\PostSummary;
use App\Support\SseDecoder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use RuntimeException;
use Throwable;
final class StreamSummaryController extends Controller
{
public function __invoke(Request $request, PostSummary $summary)
{
$validated = $request->validate(['post' => ['required', 'string', 'max:10000']]);
// 配置与编码错误应在发出流式响应头之前暴露。
$key = $summary->key();
$payload = json_encode($summary->payload($validated['post']) + ['stream' => true], JSON_THROW_ON_ERROR);
return response()->stream(function () use ($key, $payload): void {
$emit = static function (array $event): void {
echo json_encode($event, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR)."\n";
if (ob_get_level() > 0) {
ob_flush();
}
flush();
};
$decoder = new SseDecoder();
$terminal = false;
$callbackError = null;
$curl = curl_init('https://api.openai.com/v1/responses');
try {
curl_setopt_array($curl, [
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer '.$key,
'Content-Type: application/json',
'Accept: text/event-stream',
],
CURLOPT_POSTFIELDS => $payload,
CURLOPT_CONNECTTIMEOUT => 5,
CURLOPT_TIMEOUT => 90,
CURLOPT_WRITEFUNCTION => static function ($handle, string $chunk) use (
$decoder, $emit, &$terminal, &$callbackError
): int {
try {
if (connection_aborted()) {
return 0;
}
$status = curl_getinfo($handle, CURLINFO_HTTP_CODE);
if ($status < 200 || $status >= 300) {
throw new RuntimeException('上游 HTTP 请求失败');
}
foreach ($decoder->push($chunk) as $data) {
if ($terminal) {
continue;
}
$event = json_decode($data, true, 512, JSON_THROW_ON_ERROR);
$type = $event['type'] ?? '';
if ($type === 'response.output_text.delta') {
$emit(['type' => 'delta', 'text' => $event['delta']]);
} elseif ($type === 'response.completed') {
// 同时识别空回答与拒答,不把 completed 一概当作可展示答案。
\App\Support\ResponseText::extract($event['response']);
Log::info('ai.summary.stream.completed', [
'response_id' => $event['response']['id'] ?? null,
'usage' => $event['response']['usage'] ?? null,
]);
$emit(['type' => 'done']);
$terminal = true;
} elseif (in_array($type, ['response.failed', 'response.incomplete', 'error'], true)) {
throw new RuntimeException('上游生成未完成');
}
}
return strlen($chunk);
} catch (Throwable $error) {
$callbackError = $error;
return 0;
}
},
]);
$ok = curl_exec($curl);
if ($callbackError || $ok === false || !$terminal) {
throw new RuntimeException('流中断或缺少完成事件');
}
} catch (Throwable $error) {
Log::warning('ai.summary.stream.failed', ['exception_type' => get_class($error)]);
if (!$terminal && !connection_aborted()) {
$emit(['type' => 'error', 'message' => '生成未完成,已有文字仅为部分结果。']);
}
} finally {
curl_close($curl);
}
}, 200, [
'Content-Type' => 'application/x-ndjson; charset=utf-8',
'Cache-Control' => 'no-cache, no-store',
'X-Accel-Buffering' => 'no',
]);
}
}
resources/views/ai-summary.blade.php
<!doctype html>
<html lang="zh-CN">
<meta charset="utf-8">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>帖子摘要示例</title>
<textarea id="post" rows="8" cols="70" maxlength="10000" placeholder="粘贴测试帖子"></textarea>
<p><button id="generate">生成流式摘要</button> <button id="stop" disabled>停止</button></p>
<p id="status" role="status"></p>
<pre id="result" style="white-space:pre-wrap"></pre>
<script>
const button = document.querySelector('#generate');
const stop = document.querySelector('#stop');
const result = document.querySelector('#result');
const status = document.querySelector('#status');
let controller;
stop.onclick = () => controller?.abort();
button.onclick = async () => {
button.disabled = true;
stop.disabled = false;
result.textContent = '';
status.textContent = '正在生成';
controller = new AbortController();
let terminal = false;
let reader;
try {
const response = await fetch('/ai/summary/stream', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/x-ndjson, application/json',
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
},
body: JSON.stringify({post: document.querySelector('#post').value}),
signal: controller.signal,
});
if (!response.ok || !response.body || !response.headers.get('content-type')?.includes('application/x-ndjson')) {
throw new Error(`请求失败(HTTP ${response.status}),请检查登录、输入或稍后重试。`);
}
reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
function consume(text) {
buffer += text;
let position;
while ((position = buffer.indexOf('\n')) >= 0) {
const line = buffer.slice(0, position);
buffer = buffer.slice(position + 1);
if (!line.trim()) continue;
const event = JSON.parse(line);
if (event.type === 'delta') result.textContent += event.text;
if (event.type === 'error') throw new Error(event.message);
if (event.type === 'done') terminal = true;
}
}
while (true) {
const {value, done} = await reader.read();
if (done) break;
consume(decoder.decode(value, {stream: true}));
}
consume(decoder.decode());
if (buffer.trim() || !terminal) throw new Error('连接中断,摘要未完成。');
status.textContent = '已完成';
} catch (error) {
status.textContent = error.name === 'AbortError' ? '已停止,当前内容可能不完整。' : error.message;
} finally {
await reader?.cancel().catch(() => {});
button.disabled = false;
stop.disabled = true;
}
};
</script>
</html>
需要合并的路由
<?php
// 将这些路由合并到已有项目的 routes/web.php;不覆盖现有路由。
use App\Http\Controllers\PostSummaryController;
use App\Http\Controllers\StreamSummaryController;
use Illuminate\Support\Facades\Route;
Route::middleware(['auth', 'throttle:10,1'])->group(function () {
Route::view('/ai/summary', 'ai-summary');
Route::post('/ai/summary', PostSummaryController::class);
Route::post('/ai/summary/stream', StreamSummaryController::class);
});
一站式AI产品经理入门指南
关于 LearnKu