This directory contains comprehensive, production-ready code examples for the Oshun AI provider integrations. These examples demonstrate best practices for using ElevenLabs, ComfyUI/RunComfy, and Civitai APIs.
Available Examples#
ElevenLabs (elevenlabs-examples.ts)#
Text-to-speech synthesis and voice management:
| Section | Topics Covered |
|---|---|
| 1. Configuration | Basic & advanced initialization |
| 2. Synthesis | Basic TTS, voice settings, models, audio tags, long-form |
| 3. Streaming | WebSocket sessions, interactive streaming |
| 4. Voice Management | List, get, filter, select voices |
| 5. Voice Cloning | Instant cloning, quality validation |
| 6. Voice Design | Generate custom voices from descriptions |
| 7. Error Handling | Error types, retry patterns |
| 8. Monitoring | Statistics, health checks |
| 9. Cleanup | Proper shutdown, resource management |
| 10. Complete Example | Full voice assistant implementation |
ComfyUI/RunComfy (comfyui-examples.ts)#
Workflow execution and image generation:
| Section | Topics Covered |
|---|---|
| 1. Configuration | Basic & advanced initialization |
| 2. Workflows | txt2img, img2img, LoRA, inpainting, ControlNet |
| 3. Batch Processing | Parallel execution, progress tracking, rate limiting |
| 4. Job Management | Status, cancellation, history, timeouts |
| 5. Resources | Models, custom nodes, credits |
| 6. Validation | Workflow validation, cost estimation |
| 7. Error Handling | Error types, retry logic |
| 8. Monitoring | Analytics, queue status, health checks |
| 9. Advanced | Pipelines, A/B testing, seed variations |
| 10. Cleanup | Proper shutdown, auto-cleanup factories |
Civitai (civitai-examples.ts)#
Model discovery and generation:
| Section | Topics Covered |
|---|---|
| 1. Configuration | Basic & advanced initialization |
| 2. Model Discovery | Search, details, hashes, categories, creators, tags |
| 3. Image Generation | AIR URNs, LoRA, quality presets, img2img, ControlNet |
| 4. Video Generation | Text-to-video, image-to-video |
| 5. LoRA Training | Character, style, motion training |
| 6. Job Management | Completion, cancellation, history |
| 7. Cost Management | Estimates, balance checking |
| 8. Error Handling | Error types, retry patterns |
| 9. Monitoring | Analytics, rate limits, health checks |
| 10. Advanced | Model comparison, batch generation, variations |
| 11. Cleanup | Proper shutdown, auto-cleanup factories |
Usage#
Import examples in your code:
// Import specific examples
import {
example_basic_synthesis,
example_streaming_session,
} from '@oshun/training/examples/elevenlabs-examples';
// Or import all examples as a collection
import { elevenlabsExamples } from '@oshun/training/examples/elevenlabs-examples';
import { comfyuiExamples } from '@oshun/training/examples/comfyui-examples';
import { civitaiExamples } from '@oshun/training/examples/civitai-examples';
Running Examples#
# Set required environment variables
export ELEVENLABS_API_KEY=your_key
export RUNCOMFY_API_KEY=your_key
export CIVITAI_API_KEY=your_key
# Run with ts-node or in your application
npx ts-node docs/training/examples/elevenlabs-examples.ts
Key Patterns Demonstrated#
1. Provider Initialization#
All providers follow the same initialization pattern:
// Minimal configuration
const provider = new Provider({
apiKey: process.env.API_KEY!,
});
// Full configuration
const provider = new Provider({
apiKey: process.env.API_KEY!,
timeout: 60000,
maxRetries: 5,
// ... other options
});
2. Error Handling#
Consistent error handling across providers:
try {
await provider.operation();
} catch (error) {
if (error instanceof Error) {
const apiError = error as Error & { code?: string; retryable?: boolean };
if (apiError.retryable) {
// Implement retry logic
}
switch (apiError.code) {
case 'RATE_LIMITED':
// Handle rate limit
break;
case 'AUTHENTICATION_FAILED':
// Handle auth error
break;
// ...
}
}
}
3. Retry with Exponential Backoff#
async function retryWithBackoff<T>(
operation: () => Promise<T>,
maxRetries = 3
): Promise<T> {
let delay = 1000;
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
return await operation();
} catch (error) {
if (!isRetryable(error) || attempt === maxRetries) throw error;
await sleep(delay);
delay = Math.min(delay * 2, 30000);
}
}
}
4. Resource Cleanup#
const provider = new Provider(config);
try {
// Use provider
await provider.doWork();
} finally {
// Always cleanup
await provider.shutdown();
}
5. Statistics and Monitoring#
// All providers expose statistics
const stats = provider.getStats();
console.log(`Success rate: ${(stats.successful / stats.total * 100).toFixed(1)}%`);
console.log(`Average latency: ${stats.averageLatencyMs}ms`);
// Health checks
const healthy = await provider.healthCheck();
Best Practices#
-
Always initialize with proper configuration - Set timeouts, retries, and other options appropriate for your use case.
-
Handle errors gracefully - Check error codes and implement appropriate retry logic for transient failures.
-
Monitor usage - Track statistics to understand your usage patterns and optimize costs.
-
Clean up resources - Always call
shutdown()when done to release connections and clear caches. -
Use streaming for real-time applications - For low-latency requirements, use streaming APIs where available.
-
Batch operations when possible - Group multiple operations to reduce API calls and improve efficiency.
-
Cache appropriately - Use built-in caching features to reduce redundant API calls.
Next Steps#
After reviewing these examples:
- Complete the exercises in
../exercises/to practice these patterns - Attend the workshops in
../workshops/for guided learning - Watch the video tutorials (scripts in
../videos/) for visual walkthroughs - Build your own project using these patterns as a foundation
Contributing#
When adding new examples:
- Follow the existing section organization (numbered sections)
- Include comprehensive JSDoc comments
- Export examples individually and as a collection
- Update this README with new topics covered