@tchavi/sdk
v0.2.0
Published
Official Node.js SDK for the Tchavi AI API gateway
Maintainers
Readme
@tchavi/sdk
Official Node.js SDK for the Tchavi AI API gateway — use OpenAI-compatible models with credit-based billing, without managing provider keys yourself.
Requirements
- Node.js 20+ (uses native
fetchandReadableStream) - TypeScript 5+ (optional but recommended)
Installation
npm install @tchavi/sdk
# or
pnpm add @tchavi/sdk
# or
yarn add @tchavi/sdkQuick start
import Tchavi from '@tchavi/sdk';
const client = new Tchavi({ apiKey: 'sk-tch-...' });
const response = await client.chat.completions.create({
model: 'gpt-4o-mini',
messages: [{ role: 'user', content: 'Hello!' }],
});
console.log(response.choices[0].message.content);
console.log('Credits used:', response.tchavi.credits_used);Get your API key from the Tchavi dashboard.
Chat completions
Non-streaming
const completion = await client.chat.completions.create({
model: 'gpt-4o-mini',
messages: [
{ role: 'system', content: 'You are a helpful assistant.' },
{ role: 'user', content: 'What is the capital of France?' },
],
temperature: 0.7,
max_tokens: 256,
});
console.log(completion.choices[0].message.content);
// Credit metadata appended by Tchavi:
console.log(completion.tchavi.credits_used);
console.log(completion.tchavi.credits_remaining);Streaming
const stream = await client.chat.completions.create({
model: 'gpt-4o',
messages: [{ role: 'user', content: 'Tell me a story.' }],
stream: true,
});
for await (const chunk of stream) {
process.stdout.write(chunk.choices[0]?.delta?.content ?? '');
}
// Credit metadata available after iteration completes:
const meta = stream.finalMeta();
console.log('\nCredits used:', meta?.credits_used);Chat with a PDF
Attach PDFs to a user message by passing an array of content blocks. Use the document_url block with a public URL (we recommend storing the PDF on the Tchavi platform bucket first via the upload endpoint).
const completion = await client.chat.completions.create({
model: 'claude-sonnet-4-6',
messages: [
{
role: 'user',
content: [
{ type: 'text', text: 'Summarize this document in 5 bullet points.' },
{
type: 'document_url',
document_url: { url: 'https://your-bucket.r2.dev/contract.pdf' },
},
],
},
],
});
console.log(completion.choices[0].message.content);Up to 5 PDFs per request. Only models with supportsDocuments: true accept document inputs — currently claude-opus-4-7, claude-sonnet-4-6, claude-haiku-4-5-20251001, gpt-4.1, and gpt-4.1-mini. Check the capability before sending:
const models = await client.models.list();
const docModels = models.data.filter((m) => m.tchavi?.capabilities.documents);What a response guarantees
Tchavi serves many upstreams behind one API, and a model you name may be served by a different one. These hold whoever answers, so you never need a branch per provider.
model is the id you asked for. Never the provider's own name for it. Ask for
gpt-5-nano and you get gpt-5-nano, not gpt-5-nano-2025-08-07, so you can always
compare the response to your request:
const c = await client.chat.completions.create({ model: 'gpt-5-nano', messages });
c.model === 'gpt-5-nano'; // trueid is this request's id, and matches the header. It is chatcmpl- plus the value in
X-Request-Id (resp_ on /v1/responses, msg_ on /v1/messages). Every chunk of a
stream carries the same one, and the id a customer quotes is the id support looks up:
for await (const chunk of stream) {
chunk.id; // identical on every chunk
}The shape does not vary. system_fingerprint and service_tier are always present and
always null — they describe an upstream backend and an OpenAI product tier, neither of
which this API exposes; your own tier is in tchavi. message.refusal and both usage
detail blocks are always present too, so reading them never returns undefined.
Reasoning text follows the model you named. Models that publish their thinking return
message.reasoning (and delta.reasoning while streaming). Models that do not — the OpenAI
reasoning family among them — return no text while still reporting
completion_tokens_details.reasoning_tokens, which you are billed for. That mirrors how
each model behaves natively.
const c = await client.chat.completions.create({ model: 'deepseek-v4-flash', messages });
c.choices[0].message.reasoning; // the model's thinking
c.usage.completion_tokens_details.reasoning_tokens; // billed as outputEmbeddings
const result = await client.embeddings.create({
model: 'text-embedding-3-small',
input: 'The quick brown fox jumps over the lazy dog',
});
console.log(result.data[0].embedding); // number[]Decisions
Decision models are not chat models. You send a state plus the questions you want answered, and each answer comes back with a probability distribution instead of prose.
const d = await client.decisions.create({
model: 'jev-1.13',
state: "Customer writes: 'My API key stopped working after I rotated it.'",
questions: {
team: {
type: 'choice',
instructions: 'Which team should handle this?',
criteria: { billing: 'payments or credits', technical: 'API, keys' },
},
urgency: {
type: 'score',
instructions: 'How urgent is this?',
criteria: ['not urgent', 'normal', 'urgent', 'critical'],
},
blocked: { type: 'noul', instructions: 'Is the customer unable to use the product?' },
},
});
// Answers are discriminated on `type`.
if (d.answers.team.type === 'choice') {
console.log(d.answers.team.choice); // 'technical'
console.log(d.answers.team.confidence); // 1.0
console.log(d.answers.team.probabilities); // { billing: 0, technical: 1 }
}
if (d.answers.blocked.type === 'noul') {
console.log(d.answers.blocked.noul); // 0.77 — a likelihood, 0 to 1
}The three question types:
| type | you supply | you get back |
| -------- | ----------------------------------------------- | ---------------------------------------------------------- |
| choice | criteria as a map of option to meaning | choice, confidence, probabilities |
| score | criteria as an ordered array, low to high | score (a float), legend, confidence, probabilities |
| noul | nothing extra | noul only — no confidence |
Two things that differ from every other resource here:
- The response has no
tchaviblock. The gateway passes the provider's body through untouched, so credits appear in theX-Credits-UsedandX-Credits-Remainingheaders instead. Useclient.decisions.createRaw(...)to read them. - Billed input runs well above what you send. Your questions are expanded into the prompt upstream, so a short state with three questions is typically billed 300-400 input tokens. Output tokens are free.
Image generation
Nano Banana (Gemini native)
const result = await client.images.generations.create({
prompt: 'A futuristic city skyline at sunset, cinematic lighting',
model: 'nano-banana-pro',
resolution: '2K',
aspect_ratio: '16:9',
output_format: 'webp',
compression_quality: 80,
temperature: 0.8,
n: 2,
});
console.log(result.data[0].b64_json);
console.log('Credits used:', result.tchavi.credits_used);Image editing with reference images:
const result = await client.images.generations.create({
prompt: 'Change the background to a beach sunset',
model: 'nano-banana-pro',
reference_images: [{ b64_json: 'BASE64...' }],
resolution: '1K',
});| Model | Resolutions | Credits (default 1K) |
| ----------------- | ---------------- | -------------------- |
| nano-banana | 1K | 128 |
| nano-banana-2 | 0.5K, 1K, 2K, 4K | 220 |
| nano-banana-pro | 1K, 2K, 4K | 439 |
Imagen 4
const result = await client.images.generations.create({
prompt: 'A professional flyer for a sandwich restaurant, warm colors',
model: 'imagen-4',
negative_prompt: 'blurry, low quality, watermark',
aspect_ratio: '9:16',
resolution: '2K',
enhance_prompt: true,
seed: 42,
n: 1,
});| Model | Resolutions | Notes |
| ---------------- | ----------- | ------------------------------ |
| imagen-4-fast | — | Fastest, no resolution control |
| imagen-4 | 1K, 2K | Standard |
| imagen-4-ultra | 1K, 2K | Highest quality |
GPT Image
const result = await client.images.generations.create({
prompt: 'A clean app-store icon for a budgeting app, simple, high contrast',
model: 'gpt-image-1-mini',
size: '1024x1024',
quality: 'medium',
output_format: 'webp',
output_compression: 80,
background: 'transparent',
n: 1,
});Image editing with reference images (the gateway treats this as an edit request when images is present):
const result = await client.images.generations.create({
prompt: 'Add a floral pattern to the vase',
model: 'gpt-image-1',
images: ['data:image/png;base64,...'],
input_fidelity: 'high',
// mask: 'data:image/png;base64,...', // optional — transparent pixels = edit area
});| Model | Sizes | Qualities | Notes |
| ------------------ | ------------------------------------- | -------------------- | ------------------------- |
| gpt-image-1-mini | 1024x1024, 1536x1024, 1024x1536, auto | low/medium/high/auto | Most affordable |
| gpt-image-1 | same | low/medium/high/auto | Supports input_fidelity |
| gpt-image-1.5 | same | low/medium/high/auto | Latest flagship |
All image parameters
| Parameter | Nano Banana | Imagen 4 | GPT Image | Description |
| ----------------------------- | ------------- | -------- | ---------------- | ----------------------------------- |
| prompt | ✓ | ✓ | ✓ | Main prompt |
| n | 1–4 | 1–4 | 1–4 | Number of images |
| negative_prompt | appended | ✓ | — | What to exclude |
| aspect_ratio | 14 values | 5 values | — | Image aspect ratio |
| resolution | 0.5K–4K | 1K–2K | — | Output resolution (Google) |
| size | — | — | 3 values | Output dimensions (OpenAI) |
| quality | — | — | low/medium/high | Render quality (OpenAI) |
| output_format | png/jpeg/webp | png/jpeg | png/jpeg/webp | File format |
| compression_quality | 0–100 | 0–100 | — | JPEG/WebP quality (Google) |
| output_compression | — | — | 0–100 | JPEG/WebP quality (OpenAI) |
| images / reference_images | up to 14 | — | up to 16 | Input images for editing |
| mask | — | — | ✓ | Edit mask (transparent = edit area) |
| input_fidelity | — | — | gpt-image-1 only | Preserve facial features |
| background | — | — | ✓ | transparent / opaque / auto |
| temperature | 0–2 | — | — | Creativity control |
| seed | — | ✓ | — | Reproducible output |
| enhance_prompt | — | ✓ | — | Auto-rewrite prompt |
| person_generation | — | ✓ | — | Person policy |
| safety_level | ✓ | ✓ | — | Safety filter level |
Audio
Text-to-speech
client.audio.speech.create() returns the raw Response. Call .arrayBuffer() to get the audio bytes or .body to stream them directly.
const response = await client.audio.speech.create({
model: 'tts-1',
input: 'Hello, welcome to Tchavi.',
voice: 'alloy',
response_format: 'mp3', // mp3 | opus | aac | flac | wav | pcm
speed: 1.0, // 0.25–4.0, default 1.0
});
// Save to file (Node.js)
import { writeFile } from 'node:fs/promises';
const buffer = Buffer.from(await response.arrayBuffer());
await writeFile('speech.mp3', buffer);Available voices: alloy, ash, ballad, cedar, coral, echo, fable, marin, nova, onyx, sage, shimmer.
Available models: tts-1 (faster, lower cost), tts-1-hd (higher quality).
Transcription (Whisper)
import { readFile } from 'node:fs/promises';
const audioBuffer = await readFile('recording.mp3');
const file = new File([audioBuffer], 'recording.mp3', { type: 'audio/mpeg' });
const result = await client.audio.transcriptions.create({
model: 'whisper-1',
file,
language: 'en', // optional — omit for auto-detect
response_format: 'json', // json | text | srt | vtt | verbose_json
});
console.log(result.text);
console.log('Duration (min):', result.tchavi.duration_minutes);
console.log('Credits used:', result.tchavi.credits_used);Video generation
Video models (Seedance, Kling V3, Kling V3 Motion Control) run asynchronously. Submit a job with
client.videos.generations.create(...) and poll
client.jobs.retrieve(id) until it reaches completed or failed. For most
cases, the createAndWait(...) helper does both in a single call.
One-liner
const job = await client.videos.generations.createAndWait({
model: 'seedance-2',
prompt: 'A cinematic shot of the Cotonou Amazone statue at golden hour',
duration: 5, // 1–15 or -1 (auto, billed at 10s)
resolution: '480p', // '480p' | '720p'
aspect_ratio: '9:16',
generate_audio: true,
});
if (job.status === 'completed') {
console.log('Video URL:', job.output?.video_url);
console.log('Credits used:', job.tchavi?.credits_used);
} else {
console.error('Failed:', job.error?.message);
}Options: pollIntervalMs (default 5s), timeoutMs (default 5 min), signal
(AbortSignal to stop polling — the backend job keeps running), and onPoll
to track progress:
const controller = new AbortController();
setTimeout(() => controller.abort(), 2 * 60_000);
const job = await client.videos.generations.createAndWait(
{ model: 'seedance-2', prompt: '...', duration: 10 },
{ pollIntervalMs: 3000, signal: controller.signal, onPoll: (j) => console.log(j.status) },
);Fire-and-poll (advanced)
When you need to surface intermediate progress in your own UI:
const submission = await client.videos.generations.create({
model: 'seedance-2',
prompt: '...',
resolution: '720p',
});
let job = await client.jobs.retrieve(submission.id);
while (job.status === 'pending' || job.status === 'processing') {
await new Promise((r) => setTimeout(r, 5000));
job = await client.jobs.retrieve(submission.id);
}
console.log(job.status, job.output?.video_url);Image-to-video with references
await client.videos.generations.createAndWait({
model: 'seedance-2',
prompt: 'Animate this character walking forward',
image_url: 'https://cdn.example.com/character.jpg',
// OR — instead of image_url, pass up to 9 reference_images
// reference_images: ['https://.../ref1.jpg', 'https://.../ref2.jpg'],
duration: 10,
resolution: '720p',
seed: 42,
});Motion control (kling-v3-motion-control)
Transfers the motion from a reference video onto a character image. This model
takes no duration (sending one returns a 400) — the output length
follows the reference video, capped at 10s with character_orientation: 'image'
or 30s with 'video'.
Billing is reserve-then-refund: the orientation cap × per-second rate is held
at submit, and the unused part is refunded once the actual output length is
known. The completed job reports the net charge in tchavi.credits_used and
the refund in tchavi.credits_refunded.
const job = await client.videos.generations.createAndWait({
model: 'kling-v3-motion-control',
prompt: 'The character performs the dance, keeping its exact appearance',
resolution: '1080p', // '720p' | '1080p'
image_url: 'https://cdn.example.com/character.png', // required: the character
reference_video_url: 'https://cdn.example.com/motion.mp4', // required: 3–30s motion clip
character_orientation: 'image', // 'image' (≤10s) | 'video' (≤30s)
keep_original_sound: true,
// no `duration` — output length follows the reference video
});
console.log('Rendered seconds:', job.output?.duration);
console.log('Credits used (net):', job.tchavi?.credits_used);
console.log('Credits refunded:', job.tchavi?.credits_refunded);Handling credit / timeout errors
import Tchavi, { TchaviInsufficientCreditsError, TchaviTimeoutError } from '@tchavi/sdk';
try {
const job = await client.videos.generations.createAndWait(
{
model: 'seedance-2',
prompt: '...',
duration: 10,
resolution: '720p',
},
{ timeoutMs: 3 * 60_000 },
);
} catch (err) {
if (err instanceof TchaviInsufficientCreditsError) {
console.log('Top up:', err.creditsRemaining, 'credits left');
} else if (err instanceof TchaviTimeoutError) {
// Job is still running server-side — poll manually with err.jobId.
const job = await client.jobs.retrieve(err.jobId);
console.log('Eventual status:', job.status);
} else {
throw err;
}
}Listing past jobs
const { data } = await client.jobs.list({ status: 'completed', limit: 10 });
for (const job of data) {
console.log(job.created_at, job.model, job.output?.video_url);
}Credits and cached tokens
Credits carry three decimals. A short request can cost 0.04 credits, not 1. Every credit
figure the SDK returns — tchavi.credits_used, billing.getBalance().credits,
creditsCharged on a usage log — is a decimal number. Do not round it to an integer.
Cached input is billed at its own rate. Providers serve a repeated prompt prefix from a cache and charge a fraction of the input rate for it, usually a tenth. Agents and chat apps resend the same conversation every turn, so this is most of a long session's bill.
One convention, whichever model you call. prompt_tokens is the whole input and
prompt_tokens_details is the breakdown within it — never additional to it:
const c = await client.chat.completions.create({ model: 'claude-sonnet-4-6', messages });
c.usage.prompt_tokens; // 1100 — the whole prompt
c.usage.prompt_tokens_details.cached_tokens; // 800 of it served from cache
c.usage.prompt_tokens_details.cache_write_tokens; // 100 of it written to cache
// the remaining 200 at the input rate
c.usage.prompt_tokens + c.usage.completion_tokens === c.usage.total_tokens; // alwaysThe detail blocks are always present and zero-filled, so reading
prompt_tokens_details.cached_tokens never returns undefined.
Upgrading. Earlier versions passed each provider's own convention through: Anthropic reported
cache_read_input_tokensandcache_creation_input_tokensEXCLUDED fromprompt_tokens, while OpenAI nested the same count INSIDE it. Those two fields no longer appear on a response — the gateway folds that form into this one before replying. Code that added them toprompt_tokensby hand will now double-count: delete that arithmetic rather than porting it.
A usage log uses the opposite convention, deliberately. promptTokens on a log row
EXCLUDES cached tokens, keeping the three input classes disjoint so the columns sum to
totalTokens. The two surfaces meet here:
log.promptTokens + log.cacheReadTokens + log.cacheWriteTokens === response.usage.prompt_tokens;so log.promptTokens and usage.prompt_tokens are different numbers for the same request.
Reconcile with the sum, not field against field.
A model's cache rate is on its catalog entry as creditsPerKCacheRead. Null there means no
cache rate is recorded and a cached token is billed at creditsPerKInput.
Error handling
import Tchavi, {
TchaviAuthenticationError,
TchaviInsufficientCreditsError,
TchaviPromptTooLongError,
TchaviRateLimitError,
TchaviProviderError,
TchaviTimeoutError,
TchaviAPIError,
TchaviError,
} from '@tchavi/sdk';
try {
const response = await client.chat.completions.create({ ... });
} catch (err) {
if (err instanceof TchaviInsufficientCreditsError) {
// 402 — top up credits
console.log('Credits remaining:', err.creditsRemaining);
} else if (err instanceof TchaviRateLimitError) {
// 429 — back off and retry
console.log('Retry after (s):', err.retryAfter); // number | null
} else if (err instanceof TchaviAuthenticationError) {
// Invalid, revoked, expired or suspended key
console.log('Check your API key');
} else if (err instanceof TchaviPromptTooLongError) {
// 413 — split the input; retrying unchanged will not help
console.log('Max prompt tokens for', err.model, 'is', err.maxPromptTokens);
} else if (err instanceof TchaviProviderError) {
// 502/503 — upstream AI provider failed, retry later
console.log('Provider issue:', err.message);
} else if (err instanceof TchaviAPIError) {
// Other HTTP errors
console.log(err.statusCode, err.errorCode, err.message);
} else if (err instanceof TchaviError) {
// Network/timeout errors
console.log('Network error:', err.message);
}
}Error messages are clean English for every code the SDK models. An unrecognised code falls back to the server's own message, which is localised — err.serverMessage always holds it verbatim.
| Error class | Status | Extra fields |
| -------------------------------- | ------- | -------------------------------------------------------------------------------------------------------------- |
| TchaviError | — | Base class for all SDK errors |
| TchaviAPIError | any | statusCode, errorCode, serverMessage, headers |
| TchaviAuthenticationError | 401/403 | —. Also raised for a revoked, expired or suspended key |
| TchaviInsufficientCreditsError | 402 | creditsRemaining: number \| null, creditsRequired: number \| null |
| TchaviPromptTooLongError | 413 | model: string \| null, maxPromptTokens: number \| null |
| TchaviRateLimitError | 429 | retryAfter: number \| null |
| TchaviProviderError | 502/503 | —. The gateway never names the upstream |
| TchaviTimeoutError | — | jobId: string, timeoutMs: number — subclass of TchaviError, thrown by videos.generations.createAndWait |
Account management
These methods use JWT auth — pass email and password instead of apiKey:
const client = new Tchavi({
email: '[email protected]',
password: 'my-password',
});Credits
const { creditsBalance } = await client.credits.getBalance();Billing
// Estimate credits before topping up (public — no auth required)
const estimate = await client.billing.estimate({ amount: 5000, currency: 'XOF' });
console.log(estimate.credits, estimate.bonusLabel);
// Top up via mobile money
const topup = await client.billing.topup({
amount: 5000,
currency: 'XOF', // optional — defaults to 'XOF'
phoneNumber: '22900000000',
correspondent: 'MTN_MOMO_BEN',
});
// Current balance and account level
const balance = await client.billing.getBalance();
console.log(balance.credits, balance.level); // e.g. 1200.375, 'BUILDER'
// Top-up history
const history = await client.billing.getHistory({ page: 1, limit: 20 });API keys
// List all keys
const keys = await client.apiKeys.list();
// Create a new key (full secret shown only once)
const { key, ...apiKey } = await client.apiKeys.create({ label: 'Production' });
console.log('Save this:', key);
// Retrieve / update / delete
const existing = await client.apiKeys.retrieve('key-id');
await client.apiKeys.update('key-id', { label: 'Renamed' });
await client.apiKeys.delete('key-id');Usage
const stats = await client.usage.getStats({
from: '2026-09-01T00:00:00Z', // required
to: '2026-09-30T23:59:59Z', // required
granularity: 'day', // 'hour' | 'day' | 'week' | 'month'
});
const history = await client.usage.getHistory({ page: 1, limit: 20 });Payments
// Initiate a credit package purchase
const payment = await client.payments.initiate({
packId: '0f8fad5b-d9cb-469f-a165-70867728950e', // a UUID
phoneNumber: '22900000000', // digits only — no +, spaces or dashes
});
// Check payment status. `initiate` returns the payment itself, not an id.
const status = await client.payments.getStatus(payment.payment.id);
// Payment history
const history = await client.payments.getHistory();Available models
const { data } = await client.models.list();
// each entry's `id` is the value to pass as `model` in requestsAuth & user profile
// Explicit login (sets the JWT for subsequent requests)
const { accessToken, user } = await client.auth.login('[email protected]', 'password');
// Register a new account
await client.auth.register({ email: '[email protected]', password: 'secret', name: 'Alice' });
// Logout (invalidates the session)
await client.auth.logout();
// Get the authenticated user's profile
const me = await client.users.me();
// Update profile
await client.users.update({ name: 'Alice', language: 'fr' });
// Change password
await client.users.update({ currentPassword: 'old', newPassword: 'new' });Configuration
const client = new Tchavi({
// Authentication (one of):
apiKey: 'sk-tch-...', // For proxy endpoints (chat, embeddings, images, audio)
email: '[email protected]', // For account management endpoints
password: 'my-password', // (requires email)
// Optional:
baseURL: 'https://tchavi.com/api', // Default: https://tchavi.com/api
maxRetries: 2, // Retries on 429/502/503. Default: 2
timeout: 60_000, // Request timeout in ms. Default: 60000
});| Option | Type | Default | Description |
| ------------ | -------- | ---------------------------- | ------------------------------------- |
| apiKey | string | process.env.TCHAVI_API_KEY | API key (sk-tch-...) for proxy auth |
| email | string | — | Email for JWT auth |
| password | string | — | Password for JWT auth |
| baseURL | string | https://tchavi.com/api | API base URL |
| maxRetries | number | 2 | Max retries on transient errors |
| timeout | number | 60000 | Request timeout (ms) |
If apiKey is omitted, the SDK falls back to process.env.TCHAVI_API_KEY.
Per-request options
Every resource method accepts an optional second argument with signal (for cancellation) and timeout (to override the client-wide timeout for one call):
const controller = new AbortController();
setTimeout(() => controller.abort(), 5_000);
const completion = await client.chat.completions.create(
{ model: 'gpt-4o-mini', messages: [{ role: 'user', content: 'Hi' }] },
{ signal: controller.signal, timeout: 30_000 },
);License
MIT
