Open History to see the last commit
1"""
2Server-Sent Events (SSE) formatting utilities for TanStack AI
3
4Provides utilities for formatting AG-UI StreamChunk objects into SSE-compatible
5event stream format for HTTP responses.
6"""
7import json
8import secrets
9import time
10from typing import Dict, Any, AsyncIterator, Iterator, Optional, Union
11
12
13def format_sse_chunk(chunk: Dict[str, Any]) -> str:
14 """
15 Format a StreamChunk dictionary as an SSE data line.
17 Args:
18 chunk: StreamChunk dictionary to format
20 Returns:
21 SSE-formatted string (e.g., "data: {...}\n\n")
22 """
23 return f"data: {json.dumps(chunk)}\n\n"
24
25
26def format_sse_done() -> str:
27 """
28 Format the SSE completion marker.
30 Returns:
31 SSE completion marker (e.g., "data: [DONE]\n\n")
32 """
33 return "data: [DONE]\n\n"
34
35
36def format_sse_error(
37 error: Exception,
38 run_id: Optional[str] = None,
39 model: Optional[str] = None
40) -> str:
41 """
42 Format an error as an SSE RUN_ERROR chunk (AG-UI Protocol).
44 Args:
45 error: Exception to format
46 run_id: Optional run ID for correlation
47 model: Optional model name
49 Returns:
50 SSE-formatted RUN_ERROR chunk
51 """
52 error_chunk = {
53 "type": "RUN_ERROR",
54 "runId": run_id or f"run-{secrets.token_hex(4)}",
55 "model": model,
56 "timestamp": int(time.time() * 1000),
57 "error": {
58 "message": str(error),
59 "code": getattr(error, "code", None) or type(error).__name__,
60 }
61 }
62 return format_sse_chunk(error_chunk)
63
64
65async def stream_chunks_to_sse(
66 chunks: Union[AsyncIterator[Dict[str, Any]], Iterator[Dict[str, Any]]]
67) -> AsyncIterator[str]:
68 """
69 Convert an async iterator of StreamChunk dictionaries to SSE format.
71 Args:
72 chunks: Async iterator or regular iterator of StreamChunk dictionaries
74 Yields:
75 SSE-formatted strings
76 """
77 if hasattr(chunks, '__aiter__'):
78 # Async iterator
79 async for chunk in chunks:
80 yield format_sse_chunk(chunk)
81 else:
82 # Regular iterator
83 for chunk in chunks:
84 yield format_sse_chunk(chunk)
86 yield format_sse_done()
87