@tolegoai/sdk
v0.1.0
Published
Official TypeScript SDK for Tolego AI — document intelligence API for business AI assistants.
Maintainers
Readme
@tolegoai/sdk
Official TypeScript SDK for Tolego AI — document intelligence API for business AI assistants.
- Zero runtime dependencies (uses native
fetch+FormData) - ESM + CJS, full type declarations
- Node 18+ and modern browsers
- Typed error classes for every failure mode
- Automatic retry with exponential backoff on 429 / 5xx / network errors
- ~13KB bundled
Install
npm install @tolegoai/sdk
# or
pnpm add @tolegoai/sdk
# or
yarn add @tolegoai/sdkQuick start
import { Tolego } from '@tolegoai/sdk';
import { readFileSync } from 'node:fs';
const tolego = new Tolego({ apiKey: process.env.TOLEGO_API_KEY! });
// Extract text from a PDF
const pdf = readFileSync('./invoice.pdf');
const { pageTexts } = await tolego.extractText(pdf);
console.log(pageTexts[0].text);
// Ask a question about a PDF
const qa = await tolego.qa(pdf, { question: 'What is the total amount?' });
console.log(qa.answer);
// Build a knowledge base and query it
const { kbId } = await tolego.kb.ingest(pdf, { kbName: 'Policies' });
const answer = await tolego.kb.query(kbId, { question: 'What is our refund window?' });
console.log(answer.answer, answer.sources);API reference
new Tolego(options)
const tolego = new Tolego({
apiKey: 'tolego_sk_...', // required
baseUrl: 'https://api.tolegoai.com', // optional — override for staging
timeoutMs: 120_000, // optional — per-request timeout
maxRetries: 2, // optional — auto-retry 429/5xx/network
fetch: customFetchImpl, // optional — inject a custom fetch
});Document endpoints
tolego.extractText(file, options?)
Extract per-page text from a PDF.
const result = await tolego.extractText(pdfBuffer, { pages: '1-5' });
// { pages: number, extracted: number, pageTexts: { page, text }[] }Cost: 1 credit per page.
tolego.qa(file, { question })
Ask a question about a PDF using full-document context (no vector DB).
const result = await tolego.qa(pdfBuffer, {
question: 'What is the warranty period?',
});
// { question, answer, pages, tokensUsed }Cost: 5 credits per page.
tolego.detectBlocks(image, { pageWidth?, pageHeight? })
Detect text blocks + bounding boxes on a page image (PNG / JPEG / WebP).
const result = await tolego.detectBlocks(pngBuffer, { pageWidth: 612, pageHeight: 792 });
if ('blocks' in result.result) {
for (const block of result.result.blocks) {
console.log(block.type, block.bbox);
}
}Cost: 3 credits per page image.
Intent routing
tolego.routeIntent({ intent, availableTools? })
Classify a natural-language intent into a structured tool call.
const result = await tolego.routeIntent({
intent: 'extract text from this invoice',
availableTools: [
{ name: 'extract-text', description: 'Extract text from a PDF' },
{ name: 'qa', description: 'Answer questions about a PDF' },
],
});
if ('tool' in result.result) {
console.log(result.result.tool, result.result.confidence);
}Cost: 1 credit per call.
Knowledge base
tolego.kb.ingest(file, { kbId? | kbName?, sourceName? })
Ingest a PDF into a knowledge base. Creates the KB if kbId is omitted.
// First time — create a new KB
const first = await tolego.kb.ingest(pdfBuffer, {
kbName: 'Product Catalogue',
sourceName: 'catalogue-q1.pdf',
});
// { kbId, documentId, pages, chunks }
// Subsequent — add to existing KB
await tolego.kb.ingest(anotherPdf, { kbId: first.kbId });Cost: 1 credit per page.
tolego.kb.ingestCsv(file, { kbId? | kbName?, sourceName? })
Ingest a CSV (e.g. product catalogue) into a KB. One row per chunk.
await tolego.kb.ingestCsv(csvBuffer, { kbId, sourceName: 'products.csv' });Cost: 1 credit per page of rows.
tolego.kb.query(kbId, { question, topK? })
Ask a question against a KB. Returns grounded answer + source chunks.
const result = await tolego.kb.query('kb-uuid', {
question: 'What is the return policy?',
topK: 5,
});
console.log(result.answer);
for (const source of result.sources) {
console.log(` — page ${source.pageNumber}, similarity ${source.similarity}`);
}Cost: 2 credits per call (fixed, regardless of result size).
Error handling
Every method throws a typed TolegoError subclass on failure. Catch the base class to handle all, or narrow to specific subclasses for targeted UX.
import {
Tolego,
TolegoAuthError,
TolegoBillingError,
TolegoRateLimitError,
TolegoValidationError,
TolegoServerError,
TolegoNetworkError,
} from '@tolegoai/sdk';
try {
await tolego.qa(pdf, { question: '...' });
} catch (err) {
if (err instanceof TolegoAuthError) {
// 401 — API key missing / invalid / revoked
} else if (err instanceof TolegoBillingError) {
// 402 — not enough credits, prompt user to top up
} else if (err instanceof TolegoRateLimitError) {
// 429 — back off; err.retryAfterSeconds is server-provided delay
} else if (err instanceof TolegoValidationError) {
// 400/403 — caller sent bad input or lacks permission
} else if (err instanceof TolegoServerError) {
// 5xx — already retried once; retry with backoff on your end or fail
} else if (err instanceof TolegoNetworkError) {
// fetch itself failed (DNS, TLS, CORS, timeout)
}
}Every error exposes status: number and body: unknown for debugging.
File inputs
All file-accepting methods take a FileInput:
- Node:
Buffer,Uint8Array,Blob(global since Node 20), or a{ name, data, contentType? }descriptor to force a specific filename. - Browser:
FileorBlob.
// Node with filename override
await tolego.extractText({
name: 'custom-name.pdf',
data: buffer,
contentType: 'application/pdf',
});
// Browser
const file = document.querySelector('input[type=file]')!.files![0];
await tolego.extractText(file);Retry behaviour
The SDK automatically retries requests that fail with:
- 429 Rate limited — honours server
Retry-Afterheader - 5xx Server errors — exponential backoff
- Network errors (fetch rejection) — exponential backoff
Backoff is exponential (1s, 2s, 4s...) capped at 30s, with up to 500ms jitter. Default max retries is 2. Set maxRetries: 0 to disable.
Not retried: 400, 401, 402, 403. These indicate a caller problem that a retry won't fix.
Pricing
See tolegoai.com/pricing for current per-endpoint credit costs. New accounts start with 500 free credits, no card required.
License
MIT © Tolego AI
