SDK

Examples

Real-world usage examples

Real-world examples using the EasyRAG SDK.

Basic Usage

Upload, Search, Query

typescript
import { EasyRAG } from '@easyrag/sdk'; const client = new EasyRAG(process.env.EASYRAG_API_KEY); // Upload const file = new File(['content'], 'doc.pdf', { type: 'application/pdf' }); await client.upload('my-dataset', file); // Search const results = await client.search('my-dataset', 'key features'); console.log(`Found ${results.data.length} results`); // Query const answer = await client.query('my-dataset', 'summarize this'); console.log(answer.data.result);

Multi-Tenant SaaS

Isolate user data with metadata and filters.

typescript
// Backend: Upload user's document async function uploadUserDocument(userId: string, file: File) { await client.upload(`tenant-${userId}`, file, { metadata: { [file.name]: { userId, uploadedAt: new Date().toISOString() } } }); } // Backend: Search user's documents only async function searchUserDocuments(userId: string, question: string) { return await client.search(`tenant-${userId}`, question); } // Alternative: Shared dataset with filters async function uploadToSharedDataset(userId: string, file: File) { await client.upload('shared-dataset', file, { metadata: { [file.name]: { userId } } }); } async function searchSharedDataset(userId: string, question: string) { return await client.search('shared-dataset', question, { filters: [ { key: 'userId', match: { value: userId } } ] }); }

Chat Application

Build a streaming chat interface.

typescript
import { EasyRAG } from '@easyrag/sdk'; class ChatBot { private client: EasyRAG; private datasetId: string; constructor(apiKey: string, datasetId: string) { this.client = new EasyRAG(apiKey); this.datasetId = datasetId; } async *chat(question: string) { let fullResponse = ''; for await (const chunk of this.client.queryStream( this.datasetId, question )) { if (chunk.delta) { fullResponse += chunk.delta; yield chunk.delta; } else if (chunk.error) { throw new Error(chunk.error); } } return fullResponse; } } // Usage const bot = new ChatBot(apiKey, 'knowledge-base'); for await (const text of bot.chat('What is the pricing?')) { process.stdout.write(text); }

Document Management System

Complete file management workflow.

typescript
import { EasyRAG } from '@easyrag/sdk'; class DocumentManager { private client: EasyRAG; constructor(apiKey: string) { this.client = new EasyRAG(apiKey); } // Upload with metadata async upload(datasetId: string, file: File, metadata: Record<string, any>) { return await this.client.upload(datasetId, file, { metadata: { [file.name]: metadata } }); } // List all documents async list(datasetId: string) { const { files } = await this.client.listFiles(datasetId); return files.map(f => ({ id: f.fileId, name: f.originalName, size: f.size, date: new Date(f.created), metadata: f.extraMeta })); } // Get download URL async getDownloadUrl(datasetId: string, fileId: string) { const { file } = await this.client.getFile(datasetId, fileId); return file.permanentUrl; } // Delete document async delete(datasetId: string, fileId: string) { await this.client.deleteFile(datasetId, fileId); } // Search documents async search(datasetId: string, query: string, filters?: any[]) { const results = await this.client.search(datasetId, query, { filters }); return results.data.map(r => ({ score: r.score, text: r.pageContent, source: r.metadata.originalName, metadata: r.metadata })); } } // Usage const dm = new DocumentManager(apiKey); await dm.upload('docs', file, { department: 'legal', confidential: true }); const docs = await dm.list('docs'); const results = await dm.search('docs', 'contract terms');

Customer Support Bot

Answer customer questions from knowledge base.

typescript
import { EasyRAG } from '@easyrag/sdk'; class SupportBot { private client: EasyRAG; private kbDataset: string; constructor(apiKey: string, kbDataset: string) { this.client = new EasyRAG(apiKey); this.kbDataset = kbDataset; } async answer(question: string, category?: string) { const filters = category ? [{ key: 'category', match: { value: category } }] : undefined; const answer = await this.client.query(this.kbDataset, question, { filters }); return { answer: answer.data.result, sources: answer.data.sources?.map(s => s.metadata.originalName) || [] }; } async findRelated(question: string) { const results = await this.client.search(this.kbDataset, question); return results.data .filter(r => r.score > 0.7) .slice(0, 5) .map(r => ({ title: r.metadata.title || r.metadata.originalName, excerpt: r.pageContent.slice(0, 200) + '...', score: r.score })); } } // Usage const bot = new SupportBot(apiKey, 'support-kb'); const response = await bot.answer('How do I reset my password?'); console.log('Answer:', response.answer); console.log('Sources:', response.sources); const related = await bot.findRelated('password reset'); console.log('Related articles:', related);

Legal Document Analysis

Search and analyze legal documents with filters.

typescript
import { EasyRAG } from '@easyrag/sdk'; class LegalAnalyzer { private client: EasyRAG; constructor(apiKey: string) { this.client = new EasyRAG(apiKey); } // Upload contract with metadata async uploadContract( file: File, metadata: { clientId: string; contractType: string; effectiveDate: string; expiryDate: string; } ) { return await this.client.upload('legal-docs', file, { metadata: { [file.name]: { ...metadata, uploadedAt: new Date().toISOString() } } }); } // Search specific client's contracts async searchClientContracts(clientId: string, query: string) { return await this.client.search('legal-docs', query, { filters: [ { key: 'clientId', match: { value: clientId } } ] }); } // Find termination clauses async findTerminationClauses(clientId: string) { return await this.client.search( 'legal-docs', 'termination clause notice period', { filters: [ { key: 'clientId', match: { value: clientId } } ] } ); } // Compare contracts async compareContracts(contractIds: string[]) { const results = await Promise.all( contractIds.map(id => this.client.query( 'legal-docs', 'Summarize key terms: payment, duration, termination' ) ) ); return results.map((r, i) => ({ contractId: contractIds[i], summary: r.data.result })); } } // Usage const analyzer = new LegalAnalyzer(apiKey); await analyzer.uploadContract(file, { clientId: 'client-123', contractType: 'service-agreement', effectiveDate: '2024-01-01', expiryDate: '2025-01-01' }); const clauses = await analyzer.findTerminationClauses('client-123');

Content Recommendation Engine

Recommend related content based on semantic similarity.

typescript
import { EasyRAG } from '@easyrag/sdk'; class ContentRecommender { private client: EasyRAG; constructor(apiKey: string) { this.client = new EasyRAG(apiKey); } async recommend( datasetId: string, currentContent: string, limit: number = 5 ) { const results = await this.client.search(datasetId, currentContent); return results.data .filter(r => r.score > 0.6) .slice(0, limit) .map(r => ({ id: r.metadata.fileId, title: r.metadata.title || r.metadata.originalName, excerpt: r.pageContent.slice(0, 150) + '...', relevance: r.score, category: r.metadata.category })); } async recommendByTags( datasetId: string, tags: string[], limit: number = 5 ) { // Search with tag filters const tagQuery = tags.join(' '); const results = await this.client.search(datasetId, tagQuery); return results.data .slice(0, limit) .map(r => ({ id: r.metadata.fileId, title: r.metadata.title || r.metadata.originalName, tags: r.metadata.tags || [], relevance: r.score })); } } // Usage const recommender = new ContentRecommender(apiKey); const related = await recommender.recommend( 'blog-posts', 'Introduction to machine learning and neural networks', 5 ); console.log('Related posts:', related);

Research Assistant

Help researchers search and summarize papers.

typescript
import { EasyRAG } from '@easyrag/sdk'; class ResearchAssistant { private client: EasyRAG; constructor(apiKey: string) { this.client = new EasyRAG(apiKey); } async uploadPaper(file: File, metadata: { title: string; authors: string[]; year: number; journal: string; tags: string[]; }) { return await this.client.upload('research-papers', file, { metadata: { [file.name]: metadata } }); } async searchPapers(query: string, filters?: { yearFrom?: number; yearTo?: number; journal?: string; tags?: string[]; }) { const filterList = []; if (filters?.journal) { filterList.push({ key: 'journal', match: { value: filters.journal } }); } const results = await this.client.search('research-papers', query, { filters: filterList.length > 0 ? filterList : undefined }); return results.data .filter(r => { if (filters?.yearFrom && r.metadata.year < filters.yearFrom) { return false; } if (filters?.yearTo && r.metadata.year > filters.yearTo) { return false; } return true; }) .map(r => ({ title: r.metadata.title, authors: r.metadata.authors, year: r.metadata.year, relevance: r.score, excerpt: r.pageContent.slice(0, 200) + '...' })); } async summarizePaper(fileId: string) { return await this.client.query( 'research-papers', 'Provide a comprehensive summary including: research question, methodology, key findings, and conclusions' ); } async *synthesize(topic: string) { yield* this.client.queryStream( 'research-papers', `Synthesize the current state of research on: ${topic}. Include key findings from multiple papers, areas of consensus and disagreement, and open questions.` ); } } // Usage const assistant = new ResearchAssistant(apiKey); const papers = await assistant.searchPapers('neural networks', { yearFrom: 2020, journal: 'Nature' }); for await (const text of assistant.synthesize('transformers in NLP')) { process.stdout.write(text.delta || ''); }

Error Handling Patterns

typescript
import { EasyRAG, EasyRAGError } from '@easyrag/sdk'; async function robustUpload(client: EasyRAG, file: File) { try { return await client.upload('dataset', file); } catch (error) { if (error instanceof EasyRAGError) { switch (error.status) { case 400: console.log('Invalid file:', error.message); break; case 401: console.log('Invalid API key'); break; case 402: console.log('Out of credits - please top up'); // Redirect to billing page break; case 413: console.log('File too large'); break; case 429: console.log('Rate limited, retry after:', error.details?.retryAfter); break; default: console.log('Upload failed:', error.message); } } else { console.log('Network error:', error); } throw error; } } // With retry logic async function uploadWithRetry( client: EasyRAG, file: File, maxRetries = 3 ) { for (let i = 0; i < maxRetries; i++) { try { return await client.upload('dataset', file); } catch (error) { if (error instanceof EasyRAGError && error.status === 500) { if (i < maxRetries - 1) { await new Promise(r => setTimeout(r, 1000 * (i + 1))); continue; } } throw error; } } }

Next Steps