Skip to content

TypeScript SDK

The official TypeScript SDK for the RAG API. Zero dependencies — uses native fetch.

Terminal window
npm install @rag-api/sdk
import { RAGClient } from '@rag-api/sdk';
const client = new RAGClient({ apiKey: 'YOUR_API_KEY' });
// Create a knowledge base
const kb = await client.createKnowledgeBase({ name: 'My Docs' });
// Upload a document
const file = new File([buffer], 'guide.pdf', { type: 'application/pdf' });
const doc = await client.uploadDocument(kb.id, file);
// Wait for processing
let status = doc.status;
while (status !== 'ready' && status !== 'failed') {
await new Promise((r) => setTimeout(r, 2000));
const updated = await client.getDocument(kb.id, doc.id);
status = updated.status;
}
// Search
const results = await client.search(kb.id, {
query: 'How do I reset my password?',
top_k: 5,
});
console.log(results.results[0].text);
const client = new RAGClient({
apiKey: 'YOUR_API_KEY',
baseUrl: 'https://api.useragex.com/api', // optional, this is the default
});
OptionTypeDefaultDescription
apiKeystring(required)Your API key
baseUrlstringhttps://api.useragex.com/apiAPI base URL
const kb = await client.createKnowledgeBase({
name: 'Product Docs',
description: 'All product documentation', // optional
metadata: { team: 'engineering' }, // optional
});
// Returns: KnowledgeBase { id, name, description, metadata, document_count, ... }
const { data, meta } = await client.listKnowledgeBases({
limit: 20, // optional, default 20
cursor: null, // optional, for pagination
});
// Paginate
if (meta.has_more) {
const nextPage = await client.listKnowledgeBases({ cursor: meta.cursor });
}
const kb = await client.getKnowledgeBase('kb_x1y2z3w4v5');
const updated = await client.updateKnowledgeBase('kb_x1y2z3w4v5', {
name: 'Updated Name',
description: 'New description',
metadata: { team: 'platform' },
});
await client.deleteKnowledgeBase('kb_x1y2z3w4v5');
// Cascades: deletes all documents and chunks
// From a File object
const file = new File([buffer], 'guide.pdf', { type: 'application/pdf' });
const doc = await client.uploadDocument(kb.id, file, {
metadata: { department: 'engineering', version: 2 },
filename: 'custom-name.pdf', // optional override
});
// Returns 202: Document { id, status: "pending", ... }
const doc = await client.uploadTextDocument(kb.id, {
text: 'Your text content here...',
name: 'notes.txt', // optional
metadata: { source: 'scraper' }, // optional
});
const { data, meta } = await client.listDocuments(kb.id, {
status: 'ready', // optional: filter by status
limit: 20,
cursor: null,
});
const doc = await client.getDocument(kb.id, 'doc_f6g7h8i9j0');
console.log(doc.status); // "pending" | "parsing" | "chunking" | "embedding" | "ready" | "failed"
console.log(doc.chunk_count); // number of chunks after processing
const updated = await client.updateDocumentMetadata(kb.id, doc.id, {
version: 3,
reviewed: true,
});
const { data, meta } = await client.listChunks(kb.id, doc.id, {
limit: 10,
});
for (const chunk of data) {
console.log(`[${chunk.chunk_index}] ${chunk.text.slice(0, 100)}...`);
console.log(` Tokens: ${chunk.token_count}, Page: ${chunk.start_page}`);
}
await client.deleteDocument(kb.id, 'doc_f6g7h8i9j0');
// Also deletes all chunks for this document
const results = await client.search(kb.id, {
query: 'How do I configure SSO?',
top_k: 5, // optional, default 10
rerank: true, // optional, default true
score_threshold: 0.5, // optional, default 0.0
filter: { department: { $eq: 'engineering' } }, // optional
include_metadata: true, // optional, default true
});
for (const result of results.results) {
console.log(`[${result.score.toFixed(2)}] ${result.document_name}`);
console.log(` ${result.text.slice(0, 200)}`);
}
console.log(`Reranked: ${results.usage.rerank_applied}`);
const usage = await client.getUsage();
console.log(`Plan: ${usage.plan}`);
console.log(`Pages: ${usage.usage.pages_processed} / ${usage.limits.pages_processed}`);
console.log(`Queries: ${usage.usage.search_queries} / ${usage.limits.search_queries}`);
import { RAGClient, RAGApiError } from '@rag-api/sdk';
try {
await client.search(kb.id, { query: 'test' });
} catch (err) {
if (err instanceof RAGApiError) {
console.error(err.code); // e.g. "NOT_FOUND"
console.error(err.message); // Human-readable message
console.error(err.statusCode); // HTTP status code
console.error(err.details); // Optional details object
}
}

See Error Handling for all error codes and retry strategies.

All types are exported from the package:

import type {
KnowledgeBase,
Document,
DocumentStatus,
Chunk,
SearchResult,
SearchResponse,
UsageResponse,
PaginatedResponse,
CreateKBInput,
UpdateKBInput,
SearchInput,
ListOptions,
ListDocumentsOptions,
UploadDocumentOptions,
TextIngestionInput,
RAGClientOptions,
} from '@rag-api/sdk';
type DocumentStatus = 'pending' | 'parsing' | 'chunking' | 'embedding' | 'ready' | 'failed';
interface SearchResult {
chunk_id: string;
document_id: string;
document_name: string;
text: string;
score: number;
metadata: {
chunk_index: number;
start_page: number | null;
end_page: number | null;
section_heading: string | null;
};
document_metadata: Record<string, unknown>;
}
interface SearchInput {
query: string;
top_k?: number; // 1-50, default 10
rerank?: boolean; // default true
filter?: Record<string, unknown>;
score_threshold?: number; // 0-1, default 0.0
include_metadata?: boolean; // default true
}
interface PaginatedResponse<T> {
data: T[];
meta: { cursor: string | null; has_more: boolean };
}