Real-time responses and controlled output for better UX
Implement streaming responses and token limits for better user experience
LLM generates tokens one at a time
Token is emitted as soon as it's generated
Your callback function is invoked with the new token
Terminal-based applications with real-time output
Browser-based streaming with server communication
TTFT < 500ms → Feels instant
Tok/s > 20 → Reads naturally
Problem: Stream interrupted
Solution: Wrap in try-catch, save partial response
Problem: User closes connection
Solution: Handle connection errors gracefully
Problem: Token limit reached mid-stream
Solution: Check if response is complete, handle truncation
Show loading state until first chunk arrives, then update in real-time
Streaming improves UX: Users see progress immediately
maxTokens controls cost: Prevents runaway generation
Token-by-token generation: LLMs produce one token at a time
onTextChunk callback: Your hook into the generation process