Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

SSEFormatter.php

52 lines1.3 KB

1<?php
2​
3namespace TanStack\AI;
4​
5/**
6 * Server-Sent Events (SSE) formatting utilities for TanStack AI
7 *
8 * Provides utilities for formatting StreamChunk objects into SSE-compatible
9 * event stream format for HTTP responses.
10 */
11class SSEFormatter
13 /**
14 * Format a StreamChunk array as an SSE data line.
15 *
16 * @param array $chunk StreamChunk array to format
17 * @return string SSE-formatted string (e.g., "data: {...}\n\n")
18 */
19 public static function formatChunk(array $chunk): string
20 {
21 return "data: " . json_encode($chunk, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\n\n";
22 }
23​
24 /**
25 * Format the SSE completion marker.
26 *
27 * @return string SSE completion marker (e.g., "data: [DONE]\n\n")
28 */
29 public static function formatDone(): string
30 {
31 return "data: [DONE]\n\n";
32 }
33​
34 /**
35 * Format an error as an SSE error chunk.
36 *
37 * @param \Throwable $error Exception to format
38 * @return string SSE-formatted error chunk
39 */
40 public static function formatError(\Throwable $error): string
41 {
42 $errorChunk = [
43 'type' => 'error',
44 'error' => [
45 'type' => get_class($error),
46 'message' => $error->getMessage()
47 ]
48 ];
49 return self::formatChunk($errorChunk);
50 }
52​