# Oshun AI Integration Code Examples

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:

```typescript
// 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

```bash
# 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:

```typescript
// 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:

```typescript
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

```typescript
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

```typescript
const provider = new Provider(config);

try {
  // Use provider
  await provider.doWork();
} finally {
  // Always cleanup
  await provider.shutdown();
}
```

### 5. Statistics and Monitoring

```typescript
// 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

1. **Always initialize with proper configuration** - Set timeouts, retries, and
   other options appropriate for your use case.

2. **Handle errors gracefully** - Check error codes and implement appropriate
   retry logic for transient failures.

3. **Monitor usage** - Track statistics to understand your usage patterns and
   optimize costs.

4. **Clean up resources** - Always call `shutdown()` when done to release
   connections and clear caches.

5. **Use streaming for real-time applications** - For low-latency requirements,
   use streaming APIs where available.

6. **Batch operations when possible** - Group multiple operations to reduce
   API calls and improve efficiency.

7. **Cache appropriately** - Use built-in caching features to reduce redundant
   API calls.

## Next Steps

After reviewing these examples:

1. **Complete the exercises** in `../exercises/` to practice these patterns
2. **Attend the workshops** in `../workshops/` for guided learning
3. **Watch the video tutorials** (scripts in `../videos/`) for visual walkthroughs
4. **Build your own project** using these patterns as a foundation

## Contributing

When adding new examples:

1. Follow the existing section organization (numbered sections)
2. Include comprehensive JSDoc comments
3. Export examples individually and as a collection
4. Update this README with new topics covered
