@split-router/splitrouter-sdk
v1.0.4
Published
JavaScript SDK for SplitRouter AI API Gateway
Downloads
56
Readme
SplitRouter JavaScript SDK
A comprehensive JavaScript SDK for the SplitRouter AI API Gateway. SplitRouter provides a unified interface to multiple AI providers (OpenAI, Anthropic Claude, Google Gemini, and DeepSeek) with advanced features like cost tracking, credit management, and analytics.
Features
- 🚀 Multi-Provider Support: Access OpenAI, Anthropic, Gemini, and DeepSeek through a single API
- 🔄 Smart Routing: Automatic model selection based on request characteristics
- 💰 Cost Tracking: Detailed usage and cost analytics
- 🎯 Credit System: Flexible credit management for end users
- 🔑 API Key Management: Full API key lifecycle management
- 📈 Project Management: Organize end users by projects with custom pricing tiers
- 🛡️ Error Handling: Comprehensive error handling with detailed error types
- 📝 TypeScript Support: Full TypeScript definitions included
Installation
npm install @split-router/splitrouter-sdkQuick Start
import SplitRouterClient from '@split-router/splitrouter-sdk';
// Initialize the client
const client = new SplitRouterClient({
apiKey: 'sk-your-developer-api-key-here', // Must start with 'sk-' for developer keys
// Optional, defaults to https://test.splitrouter.ai/ for development
});
// Test the connection
const status = await client.testConnection();
console.log('Connection status:', status);
// Create a chat completion
const response = await client.chat.create({
model: 'gpt-4o',
messages: [
{ role: 'user', content: 'Hello, how are you?' }
]
});
console.log('AI Response:', response.choices[0].message.content);Configuration
API Key Format
SplitRouter uses specific API key formats:
- Developer Keys: Must start with
sk-(e.g.,sk-dev-1234567890abcdef...) - End User Keys: Must start with
pk_(e.g.,pk_project_user_hash...)
You can obtain your developer API key from the SplitRouter dashboard. End user keys are generated automatically when you create end users through your projects.
Client Configuration
const client = new SplitRouterClient({
apiKey: 'your-api-key-here', // Required: Your SplitRouter API key
baseURL: 'https://test.splitrouter.ai/', // Optional: API base URL (development default)
timeout: 30000, // Optional: Request timeout in ms
defaultHeaders: { // Optional: Default headers
'X-Custom-Header': 'value'
}
});API Reference
Chat Completions
Create AI chat completions using various models:
// Standard chat completion
const response = await client.chat.create({
model: 'gpt-4o',
messages: [
{ role: 'system', content: 'You are a helpful assistant.' },
{ role: 'user', content: 'Explain quantum computing' }
],
max_tokens: 1000,
temperature: 0.7
});
// Smart routing (automatically selects best model)
const smartResponse = await client.chat.createWithSmartRouting({
messages: [
{ role: 'user', content: 'Write a Python function to sort a list' }
]
});
// General AI request (supports both chat and completion)
const generalResponse = await client.chat.createRequest({
model: 'claude-3-5-sonnet',
type: 'chat',
messages: [
{ role: 'user', content: 'Hello!' }
]
});Project Management
Organize your end users into projects with custom pricing tiers:
// Create a project
const project = await client.projects.create({
name: 'My AI App',
markup_tiers: {
'basic': 10, // 10% markup
'premium': 5, // 5% markup
'enterprise': 0 // No markup
}
});
// List projects
const projects = await client.projects.list({
status: 'active',
limit: 50,
offset: 0
});
// Get specific project
const projectDetails = await client.projects.get(project.id);
// Update project
const updatedProject = await client.projects.update(project.id, {
name: 'Updated App Name',
markup_tiers: {
'basic': 15,
'premium': 8,
'enterprise': 2
}
});
// Delete project
await client.projects.delete(project.id);End User Management
Manage end users within your projects:
// Create an end user
const endUser = await client.endUsers.create({
project_id: 'project-id',
developer_user_id: '[email protected]',
markup_tier: 'premium'
});
// List end users
const endUsers = await client.endUsers.list({
project_id: 'project-id',
status: 'active',
markup_tier: 'premium',
search: '[email protected]',
limit: 50
});
// Get end user API keys
const keys = await client.endUsers.getKeys(endUser.id);
// Update end user
const updatedUser = await client.endUsers.update(endUser.id, {
markup_tier: 'enterprise',
status: 'active'
});
// Suspend end user
await client.endUsers.suspend(endUser.id, 'Policy violation');
// Reactivate end user
await client.endUsers.reactivate(endUser.id);
// Get end user statistics
const stats = await client.endUsers.getStats(endUser.id, { days: 30 });Credit Management
Handle credit purchases and balance management:
// Get your credit balance
const balance = await client.credits.getBalance();
// Get end user credit balance
const userBalance = await client.credits.getEndUserBalance(endUser.id);
// Calculate purchase total
const calculation = await client.credits.calculateTotal({
end_user_id: endUser.id,
credit_amount: 100.00
});
// Initiate credit purchase
const purchase = await client.credits.purchase({
end_user_id: endUser.id,
credit_amount: 100.00,
return_url: 'https://yourapp.com/success',
cancel_url: 'https://yourapp.com/cancel'
});
// Redirect user to purchase.checkout_url
// Get transaction history
const transactions = await client.credits.getTransactions({
end_user_id: endUser.id,
type: 'purchase',
limit: 50
});
// Transfer credits (admin only)
await client.credits.transfer({
from_end_user_id: 'user1',
to_end_user_id: 'user2',
amount: 50.00,
reason: 'Refund processing'
});
// Add bonus credits (admin only)
await client.credits.addBonus({
end_user_id: endUser.id,
amount: 25.00,
reason: 'Welcome bonus'
});API Key Management
Manage your API keys programmatically:
// List API keys
const keys = await client.apiKeys.list({
status: 'active',
limit: 50
});
// Create new API key
const newKey = await client.apiKeys.create({
name: 'Production Key',
description: 'Key for production environment',
scopes: ['chat', 'models', 'usage'],
rate_limits: {
requests_per_minute: 1000,
requests_per_day: 50000
},
custom_markup: 5,
expires_at: '2025-12-31T23:59:59Z'
});
// Get key details
const keyDetails = await client.apiKeys.get(newKey.id);
// Update API key
const updatedKey = await client.apiKeys.update(newKey.id, {
name: 'Updated Production Key',
custom_markup: 7
});
// Test key validity
const testResult = await client.apiKeys.test(newKey.id);
// Update rate limits
await client.apiKeys.updateRateLimits(newKey.id, {
requests_per_minute: 2000,
tokens_per_minute: 100000
});
// Revoke API key
await client.apiKeys.revoke(newKey.id, 'Security breach');
// Regenerate API key
const regenerated = await client.apiKeys.regenerate(newKey.id);Error Handling
The SDK provides comprehensive error handling with specific error types:
import { SplitRouterError, APIError, AuthenticationError, ValidationError } from '@split-router/splitrouter-sdk';
try {
const response = await client.chat.create({
model: 'invalid-model',
messages: []
});
} catch (error) {
if (error instanceof AuthenticationError) {
console.error('Authentication failed:', error.message);
// Handle auth error (redirect to login, refresh token, etc.)
} else if (error instanceof ValidationError) {
console.error('Validation error:', error.message);
console.error('Field:', error.field);
// Handle validation error (show user feedback, fix input, etc.)
} else if (error instanceof APIError) {
console.error('API error:', error.message);
console.error('Status:', error.status);
console.error('Code:', error.code);
// Handle API error (retry, fallback, etc.)
} else if (error instanceof SplitRouterError) {
console.error('SDK error:', error.message);
// Handle general SDK error
} else {
console.error('Unexpected error:', error);
// Handle unexpected errors
}
}TypeScript Support
The SDK includes full TypeScript definitions:
import SplitRouterClient, { ChatCompletionParams, Project, EndUser } from '@split-router/splitrouter-sdk';
const client = new SplitRouterClient({
apiKey: process.env.SPLITROUTER_API_KEY!
});
// TypeScript will provide full intellisense and type checking
const params: ChatCompletionParams = {
model: 'gpt-4o',
messages: [
{ role: 'user', content: 'Hello!' }
],
temperature: 0.7
};
const response = await client.chat.create(params);Environment Variables
For security, store your API key in environment variables:
# .env file
SPLITROUTER_API_KEY=your-api-key-here
SPLITROUTER_BASE_URL=https://your-instance.com # Optional// Load from environment
const client = new SplitRouterClient({
apiKey: process.env.SPLITROUTER_API_KEY,
baseURL: process.env.SPLITROUTER_BASE_URL
});Rate Limiting
The SDK handles rate limiting automatically and will throw appropriate errors when limits are exceeded. You can check rate limit status:
// Check rate limit status for a specific API key
const rateLimitStatus = await client.apiKeys.getRateLimitStatus('key-id');
console.log('Remaining requests:', rateLimitStatus.remaining_requests);
console.log('Reset time:', rateLimitStatus.reset_time);Examples
Complete Chat Application
import SplitRouterClient from '@split-router/splitrouter-sdk';
class ChatApp {
constructor(apiKey) {
this.client = new SplitRouterClient({ apiKey });
this.conversation = [];
}
async sendMessage(message) {
try {
// Add user message to conversation
this.conversation.push({ role: 'user', content: message });
// Get AI response with smart routing
const response = await this.client.chat.createWithSmartRouting({
messages: this.conversation,
temperature: 0.7
});
// Add AI response to conversation
const aiMessage = response.choices[0].message;
this.conversation.push(aiMessage);
return aiMessage.content;
} catch (error) {
console.error('Chat error:', error);
throw error;
}
}
async getCreditBalance() {
return await this.client.credits.getBalance();
}
}
// Usage
const app = new ChatApp('your-api-key');
const response = await app.sendMessage('Hello, how are you?');
console.log('AI:', response);Multi-Tenant SaaS Application
class SaaSPlatform {
constructor(apiKey) {
this.client = new SplitRouterClient({ apiKey });
}
async onboardCustomer(customerData) {
// Create project for the customer
const project = await this.client.projects.create({
name: customerData.companyName,
markup_tiers: {
'starter': 20, // 20% markup for starter plan
'professional': 10, // 10% markup for pro plan
'enterprise': 5 // 5% markup for enterprise
}
});
// Create end user
const endUser = await this.client.endUsers.create({
project_id: project.id,
developer_user_id: customerData.email,
markup_tier: customerData.plan // 'starter', 'professional', or 'enterprise'
});
// Get API keys for the end user
const keys = await this.client.endUsers.getKeys(endUser.id);
return {
project,
endUser,
apiKey: keys.provisional_key
};
}
async getCustomerInfo(projectId) {
// Get basic project and user information
const project = await this.client.projects.get(projectId);
const endUsers = await this.client.endUsers.list({ project_id: projectId });
return { project, endUsers };
}
}Troubleshooting
Common Issues
Insufficient Credits Error
Error: Insufficient credits
Details: { required: 0.000243, available: 0, message: 'You need at least $0.0002 credits...' }Solution: Add credits to your SplitRouter account through the dashboard or purchase credits programmatically using the SDK's credit management features.
Invalid API Key Format
Error: Invalid API key formatSolution: Ensure your API key starts with sk- for developer keys or pk_ for end-user keys.
Network Error / Connection Failed
Error: Network error: No response receivedSolution:
- Check if the SplitRouter API is running
- Verify the
baseURLconfiguration - For development, ensure the server is running on the correct port
Environment Setup
For development, create a .env file:
SPLITROUTER_API_KEY=sk-your-developer-key-here
SPLITROUTER_BASE_URL=https://test.splitrouter.ai/Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
License
This project is licensed under the MIT License - see the LICENSE file for details.
Support
- 📧 Email: [email protected]
- 📖 Documentation: https://docs.splitrouter.com
- 🐛 Issues: GitHub Issues
Changelog
v1.0.0
- Initial release
- Full API coverage for SplitRouter
- TypeScript support
- Comprehensive error handling
- Complete documentation and examples
