aiarbitration
v0.1.0
Published
JavaScript/TypeScript SDK for the AIArbitration intelligent AI model router
Maintainers
Readme
aiarbitration · JavaScript / TypeScript SDK
Intelligent AI model routing for JavaScript and TypeScript applications.
AIArbitration selects the best model for every request — balancing cost, latency, capability, and compliance — and falls back automatically on failure.
npm install aiarbitration
# or
pnpm add aiarbitration
# or
yarn add aiarbitrationWorks in Node.js 18+ and modern browsers (uses the fetch API). Fully typed — no separate @types package needed.
Quick start
import { AIArbitrationClient } from 'aiarbitration'
// Option A — supply a JWT obtained from your login flow
const client = new AIArbitrationClient({
baseUrl: 'https://api.theaiarbitration.com',
apiKey: '<your-jwt-token>',
})
// Option B — let the SDK authenticate for you
const client = await AIArbitrationClient.login(
'https://api.theaiarbitration.com',
'[email protected]',
's3cr3t',
)
const response = await client.execute('Explain quantum entanglement in one sentence.')
console.log(response.content)
// → "Quantum entanglement is a phenomenon where two particles ..."
console.log(`Model: ${response.modelUsed} Cost: $${response.cost.toFixed(6)}`)Streaming
for await (const chunk of client.stream('Write a short poem about the ocean.')) {
process.stdout.write(chunk.content)
if (chunk.isDone) break
}Structured request
import type { ChatRequest } from 'aiarbitration'
const request: ChatRequest = {
messages: [
{ role: 'system', content: 'You are a concise technical assistant.' },
{ role: 'user', content: 'What is a transformer model?' },
],
taskType: 'general',
maxCostUsd: 0.05, // reject models over $0.05 for this request
requiredRegion: 'eu-west-1', // GDPR: EU-only providers
}
const response = await client.execute(request)Cost estimate (dry run)
const estimate = await client.estimate('Summarise this 10,000-word document.')
console.log(`Selected: ${estimate.selectedModel?.modelId}`)
console.log(`Estimated cost: $${estimate.estimatedCost.toFixed(6)}`)
console.log(`Candidates: ${estimate.allCandidates.length}`)Image generation
const result = await client.generateImage({
prompt: 'Futuristic smart city at golden hour, photorealistic',
size: '1024x1024',
})
console.log(result.imageUrl)Batch execution
const requests = ['What is TypeScript?', 'What is Rust?', 'What is Go?']
.map(content => ({ messages: [{ role: 'user' as const, content }] }))
const batch = await client.executeBatch(requests)
console.log(`Success rate: ${(batch.successRate * 100).toFixed(0)}%`)
console.log(`Total cost: $${batch.totalCost.toFixed(6)}`)
batch.successfulResponses.forEach(r => console.log(r.content.slice(0, 80)))List available models
const models = await client.getModels({ vision: true, tier: 'flagship' })
for (const m of models) {
console.log(`${m.displayName.padEnd(30)} ${m.contextWindow.toLocaleString()} ctx`)
}Drop-in OpenAI replacement
AIArbitration exposes an OpenAI-compatible endpoint at /v1.
Point the official OpenAI SDK at it and your existing code works unchanged:
import OpenAI from 'openai'
const openai = new OpenAI({
baseURL: 'https://api.theaiarbitration.com/v1',
apiKey: '<your-jwt-token>',
})
const response = await openai.chat.completions.create({
model: 'arbitrated', // let the engine choose, or pin a specific model
messages: [{ role: 'user', content: 'Hello!' }],
})
console.log(response.choices[0].message.content)Error handling
import {
AIArbitrationError,
AuthenticationError,
BudgetExceededError,
RateLimitError,
ServiceUnavailableError,
} from 'aiarbitration'
try {
const response = await client.execute('...')
} catch (e) {
if (e instanceof AuthenticationError) console.error('Invalid or expired token.')
else if (e instanceof RateLimitError) console.error('Quota reached — upgrade your plan.')
else if (e instanceof BudgetExceededError) console.error('Request exceeds budget cap.')
else if (e instanceof ServiceUnavailableError) console.error('All models unavailable.')
else if (e instanceof AIArbitrationError) console.error(`API error ${e.statusCode}: ${e.message}`)
else throw e
}Configuration reference
| Option | Default | Description |
|---|---|---|
| baseUrl | — | API base URL (required) |
| apiKey | undefined | JWT bearer token |
| timeoutMs | 120000 | Request timeout in milliseconds |
