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

SSEFormatter.php

57 lines1.7 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 RUN_ERROR chunk (AG-UI Protocol).
36 *
37 * @param \Throwable $error Exception to format
38 * @param string|null $runId Optional run ID for correlation
39 * @param string|null $model Optional model name
40 * @return string SSE-formatted RUN_ERROR chunk
41 */
42 public static function formatError(\Throwable $error, ?string $runId = null, ?string $model = null): string
43 {
44 $errorChunk = [
45 'type' => 'RUN_ERROR',
46 'runId' => $runId ?? ('run-' . bin2hex(random_bytes(4))),
47 'model' => $model,
48 'timestamp' => (int)(microtime(true) * 1000),
49 'error' => [
50 'message' => $error->getMessage(),
51 'code' => (string)$error->getCode()
52 ]
53 ];
54 return self::formatChunk($errorChunk);
55 }
57​