aiChatStream
Stream AI responses in real-time with a callback function, ideal for UI updates and long responses.
Syntax
aiChatStream(messages, callback, params, options)Parameters
messages
any
Yes
The messages to pass to the AI model
callback
function
Yes
Function called with each chunk: function(chunk)
params
struct
No
Request parameters for the AI provider
options
struct
No
Request options (provider, apiKey, timeout, logging)
Options Structure
provider
string
(config)
The AI provider to use
apiKey
string
(config/env)
API key for the provider
timeout
numeric
30
Request timeout in seconds
logResponse
boolean
false
Log the response
logRequest
boolean
false
Log the request
Note: returnFormat is not used in streaming - chunks are passed directly to callback.
Returns
Returns void. All output is delivered through the callback function.
Examples
Basic Streaming
Build Complete Response
UI Integration
With Progress Tracking
Error Handling in Callback
Streaming with Parameters
Multiple Providers
Streaming to File
Server-Sent Events (SSE) Integration
Conversation Streaming
Callback Function Signature
Use Cases
✅ Long Responses
Provide immediate feedback for multi-paragraph responses.
✅ Real-Time UI Updates
Update chat interfaces as text arrives.
✅ Progress Indication
Show users that AI is "thinking" and generating.
✅ Server-Sent Events
Stream responses to browser clients.
✅ Token-by-Token Processing
Process response incrementally for real-time analysis.
❌ Short Responses
Use aiChat() for simple, quick requests.
❌ When You Need Complete Response First
Use aiChat() if you need full response before processing.
Notes
Real-time delivery: Chunks arrive as AI generates them
No buffering: Response not accumulated automatically - callback handles each chunk
Provider support: Not all providers support streaming (fallback to complete response)
No return format: Streaming always delivers raw text chunks
Flush recommended: Use
flushin callback to push content to client immediatelyError handling: Errors in callback don't stop stream - handle within callback
Thread blocking: Function blocks until stream complete
Related Functions
aiChat()- Synchronous, complete responseaiChatAsync()- Asynchronous with FutureaiAgent()- Agents support.stream()method
Performance Tips
Last updated