@relayplane/sdk
Version:
RelayPlane SDK with zero-config AI access, intelligent model selection, built-in examples, and contextual error handling. The easiest way to add AI to your app with automatic optimization and fallback.
367 lines (300 loc) ⢠13.9 kB
JavaScript
#!/usr/bin/env node
/**
* RelayPlane SDK - Interactive Demo
*
* Run this script to experience all SDK features in an interactive guided demo.
* Perfect for new developers to understand capabilities in under 5 minutes.
*
* Usage: node examples/interactive-demo.js
*/
const RelayPlane = require('@relayplane/sdk');
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
function ask(question) {
return new Promise(resolve => rl.question(question, resolve));
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function main() {
console.log('šŖ Welcome to RelayPlane SDK Interactive Demo!');
console.log('āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā\n');
console.log('This demo will show you:');
console.log('⨠Zero-config AI magic');
console.log('š§ Intelligent model selection');
console.log('š Built-in examples library');
console.log('ā” Smart retry and error handling');
console.log('š§ Advanced configuration options\n');
// Check environment setup
console.log('š Checking your environment...');
const hasOpenAI = !!process.env.OPENAI_API_KEY;
const hasAnthropic = !!process.env.ANTHROPIC_API_KEY;
const hasGoogle = !!process.env.GOOGLE_API_KEY;
const hasRelayPlane = !!process.env.RELAY_API_KEY;
console.log(` OpenAI API Key: ${hasOpenAI ? 'ā
' : 'ā'}`);
console.log(` Anthropic API Key: ${hasAnthropic ? 'ā
' : 'ā'}`);
console.log(` Google API Key: ${hasGoogle ? 'ā
' : 'ā'}`);
console.log(` RelayPlane API Key: ${hasRelayPlane ? 'ā
' : 'ā'}\n`);
if (!hasOpenAI && !hasAnthropic && !hasGoogle && !hasRelayPlane) {
console.log('ā ļø No API keys detected. Some features will be simulated.');
console.log('š” To test with real AI models, set one of these environment variables:');
console.log(' export OPENAI_API_KEY="sk-..."');
console.log(' export ANTHROPIC_API_KEY="sk-ant-..."');
console.log(' export GOOGLE_API_KEY="..."');
console.log(' export RELAY_API_KEY="rp_..."');
console.log();
}
await ask('Press Enter to start the demo...');
console.clear();
// Demo 1: Zero-Config Magic
await demo1ZeroConfig();
// Demo 2: Built-in Examples
await demo2Examples();
// Demo 3: Error Handling
await demo3ErrorHandling();
// Demo 4: Advanced Features
await demo4Advanced();
// Conclusion
await demoConclusion();
rl.close();
}
async function demo1ZeroConfig() {
console.log('šŖ Demo 1: Zero-Config Magic');
console.log('āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā\n');
console.log('The RelayPlane SDK can automatically:');
console.log('⢠Detect your available API keys');
console.log('⢠Choose the best model for your task');
console.log('⢠Provide reasoning for its decisions');
console.log('⢠Handle fallbacks gracefully\n');
const question = await ask('Enter a question to ask the AI (or press Enter for default): ');
const prompt = question.trim() || 'Explain quantum computing in simple terms';
console.log(`\nš¤ Asking: "${prompt}"`);
console.log('ā³ Processing...\n');
try {
const startTime = Date.now();
const result = await RelayPlane.ask(prompt, {
budget: 'moderate',
priority: 'balanced',
taskType: 'general'
});
const duration = Date.now() - startTime;
console.log('ā
Response received!');
console.log(`š§ Model Selected: ${result.reasoning.selectedModel}`);
console.log(`š” Reasoning: ${result.reasoning.rationale}`);
console.log(`ā” Response Time: ${duration}ms`);
console.log(`š Answer: ${result.response.body}\n`);
} catch (error) {
console.log('ā Demo Error:', error.message);
console.log('š” This is expected if no API keys are configured.');
console.log(' The SDK would normally auto-detect and route to available models.\n');
}
await ask('Press Enter to continue to built-in examples...');
console.clear();
}
async function demo2Examples() {
console.log('š Demo 2: Built-in Examples Library');
console.log('āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā\n');
console.log('RelayPlane includes ready-to-use patterns for common tasks:');
console.log('1. š Summarization');
console.log('2. š Translation');
console.log('3. š Code Review');
console.log('4. š¬ Research');
console.log('5. š¬ Chatbot\n');
const choice = await ask('Choose an example (1-5) or press Enter for summarization: ');
const exampleChoice = choice.trim() || '1';
console.log('\nā³ Running example...\n');
try {
let result;
switch (exampleChoice) {
case '1':
console.log('š Summarization Example');
const longText = 'Artificial intelligence (AI) is intelligence demonstrated by machines, in contrast to the natural intelligence displayed by humans and animals. Leading AI textbooks define the field as the study of "intelligent agents": any device that perceives its environment and takes actions that maximize its chance of successfully achieving its goals. Colloquially, the term "artificial intelligence" is often used to describe machines that mimic "cognitive" functions that humans associate with the human mind, such as "learning" and "problem solving".';
result = await RelayPlane.examples.summarize(longText, { length: 'brief' });
console.log('ā
Summary:', result);
break;
case '2':
console.log('š Translation Example');
result = await RelayPlane.examples.translate('Hello, how are you today?', 'Spanish');
console.log('ā
Translation:', result);
break;
case '3':
console.log('š Code Review Example');
const code = 'function add(a, b) { return a + b; }';
result = await RelayPlane.examples.codeReview(code, { focus: 'best-practices' });
console.log('ā
Code Review:', result);
break;
case '4':
console.log('š¬ Research Example');
result = await RelayPlane.examples.research('Benefits of renewable energy');
console.log('ā
Research:', result);
break;
case '5':
console.log('š¬ Chatbot Example');
result = await RelayPlane.examples.chatbot('What can you help me with?', {
personality: 'helpful and friendly assistant'
});
console.log('ā
Chatbot Response:', result);
break;
default:
console.log('Invalid choice, showing summarization example...');
result = await RelayPlane.examples.summarize(longText, { length: 'brief' });
console.log('ā
Summary:', result);
}
} catch (error) {
console.log('ā Example Error:', error.message);
console.log('š” Examples require API keys to function.');
console.log(' In production, these would return real AI-generated content.\n');
}
await ask('\nPress Enter to continue to error handling demo...');
console.clear();
}
async function demo3ErrorHandling() {
console.log('š§ Demo 3: Smart Error Handling');
console.log('āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā\n');
console.log('RelayPlane provides intelligent error handling:');
console.log('⢠Contextual error messages');
console.log('⢠Helpful recovery suggestions');
console.log('⢠Automatic retry with backoff');
console.log('⢠Smart model fallbacks\n');
console.log('ā³ Simulating various error scenarios...\n');
// Simulate API key error
console.log('š Testing API Key Error Handling:');
try {
// This will likely fail without proper API keys
await RelayPlane.relay({
to: 'nonexistent-model',
payload: { messages: [{ role: 'user', content: 'test' }] }
});
} catch (error) {
if (error.getHelpfulMessage) {
console.log('ā
Contextual Error Message:');
console.log(error.getHelpfulMessage());
} else {
console.log('ā Standard Error:', error.message);
}
}
await sleep(1000);
// Show smart retry example
console.log('\nā” Smart Retry Example:');
try {
const result = await RelayPlane.smartRetry({
to: 'claude-sonnet-4-20250514',
payload: { messages: [{ role: 'user', content: 'Hello' }] }
}, {
maxRetries: 3,
retryOnFailureTypes: ['rate_limit', 'timeout', 'model_error']
});
console.log('ā
Smart retry succeeded!');
console.log('š Retry info:', result.retryInfo);
} catch (error) {
console.log('ā Smart retry demo error:', error.message);
console.log('š” In production, this would automatically try fallback models.');
}
await ask('\nPress Enter to continue to advanced features...');
console.clear();
}
async function demo4Advanced() {
console.log('š Demo 4: Advanced Features');
console.log('āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā\n');
console.log('Advanced SDK capabilities:');
console.log('⢠Multi-agent chaining');
console.log('⢠Batch processing');
console.log('⢠Streaming optimization');
console.log('⢠Cost management\n');
const feature = await ask('Choose feature to demo (chain/batch/stream/cost) or Enter for chain: ');
const featureChoice = feature.trim() || 'chain';
console.log(`\nā³ Demonstrating ${featureChoice}...\n`);
try {
switch (featureChoice.toLowerCase()) {
case 'chain':
console.log('š Multi-Agent Chaining Example');
const chainResult = await RelayPlane.chain({
steps: [
{ step: 'research', to: 'claude-3-5-haiku-20241022', prompt: 'Research AI trends' },
{ step: 'analyze', to: 'gpt-4o-mini', prompt: 'Analyze findings' },
{ step: 'summarize', to: 'claude-3-5-haiku-20241022', prompt: 'Create summary' }
],
input: 'Current state of AI development',
optimization: true
});
console.log('ā
Chain completed:', chainResult);
break;
case 'batch':
console.log('š¦ Batch Processing Example');
const batchResult = await RelayPlane.batch({
requests: [
{ to: 'claude-3-5-haiku-20241022', payload: { messages: [{ role: 'user', content: 'Hello' }] } },
{ to: 'gpt-4o-mini', payload: { messages: [{ role: 'user', content: 'Hi there' }] } }
],
parallel: true,
optimization: { enabled: true }
});
console.log('ā
Batch completed:', batchResult.length, 'responses');
break;
case 'stream':
console.log('š Streaming Optimization Example');
console.log('ā
Streaming would provide real-time chunks with:');
console.log(' ⢠Optimized chunk sizes');
console.log(' ⢠Typing indicators');
console.log(' ⢠Progress estimation');
console.log(' ⢠Real-time cost tracking');
break;
case 'cost':
console.log('š° Cost Management Example');
console.log('ā
Cost features include:');
console.log(' ⢠Real-time cost tracking');
console.log(' ⢠Budget limits');
console.log(' ⢠Cost-optimized model selection');
console.log(' ⢠Usage analytics');
break;
default:
console.log('š Showing chain example by default...');
console.log('ā
Multi-agent chains allow complex workflows');
}
} catch (error) {
console.log('ā Advanced feature demo error:', error.message);
console.log('š” Advanced features require API keys and may need RelayPlane account.');
}
await ask('\nPress Enter for conclusion...');
console.clear();
}
async function demoConclusion() {
console.log('š Demo Complete!');
console.log('āāāāāāāāāāāāāāāāāāāāāāā\n');
console.log('You\'ve experienced RelayPlane SDK\'s key features:');
console.log('ā
Zero-config AI access');
console.log('ā
Intelligent model selection');
console.log('ā
Built-in examples library');
console.log('ā
Smart error handling');
console.log('ā
Advanced orchestration\n');
console.log('š Next Steps:');
console.log('1. Install: npm install @relayplane/sdk');
console.log('2. Set your API keys (OpenAI, Anthropic, Google, or RelayPlane)');
console.log('3. Start with: RelayPlane.ask("Your question here")');
console.log('4. Explore examples: RelayPlane.examples.*');
console.log('5. Read docs: https://relayplane.com/docs/sdk\n');
console.log('š Example Files to Try:');
console.log('⢠examples/gpt-example.js - OpenAI integration');
console.log('⢠examples/claude-example.js - Anthropic integration');
console.log('⢠examples/optimize-example.js - Advanced optimization');
console.log('⢠examples/chained-agents.js - Multi-agent workflows\n');
console.log('š Get Help:');
console.log('⢠Documentation: https://relayplane.com/docs');
console.log('⢠GitHub: https://github.com/relayplane/sdk');
console.log('⢠Support: support@relayplane.com\n');
console.log('Thank you for trying RelayPlane SDK! šŖ');
}
// Handle Ctrl+C gracefully
process.on('SIGINT', () => {
console.log('\n\nš Demo interrupted. Thanks for trying RelayPlane SDK!');
rl.close();
process.exit(0);
});
// Run the demo
if (require.main === module) {
main().catch(console.error);
}
module.exports = { main };