Thred SDK provides comprehensive streaming support for AI-generated responses, enabling real-time UI updates as content is generated. This creates a more engaging user experience, especially for longer responses.The SDK offers two streaming approaches:
Callback-based streaming with answerStream() - Best for simple real-time updates
Async generator streaming with answerStreamGenerator() - Best for fine-grained control
Streaming is particularly useful for long-form content where waiting for the complete response would create a poor user experience.
import { ThredClient } from '@thred-apps/thred-js';const client = new ThredClient({ apiKey: process.env.THRED_API_KEY!,});const metadata = await client.answerStream( { message: 'Explain agile project management in detail', model: 'gpt-4', }, (accumulatedText) => { // This callback is called multiple times as text streams in document.getElementById('response').textContent = accumulatedText; });// After streaming completes, you receive the full metadataconsole.log('Brand used:', metadata?.metadata.brandUsed?.name);
for await (const chunk of client.answerStreamGenerator({ message: 'What are cloud storage options for businesses?', model: 'gpt-4',})) { if (typeof chunk === 'string') { // This is accumulated text console.log('Current text:', chunk); updateUI(chunk); } else { // This is the final metadata object console.log('Brand:', chunk.metadata.metadata.brandUsed?.name); console.log('Similarity score:', chunk.metadata.metadata.similarityScore); }}
Long responses expected - Queries that will generate 200+ words
User engagement is critical - Interactive chat interfaces
Progressive rendering needed - Display content as it arrives
Perceived performance matters - Users see immediate feedback
// Good use case for streamingawait client.answerStream( { message: 'Write a comprehensive guide to project management', model: 'gpt-4', maxTokens: 2000, }, (text) => updateUI(text));
// Good use case for non-streamingconst response = await client.answer({ message: 'What is CRM?', model: 'gpt-3.5-turbo', maxTokens: 100,});console.log(response.response);
You can combine streaming with automatic DOM updates:
await client.answerStream( { message: 'Best accounting software for freelancers?', }, (text) => { // Manual update during streaming console.log('Streaming:', text.length, 'characters'); }, { text: 'response-container', // Auto-updated on completion link: 'affiliate-link', // Auto-updated on completion });
When using the targets parameter, the DOM elements are updated only after streaming completes, not during the stream. Use the callback for real-time updates.