Skip to content

Commit 1645be2

Browse files
committed
[Platform] Streamline RawHttpResult from streaming
Fix: - Skip SSE comments - Skip SSE errors - Drop manual JSON convert process - Use JSON decode from the ServerSentEvent
1 parent 326b88d commit 1645be2

File tree

1 file changed

+12
-19
lines changed

1 file changed

+12
-19
lines changed

src/platform/src/Result/RawHttpResult.php

Lines changed: 12 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -33,30 +33,23 @@ public function getData(): array
3333
public function getDataStream(): iterable
3434
{
3535
foreach ((new EventSourceHttpClient())->stream($this->response) as $chunk) {
36-
if ($chunk->isFirst() || $chunk->isLast() || ($chunk instanceof ServerSentEvent && '[DONE]' === $chunk->getData())) {
36+
// Handle only complete events (no need for handle DataChunk`s)
37+
if (!$chunk instanceof ServerSentEvent) {
3738
continue;
3839
}
3940

40-
$jsonDelta = $chunk instanceof ServerSentEvent ? $chunk->getData() : $chunk->getContent();
41-
42-
// Remove leading/trailing brackets
43-
if (str_starts_with($jsonDelta, '[') || str_starts_with($jsonDelta, ',')) {
44-
$jsonDelta = substr($jsonDelta, 1);
45-
}
46-
if (str_ends_with($jsonDelta, ']')) {
47-
$jsonDelta = substr($jsonDelta, 0, -1);
41+
// Do not handle: Init, Terminate, Errors, Comments and openAI specific termination via DONE
42+
if (
43+
$chunk->isFirst()
44+
|| $chunk->isLast()
45+
|| null !== $chunk->getError()
46+
|| str_starts_with($chunk->getContent(), ':')
47+
|| '[DONE]' === $chunk->getData()
48+
) {
49+
continue;
4850
}
4951

50-
// Split in case of multiple JSON objects
51-
$deltas = explode(",\r\n", $jsonDelta);
52-
53-
foreach ($deltas as $delta) {
54-
if ('' === trim($delta)) {
55-
continue;
56-
}
57-
58-
yield json_decode($delta, true, flags: \JSON_THROW_ON_ERROR);
59-
}
52+
yield $chunk->getArrayData();
6053
}
6154
}
6255

0 commit comments

Comments
 (0)