/** * Streaming Example - Real-time Agent Responses * * This example demonstrates streaming responses from agents * for real-time output display. */ import { Studio } from '../src'; async function main() { const studio = new Studio({ apiKey: process.env.LYZR_API_KEY }); try { // Create a streaming agent console.log('Creating streaming agent...'); const agent = await studio.createAgent({ name: 'Storyteller', provider: 'gpt-4o', role: 'Creative storyteller', goal: 'Tell engaging stories', instructions: 'Tell a detailed and engaging story' }); console.log('✓ Agent created\n'); // Stream response - Method 1: AsyncIterable with for-await-of console.log('Streaming response (Method 1: for-await-of):\n'); console.log('---'); for await (const chunk of await agent.run('Tell a short science fiction story', { stream: true })) { // Print each chunk as it arrives process.stdout.write(chunk.content); } console.log('\n---\n'); // Stream response - Method 2: With handler console.log('Streaming response (Method 2: with handler):\n'); console.log('---'); let totalChunks = 0; let totalLength = 0; for await (const chunk of await agent.run('Tell me about the future of AI', { stream: true })) { totalChunks++; totalLength += chunk.content.length; process.stdout.write(chunk.content); } console.log('\n---\n'); console.log(`Total chunks: ${totalChunks}`); console.log(`Total characters: ${totalLength}`); // Stream with metadata console.log('\n\nStreaming with metadata tracking:\n'); console.log('---'); let chunkIndex = 0; for await (const chunk of await agent.run('List 5 reasons why TypeScript is great', { stream: true })) { chunkIndex++; process.stdout.write(chunk.content); if (chunk.done) { console.log('\n---'); console.log(`Stream complete after ${chunkIndex} chunks`); } } // Collect entire stream into single response console.log('\n\nCollecting full stream:\n'); console.log('---'); let fullResponse = ''; for await (const chunk of await agent.run('Explain quantum computing simply', { stream: true })) { fullResponse += chunk.content; } console.log(fullResponse); console.log('---\n'); // Clean up await agent.delete(); console.log('✓ Agent deleted'); } catch (error) { console.error('Error:', error); process.exit(1); } } main();