Open History to see the last commit
1"""
2Server-Sent Events (SSE) formatting utilities for TanStack AI
3
4Provides utilities for formatting StreamChunk objects into SSE-compatible
5event stream format for HTTP responses.
6"""
7import json
8from typing import Dict, Any, AsyncIterator, Iterator, Union
9
10
11def format_sse_chunk(chunk: Dict[str, Any]) -> str:
12 """
13 Format a StreamChunk dictionary as an SSE data line.
15 Args:
16 chunk: StreamChunk dictionary to format
18 Returns:
19 SSE-formatted string (e.g., "data: {...}\n\n")
20 """
21 return f"data: {json.dumps(chunk)}\n\n"
22
23
24def format_sse_done() -> str:
25 """
26 Format the SSE completion marker.
28 Returns:
29 SSE completion marker (e.g., "data: [DONE]\n\n")
30 """
31 return "data: [DONE]\n\n"
32
33
34def format_sse_error(error: Exception) -> str:
35 """
36 Format an error as an SSE error chunk.
38 Args:
39 error: Exception to format
41 Returns:
42 SSE-formatted error chunk
43 """
44 error_chunk = {
45 "type": "error",
46 "error": {
47 "type": type(error).__name__,
48 "message": str(error)
49 }
50 }
51 return format_sse_chunk(error_chunk)
52
53
54async def stream_chunks_to_sse(
55 chunks: Union[AsyncIterator[Dict[str, Any]], Iterator[Dict[str, Any]]]
56) -> AsyncIterator[str]:
57 """
58 Convert an async iterator of StreamChunk dictionaries to SSE format.
60 Args:
61 chunks: Async iterator or regular iterator of StreamChunk dictionaries
63 Yields:
64 SSE-formatted strings
65 """
66 if hasattr(chunks, '__aiter__'):
67 # Async iterator
68 async for chunk in chunks:
69 yield format_sse_chunk(chunk)
70 else:
71 # Regular iterator
72 for chunk in chunks:
73 yield format_sse_chunk(chunk)
75 yield format_sse_done()
76