fix stream error handling
This commit is contained in:
@@ -40,6 +40,10 @@ final readonly class AskSseController
|
||||
|
||||
return new StreamedResponse(
|
||||
function () use ($prompt, $clientId, $cookieResponse, $includeFullContext): void {
|
||||
@set_time_limit(0);
|
||||
@ini_set('output_buffering', 'off');
|
||||
@ini_set('zlib.output_compression', '0');
|
||||
|
||||
while (ob_get_level() > 0) {
|
||||
ob_end_flush();
|
||||
}
|
||||
@@ -49,7 +53,7 @@ final readonly class AskSseController
|
||||
}
|
||||
|
||||
echo "retry: 3000\n\n";
|
||||
flush();
|
||||
$this->sendComment('stream-open');
|
||||
|
||||
if ($prompt === '') {
|
||||
$this->sendEvent('error', 'Empty prompt');
|
||||
@@ -59,6 +63,10 @@ final readonly class AskSseController
|
||||
|
||||
try {
|
||||
foreach ($this->agentRunner->run($prompt, $clientId, $includeFullContext) as $chunk) {
|
||||
if (connection_aborted() === 1) {
|
||||
return;
|
||||
}
|
||||
|
||||
$chunk = str_replace(["\r\n", "\r"], "\n", $chunk);
|
||||
$this->sendData($chunk);
|
||||
}
|
||||
@@ -77,12 +85,18 @@ final readonly class AskSseController
|
||||
'Cache-Control' => 'no-cache, no-store, must-revalidate',
|
||||
'Connection' => 'keep-alive',
|
||||
'X-Accel-Buffering' => 'no',
|
||||
'X-Content-Type-Options' => 'nosniff',
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
private function sendData(string $data): void
|
||||
{
|
||||
if ($data === '') {
|
||||
$this->sendComment('keepalive');
|
||||
return;
|
||||
}
|
||||
|
||||
$lines = explode("\n", $data);
|
||||
|
||||
foreach ($lines as $line) {
|
||||
@@ -90,7 +104,7 @@ final readonly class AskSseController
|
||||
}
|
||||
|
||||
echo "\n\n";
|
||||
flush();
|
||||
$this->flushOutput();
|
||||
}
|
||||
|
||||
private function sendEvent(string $event, string $data): void
|
||||
@@ -99,6 +113,23 @@ final readonly class AskSseController
|
||||
|
||||
echo "event: {$event}\n";
|
||||
echo "data: {$safe}\n\n";
|
||||
flush();
|
||||
$this->flushOutput();
|
||||
}
|
||||
|
||||
private function sendComment(string $comment): void
|
||||
{
|
||||
$safe = str_replace(["\r", "\n"], ' ', $comment);
|
||||
|
||||
echo ': ' . $safe . "\n\n";
|
||||
$this->flushOutput();
|
||||
}
|
||||
|
||||
private function flushOutput(): void
|
||||
{
|
||||
if (function_exists('ob_flush')) {
|
||||
@ob_flush();
|
||||
}
|
||||
|
||||
@flush();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user