import React, { useState, useEffect } from 'react'; import { AIRouterProvider, useAIRouter, useAIRouterBatch, useAIRouterContext, generateViralPollRoute, generateTwitterPollRoute, analyzeArticleContextRoute, createOpenAIConfig, createWebLLMConfig, isWebLLMSupported, z } from '../src'; // Example 1: Advanced Configuration with Fallback Chain function AdvancedApp() { const [webLLMSupported, setWebLLMSupported] = useState(null); useEffect(() => { isWebLLMSupported().then(setWebLLMSupported); }, []); // Create configuration with intelligent fallback const config = { defaultProvider: createOpenAIConfig(process.env.REACT_APP_OPENAI_KEY || ''), fallbackProviders: webLLMSupported ? [ createWebLLMConfig('Llama-3.2-3B-Instruct-q4f32_1'), createWebLLMConfig('Llama-3.2-1B-Instruct-q4f32_1') ] : [], enableRetries: true, maxRetries: 2, timeout: 30000, validateOutput: true }; return (

Advanced AI Router Demo

); } // Example 2: Provider Status and Health Check function ProviderStatus() { const { config, isProviderAvailable } = useAIRouterContext(); const [providerTests, setProviderTests] = useState>({}); useEffect(() => { const testProviders = async () => { const tests = { openai: isProviderAvailable('openai'), webllm: isProviderAvailable('web-llm') }; setProviderTests(tests); }; testProviders(); const interval = setInterval(testProviders, 30000); // Test every 30s return () => clearInterval(interval); }, [isProviderAvailable]); return (

Provider Status

OpenAI {providerTests.openai ? '✅' : '❌'}
WebLLM {providerTests.webllm ? '✅' : '❌'}

Current Configuration

{JSON.stringify(config, null, 2)}
); } // Example 3: Batch Processing Multiple Articles function BatchProcessingDemo() { const { executeBatch, isLoading, errors, responses } = useAIRouterBatch(); const [results, setResults] = useState([]); const handleBatchProcessing = async () => { const articles = [ { url: 'https://example.com/ai-news', title: 'AI Startup Raises $100M Series A', summary: 'New company promises AGI breakthrough', news_site: 'tech-news.com', tags: ['ai', 'startup', 'funding'] }, { url: 'https://example.com/crypto-news', title: 'Bitcoin Hits New All-Time High', summary: 'BTC surges past previous records', news_site: 'crypto-daily.com', tags: ['bitcoin', 'crypto', 'ath'] }, { url: 'https://example.com/tech-news', title: 'Apple Announces Revolutionary VR Headset', summary: 'Vision Pro successor promises 8K per eye', news_site: 'apple-insider.com', tags: ['apple', 'vr', 'vision-pro'] } ]; try { const batchRequests = articles.map(article => ({ route: generateViralPollRoute, input: { article_data: article, perspective: 'balanced' as const, payment_token: 'FLOW' as const } })); const batchResults = await executeBatch(batchRequests); setResults(batchResults); } catch (error) { console.error('Batch processing failed:', error); } }; return (

Batch Processing Demo

{isLoading && (

Processing {responses.filter(Boolean).length}/3 articles...

)} {errors.some(Boolean) && (

Errors:

{errors.map((error, index) => error && (
Article {index + 1}: {error.message}
) )}
)} {results.length > 0 && (

Generated Polls:

{results.map((poll, index) => (

Article {index + 1}

{poll.question}

🚀 {poll.serial_optimism} 💀 {poll.pessimistic}
))}
)}
); } // Example 4: Custom Route Definition const CustomAnalysisRoute = { path: '/custom/sentiment-analysis', description: 'Custom sentiment analysis with market predictions', inputSchema: z.object({ text: z.string().min(10), domain: z.enum(['tech', 'finance', 'politics']) }), outputSchema: z.object({ sentiment: z.number().min(-1).max(1), confidence: z.number().min(0).max(1), key_themes: z.array(z.string()), market_prediction: z.string(), risk_factors: z.array(z.string()) }), systemPrompt: `You are a financial analyst AI. Analyze the given text and provide: 1. Sentiment score (-1 to 1) 2. Confidence in analysis (0 to 1) 3. Key themes identified 4. Market prediction based on content 5. Risk factors to consider Always respond with valid JSON matching the schema.`, temperature: 0.4, maxTokens: 800 }; function CustomRouteDemo() { const [input, setInput] = useState({ text: 'Fed announces dovish stance, markets rally on rate cut hopes', domain: 'finance' as const }); const { execute, isLoading, error, response } = useAIRouter(CustomAnalysisRoute); const handleAnalysis = async () => { try { const result = await execute(input); console.log('Custom analysis result:', result); } catch (err) { console.error('Analysis failed:', err); } }; return (

Custom Route Demo