Basic Examples

Simple Agent
Beginner
Create a basic AI agent and generate speech. Perfect for getting started.
examples/simple-usage.js
Agent creation
Basic TTS
File generation
const { Agent } = require('ai-stream-sdk'); async function simpleExample() { // Create an agent const agent = new Agent({ id: 'my-bot', persona: { name: 'My AI Bot', bio: 'A simple AI assistant.' } }); console.log('āœ… Agent created:', agent.id); // Generate speech const textToSpeak = 'Hello! This is a simple demonstration.'; const audioPath = await agent.speak(textToSpeak); console.log('āœ… Audio generated:', audioPath); // Check file stats const fs = require('fs'); const stats = fs.statSync(audioPath); console.log('āœ… File size:', Math.round(stats.size / 1024), 'KB'); } simpleExample().catch(console.error);
Basic TTS
Beginner
Test different TTS providers and compare their output quality.
demo-all-tts.js
Multiple TTS providers
Quality comparison
Error handling
const { TTSAdapters } = require('ai-stream-sdk'); async function testAllTTS() { const providers = [ { name: 'Mock TTS', adapter: TTSAdapters.Mock }, { name: 'ElevenLabs', adapter: TTSAdapters.ElevenLabs }, { name: 'OpenAI TTS', adapter: TTSAdapters.OpenAI }, { name: 'Local TTS', adapter: TTSAdapters.Local } ]; for (const provider of providers) { try { console.log(`\nšŸŽ¤ Testing ${provider.name}...`); const audioPath = await provider.adapter.synthesizeToFile( 'Hello from ' + provider.name, `/tmp/test-${provider.name.toLowerCase().replace(' ', '-')}.wav` ); console.log(`āœ… ${provider.name}: ${audioPath}`); } catch (error) { console.log(`āŒ ${provider.name}: ${error.message}`); } } } testAllTTS().catch(console.error);
Basic Streaming
Intermediate
Stream audio and video to an RTMP endpoint. Requires a valid RTMP URL.
examples/rtmp-mvp/index.js
RTMP streaming
Image + audio
ffmpeg integration
require('dotenv').config(); const path = require('path'); const Agent = require('../../src/agent'); async function main() { const rtmpUrl = process.env.RTMP_URL; if (!rtmpUrl) { console.error('Set RTMP_URL in .env to stream'); process.exit(1); } const imagePath = process.env.IMAGE_PATH || path.join(__dirname, 'placeholder.png'); const agent = new Agent({ id: 'mvp-newsbot', persona: { name: 'MVP Bot' } }); console.log('Starting stream...'); const ff = await agent.startStream({ imagePath, text: 'Welcome to the MVP stream. This is a test.', rtmpUrl }); // Let it run for 20 seconds then stop setTimeout(() => { console.log('Stopping stream...'); agent.stopStream(); }, 20000); } main().catch(console.error);

AI Examples

AI Thinking
Intermediate
Use AI to generate intelligent responses and content.
examples/ai-powered-agent.js
LLM integration
AI responses
Multiple providers
const { Agent, LLMAdapters } = require('ai-stream-sdk'); async function aiThinkingExample() { const agent = new Agent({ id: 'ai-thinker', persona: { name: 'AI Thinker', bio: 'An intelligent AI that thinks deeply' } }); // Test AI thinking console.log('🧠 Testing AI thinking...'); const response = await agent.think('What are the latest trends in AI?'); console.log('AI Response:', response); // Test with different options const creativeResponse = await agent.think('Write a short poem about coding', { maxTokens: 100, temperature: 0.9 }); console.log('Creative Response:', creativeResponse); // Test direct LLM usage const mockLLM = new LLMAdapters.Mock(); const directResponse = await mockLLM.generate('Hello, how are you?'); console.log('Direct LLM:', directResponse); } aiThinkingExample().catch(console.error);
AI Speaking
Intermediate
Combine AI thinking with text-to-speech for intelligent voice responses.
AI + TTS
Voice responses
Custom options
const { Agent } = require('ai-stream-sdk'); async function aiSpeakingExample() { const agent = new Agent({ id: 'ai-speaker', persona: { name: 'AI Speaker', bio: 'An AI that thinks and speaks' } }); // AI thinks and speaks console.log('šŸŽ¤ AI thinking and speaking...'); const audioPath = await agent.thinkAndSpeak('Tell me a joke about programming'); console.log('Audio generated:', audioPath); // With custom options const customAudio = await agent.thinkAndSpeak('Explain quantum computing', { maxTokens: 200, temperature: 0.8, ttsOptions: { voice: 'alloy' } }); console.log('Custom audio:', customAudio); } aiSpeakingExample().catch(console.error);
AI Streaming
Advanced
Create AI-powered streaming content that generates and speaks intelligent responses.
AI content generation
Live streaming
Real-time AI
const { Agent } = require('ai-stream-sdk'); async function aiStreamingExample() { const agent = new Agent({ id: 'ai-streamer', persona: { name: 'AI Streamer', bio: 'An AI that streams intelligent content' } }); // AI-powered streaming console.log('šŸ“ŗ Starting AI-powered stream...'); await agent.startAIStream({ imagePath: '/path/to/image.png', prompt: 'Give a 30-second introduction about artificial intelligence', rtmpUrl: 'rtmp://live.twitch.tv/app/YOUR_KEY', llmOptions: { maxTokens: 200, temperature: 0.8 }, ttsOptions: { voice: 'alloy' } }); console.log('āœ… AI stream started successfully!'); } aiStreamingExample().catch(console.error);

Advanced Examples

News Bot
Advanced
Create an AI news bot that generates and streams news content.
News generation
Regular updates
Professional voice
const { Agent } = require('ai-stream-sdk'); class NewsBot extends Agent { constructor(options) { super(options); this.newsInterval = null; } async generateNews() { const topics = [ 'technology', 'science', 'business', 'entertainment', 'sports' ]; const topic = topics[Math.floor(Math.random() * topics.length)]; const prompt = `Generate a 30-second news segment about the latest ${topic} news. Make it engaging and informative.`; return await this.think(prompt, { maxTokens: 200 }); } async startNewsStream(rtmpUrl, imagePath) { console.log('šŸ“° Starting news stream...'); // Generate initial news const news = await this.generateNews(); await this.startStream({ imagePath, text: news, rtmpUrl }); // Update news every 2 minutes this.newsInterval = setInterval(async () => { try { const newNews = await this.generateNews(); console.log('šŸ“° Updating news:', newNews.substring(0, 50) + '...'); // In a real implementation, you'd update the stream } catch (error) { console.error('āŒ News update failed:', error.message); } }, 120000); } stopNewsStream() { if (this.newsInterval) { clearInterval(this.newsInterval); this.newsInterval = null; } this.stopStream(); } } // Usage const newsBot = new NewsBot({ id: 'news-bot', persona: { name: 'News Bot', bio: 'AI-powered news anchor' } }); newsBot.startNewsStream( 'rtmp://live.twitch.tv/app/YOUR_KEY', '/path/to/news-background.png' );
Interactive Bot
Advanced
Create an interactive bot that responds to chat messages and user input.
Chat integration
Real-time responses
Context awareness
const { Agent } = require('ai-stream-sdk'); class InteractiveBot extends Agent { constructor(options) { super(options); this.chatHistory = []; this.isStreaming = false; } async processChatMessage(message, user) { // Add to chat history this.chatHistory.push({ user, message, timestamp: Date.now() }); // Keep only last 10 messages if (this.chatHistory.length > 10) { this.chatHistory.shift(); } // Generate response const context = this.chatHistory .slice(-5) .map(msg => `${msg.user}: ${msg.message}`) .join('\n'); const prompt = `You are ${this.persona.name}. Respond to this chat message in character. Recent chat context:\n${context}\n\nNew message: ${user}: ${message}`; const response = await this.think(prompt, { maxTokens: 150 }); // Speak the response if (this.isStreaming) { await this.speak(response); } return response; } async startInteractiveStream(rtmpUrl, imagePath) { console.log('šŸ’¬ Starting interactive stream...'); this.isStreaming = true; // Start with introduction const intro = await this.think('Introduce yourself to the chat'); await this.startStream({ imagePath, text: intro, rtmpUrl }); // Simulate chat messages (in real app, connect to chat API) setTimeout(() => { this.processChatMessage('Hello! How are you?', 'viewer1'); }, 5000); setTimeout(() => { this.processChatMessage('What can you do?', 'viewer2'); }, 10000); } } // Usage const interactiveBot = new InteractiveBot({ id: 'interactive-bot', persona: { name: 'Chat Bot', bio: 'Interactive AI that responds to chat' } }); interactiveBot.startInteractiveStream( 'rtmp://live.twitch.tv/app/YOUR_KEY', '/path/to/chat-background.png' );