Polyglot \ Streaming
Advanced Stream Processing
How to use advanced stream processing features in Polyglot
Using Callbacks
You can use the onPartialResponse
method to register a callback that is called for each partial response:
Transforming Stream Content
You can process and transform the content as it streams:
Processing JSON Streams
For streaming JSON responses, you need to accumulate content until you have valid JSON:
Cancellation
In some cases, you may want to stop the generation early:
Note that when you break out of the loop, the request to the provider continues in the background, but your application stops processing the response.
Performance Considerations
When working with streaming responses, keep these performance considerations in mind:
- Memory Usage: Be careful with how you accumulate content, especially for very long responses
- Buffer Flushing: In web applications, make sure output buffers are properly flushed
- Connection Stability: Streaming connections can be more sensitive to network issues
- Timeouts: Adjust timeout settings for long-running streams
Here’s an example of memory-efficient processing for very long responses: