@ai-queue/sdk
v0.4.12
Published
SDK for interacting with the AI Queue API
Readme
AI Queue SDK
A simple, well-defined SDK for interacting with the AI Queue API. This SDK provides a clean, type-safe interface for all API operations, making it easy to integrate AI Queue into your applications.
Installation
npm install @ai-queue/sdk
# or
yarn add @ai-queue/sdkQuick Start
import { AIQueue } from '@ai-queue/sdk';
// Initialize the SDK
const sdk = new AIQueue({
apiKey: 'your-api-key',
baseUrl: 'http://localhost:8080' // Optional, defaults to http://localhost:8080
});
// Add a speech job
const job = await sdk.queue.addJob({
type: 'speech',
data: {
text: 'Hello world, this is a test of text-to-speech conversion.',
provider: 'elevenlabs',
voiceId: 'voice-id-here'
},
webhookUrl: 'https://your-app.com/api/webhooks/speech-callback'
});
console.log('Job created:', job.jobId);Features
- Simple, intuitive API for all operations
- Full TypeScript support with proper type definitions
- Comprehensive error handling
- Automatic request validation
- Retry logic for failed requests
- Works in both browser and Node.js environments
API Reference
Configuration
const sdk = new AIQueue({
apiKey: 'your-api-key', // Required
baseUrl: 'http://localhost:8080', // Optional, defaults to http://localhost:8080
timeout: 30000, // Optional, defaults to 30000 (30 seconds)
maxRetries: 3, // Optional, defaults to 3
throwOnError: true // Optional, defaults to true
});Queue Operations
Add a Job
const job = await sdk.queue.addJob({
type: 'speech',
data: {
text: 'Hello world',
provider: 'elevenlabs',
voiceId: 'voice-id'
},
webhookUrl: 'https://your-app.com/api/webhooks/callback',
metadata: {
userId: 'user123',
requestId: 'req456'
}
});Add a Batch of Jobs
const batch = await sdk.queue.addBatchJob({
type: 'image',
jobs: [
{
data: {
prompt: 'A beautiful sunset over mountains',
provider: 'getimg'
},
metadata: { index: 0 }
},
{
data: {
prompt: 'A serene beach with palm trees',
provider: 'getimg'
},
metadata: { index: 1 }
}
],
webhookUrl: 'https://your-app.com/api/webhooks/batch-callback',
batchMetadata: {
batchName: 'landscape-images'
}
});Speech Operations
Get Speech Providers
const providers = await sdk.speech.getProviders();Get Voices for a Provider
const voices = await sdk.speech.getVoices('elevenlabs');Image Operations
Get Image Providers
const providers = await sdk.image.getProviders();Get Models for a Provider
const models = await sdk.image.getModels('getimg');Storage Operations
Generate a Presigned URL
const { presignedUrl, fileUrl } = await sdk.storage.generatePresignedUrl({
contentType: 'image/jpeg',
fileName: 'upload.jpg',
expiresIn: 3600 // Optional, seconds until URL expires
});Upload a File (Browser)
// In a browser environment
const fileInput = document.getElementById('fileInput') as HTMLInputElement;
const file = fileInput.files?.[0];
if (file) {
const fileUrl = await sdk.storage.upload(
file,
file.name,
file.type
);
console.log('File uploaded:', fileUrl);
}Upload a File (Node.js)
// In a Node.js environment
import fs from 'fs';
const filePath = './image.jpg';
const fileName = 'image.jpg';
const contentType = 'image/jpeg';
const fileBuffer = fs.readFileSync(filePath);
const fileUrl = await sdk.storage.upload(
fileBuffer,
fileName,
contentType
);
console.log('File uploaded:', fileUrl);Error Handling
The SDK throws typed errors that you can catch and handle:
import { AIQueue, APIError, ValidationError } from '@ai-queue/sdk';
try {
const job = await sdk.queue.addJob({
// Invalid job data
});
} catch (error) {
if (error instanceof ValidationError) {
console.error('Validation error:', error.errors);
} else if (error instanceof APIError) {
console.error('API error:', error.statusCode, error.message);
} else {
console.error('Unknown error:', error);
}
}Pricing Information
The SDK provides comprehensive pricing operations with automatic rate calculation:
Rate Configuration
// All rates are in USD cents per unit
const exampleRate = {
unit: 'characters', // Supported units: characters, seconds, image, etc.
rate: 0.25, // $0.0025 per character
minimum: 25 // $0.25 minimum charge
};Common Operations
// Get complete pricing matrix
const { pricing } = await sdk.pricing.getPricing();
// Calculate speech generation cost
const text = "Hello world, this is a test";
const cost = await sdk.pricing.calculateCost(
'speech',
'elevenlabs',
text.length // Character count
);
console.log(`Estimated cost: $${(cost / 100).toFixed(2)}`);
// Handle minimum charges
const smallJobCost = await sdk.pricing.calculateCost(
'speech',
'aws',
10 // Below AWS's 50 character minimum
);
console.log(`Charged minimum: $${(smallJobCost / 100).toFixed(2)}`);Error Handling
try {
const cost = await sdk.pricing.calculateCost(
'invalid-service',
'elevenlabs',
1000
);
} catch (error) {
if (error instanceof ValidationError) {
console.error('Invalid service type:', error.errors);
}
}Provider-Specific Rates
// Compare provider pricing
const [elevenlabs, google] = await Promise.all([
sdk.pricing.getProviderPricing('elevenlabs'),
sdk.pricing.getProviderPricing('google')
]);
console.log('ElevenLabs rate:', elevenlabs[0].rate);
console.log('Google rate:', google[0].rate);Rate Configuration Notes
- All rates configured in USD cents (1 cent = $0.01)
- Minimum charges apply per-request
- Units vary by service type (characters, seconds, etc.)
- Real-time pricing updates via API
License
MIT
