@sponge_theory/spt-neo-rag-client
v1.0.0
Published
Complete JavaScript/TypeScript client with 100% API coverage for SPT Neo RAG - Advanced RAG platform with knowledge graphs, RAPTOR, BM25, and enterprise features
Maintainers
Readme
SPT Neo RAG JavaScript/TypeScript Client
A comprehensive JavaScript/TypeScript client library for the SPT Neo RAG API with complete 100% API coverage. This client provides a fully-typed, async/await-based interface for all Neo RAG features including document management, semantic search, knowledge graphs, RAPTOR, BM25, and enterprise administration.
Status
API Coverage: ✅ 100% (165+ endpoints fully implemented)
Version: 1.0.0
Complete Feature Set
Core RAG Operations
- ✅ Authentication & User Management: Login, register, API keys, password management
- ✅ Knowledge Bases: Full CRUD with advanced configuration
- ✅ Document Management: Upload, process, scrape web pages, reprocess, content extraction
- ✅ Query Execution: Standard, streaming, multiple strategies, source retrieval
- ✅ Task Monitoring: Background job tracking and management
Advanced Retrieval
- ✅ Knowledge Graph: Entity extraction, relationship querying, path finding, full graph traversal
- ✅ RAPTOR Trees: Hierarchical document clustering and retrieval
- ✅ BM25 Index: Hybrid search with keyword-based retrieval
- ✅ Query Strategies: Adaptive, conversational, hybrid, and more
Enterprise Features
- ✅ Teams: Multi-user collaboration, member management, knowledge base sharing
- ✅ API Keys: Programmatic access management
- ✅ User Management: Full user lifecycle and permissions
- ✅ Webhooks: Event notifications and integrations
- ✅ Structured Schemas: Data extraction templates
Model & Infrastructure
- ✅ Model Management: LLM and embedding model configuration
- ✅ Admin Operations: System metrics, maintenance, license management
- ✅ Dashboard: Analytics, metrics, usage statistics
- ✅ System Settings: Configuration management
- ✅ Health Checks: Component monitoring and diagnostics
Features
- 🎯 100% API Coverage: All 165+ endpoints fully implemented and tested
- 🔐 Multiple Authentication: API keys, username/password, CSRF tokens
- 📄 Complete Document Lifecycle: Upload, process, scrape, reprocess, extract
- 🔍 Advanced Search: Vector similarity, BM25, hybrid, knowledge graph queries
- 🧠 Knowledge Graphs: Entity extraction, relationship mapping, path finding
- 🌳 RAPTOR: Hierarchical retrieval with tree-based clustering
- 👥 Enterprise Ready: Teams, permissions, webhooks, admin controls
- 📊 Background Tasks: Async processing with real-time monitoring
- 💬 Streaming: Real-time query response streaming
- 🎯 Full TypeScript: Complete type definitions for all models
- ⚡ Modern API: Promise-based async/await throughout
- 🌐 Cross-platform: Works in Node.js and browsers
Installation
npm install @sponge_theory/spt-neo-rag-clientOr with yarn:
yarn add @sponge_theory/spt-neo-rag-clientQuick Start
With API Key
import { NeoRagClient } from '@sponge_theory/spt-neo-rag-client';
const client = new NeoRagClient(
'https://your-neorag-instance.com',
'your-api-key'
);
// Query a knowledge base
const response = await client.query('What is RAG?', {
knowledgeBaseId: 'kb-id-here',
topK: 5,
});
console.log(response.result.answer);With Username/Password
import { NeoRagClient } from '@sponge_theory/spt-neo-rag-client';
const client = new NeoRagClient('https://your-neorag-instance.com');
// Login
await client.login('[email protected]', 'password');
// Use the client
const kbs = await client.knowledgeBases.listKnowledgeBases();
console.log(kbs);
// Logout when done
await client.logout();Usage Examples
Knowledge Base Management
// Create a knowledge base
const kb = await client.knowledgeBases.createKnowledgeBase({
name: 'My Knowledge Base',
description: 'A collection of important documents',
kb_type: 'default',
config: {
embedding_model: 'text-embedding-3-small',
chunk_size: 1000,
chunk_overlap: 200,
},
});
// List knowledge bases
const kbs = await client.knowledgeBases.listKnowledgeBases(0, 10);
// Get a specific knowledge base
const kbDetail = await client.knowledgeBases.getKnowledgeBase(kb.id);
// Update knowledge base
const updated = await client.knowledgeBases.updateKnowledgeBase(kb.id, {
description: 'Updated description',
});
// Delete knowledge base
await client.knowledgeBases.deleteKnowledgeBase(kb.id);Document Management
// Upload a document (Browser)
const fileInput = document.getElementById('file') as HTMLInputElement;
const file = fileInput.files[0];
const doc = await client.documents.uploadDocument(
file,
'My Document',
'kb-id-here',
{
description: 'Important research paper',
source: 'https://example.com/paper.pdf',
processorType: 'docling',
metadata: {
author: 'John Doe',
year: 2024,
},
}
);
// Upload a document (Node.js)
import fs from 'fs';
const fileBuffer = fs.readFileSync('./document.pdf');
const blob = new Blob([fileBuffer], { type: 'application/pdf' });
const doc = await client.documents.uploadDocument(
blob,
'My Document',
'kb-id-here'
);
// List documents
const docs = await client.documents.listDocuments('kb-id-here', 0, 10);
// Get document details
const docDetail = await client.documents.getDocument(doc.id);
// Get document chunks
const chunks = await client.documents.getDocumentChunks(doc.id, 0, 50);
// Get download URL
const downloadUrl = await client.documents.getDocumentDownloadUrl(doc.id);
// Update document
const updatedDoc = await client.documents.updateDocument(doc.id, {
description: 'Updated description',
doc_metadata: {
reviewed: true,
},
});
// Delete document
await client.documents.deleteDocument(doc.id);Querying
// Basic query
const response = await client.query('What is machine learning?', {
knowledgeBaseId: 'kb-id-here',
topK: 5,
similarityThreshold: 0.7,
});
console.log(response.result.answer);
console.log(response.result.sources);
// Advanced query with multiple knowledge bases
const multiKbResponse = await client.query('Explain neural networks', {
knowledgeBaseIds: ['kb-id-1', 'kb-id-2'],
queryStrategy: 'adaptive',
enableBm25: true,
bm25Weight: 0.3,
model: 'claude-3-5-sonnet-20241022',
provider: 'anthropic',
});
// Query specific documents
const docResponse = await client.query('Summarize the key points', {
knowledgeBaseId: 'kb-id-here',
documentsIds: ['doc-id-1', 'doc-id-2'],
queryConfig: {
temperature: 0.7,
max_tokens: 500,
},
});
// Using the queries endpoint directly
import { QueryRequest } from '@sponge_theory/spt-neo-rag-client';
const payload: QueryRequest = {
query: 'What are the benefits of RAG?',
knowledge_base_id: 'kb-id-here',
top_k: 3,
query_strategy: 'hybrid',
};
const result = await client.queries.query(payload);
// Get available query strategies
const strategies = await client.queries.getQueryStrategies();
console.log(strategies.strategies);
// Retrieve sources only (no answer generation)
const sources = await client.queries.retrieveSources(payload);
console.log(sources.sources);Streaming Queries
// Stream query responses
const stream = client.streamQuery('Explain quantum computing', {
knowledgeBaseId: 'kb-id-here',
topK: 5,
});
for await (const chunk of stream) {
if (chunk.type === 'text') {
process.stdout.write(chunk.content);
} else if (chunk.type === 'sources') {
console.log('\nSources:', chunk.sources);
}
}Task Monitoring
// Upload a document and monitor the processing task
const doc = await client.documents.uploadDocument(
file,
'Large Document',
'kb-id-here'
);
// The document object contains a task_id for background processing
if (doc.task_id) {
let task = await client.tasks.getTask(doc.task_id);
while (task.status === 'pending' || task.status === 'processing') {
console.log(`Progress: ${task.progress}%`);
await new Promise((resolve) => setTimeout(resolve, 2000));
task = await client.tasks.getTask(doc.task_id);
}
if (task.status === 'completed') {
console.log('Document processing completed!');
} else {
console.error('Document processing failed:', task.error);
}
}Health Checks
// Simple health check
const health = await client.health.healthCheck();
console.log(`Status: ${health.status}, Version: ${health.api_version}`);
// Detailed health check
const detailedHealth = await client.health.detailedHealthCheck();
console.log('Database:', detailedHealth.components.database.status);
console.log('Redis:', detailedHealth.components.redis.status);
console.log('Storage:', detailedHealth.components.storage.status);User Management
// Register a new user
const user = await client.register(
'[email protected]',
'securepassword',
'John Doe'
);
// Login
const token = await client.login('[email protected]', 'securepassword');
// Get current user info
const currentUser = await client.getCurrentUser();
console.log(currentUser);
// Change password
await client.changePassword('oldpassword', 'newpassword');
// Request password reset
await client.requestPasswordReset('[email protected]');Error Handling
import {
NeoRagApiError,
AuthenticationError,
ConfigurationError,
NetworkError,
} from '@sponge_theory/spt-neo-rag-client';
try {
const response = await client.query('Test query', {
knowledgeBaseId: 'invalid-id',
});
} catch (error) {
if (error instanceof NeoRagApiError) {
console.error(`API Error (${error.statusCode}):`, error.detail);
} else if (error instanceof AuthenticationError) {
console.error('Authentication failed:', error.message);
} else if (error instanceof ConfigurationError) {
console.error('Configuration error:', error.message);
} else if (error instanceof NetworkError) {
console.error('Network error:', error.message);
console.error('Original error:', error.originalError);
} else {
console.error('Unexpected error:', error);
}
}Advanced Features
LiteLLM API Key
For deployments using LiteLLM proxy:
const client = new NeoRagClient('https://your-neorag-instance.com', 'api-key');
// Set LiteLLM API key
client.setLiteLLMApiKey('litellm-key-here');
// Now all queries will include the LiteLLM API key header
const response = await client.query('Test query', {
knowledgeBaseId: 'kb-id-here',
});Custom Timeout
// Set a custom timeout (in milliseconds)
const client = new NeoRagClient(
'https://your-neorag-instance.com',
'api-key',
120000 // 2 minutes
);TypeScript Support
This library is written in TypeScript and provides complete type definitions:
import {
NeoRagClient,
KnowledgeBaseResponse,
DocumentResponse,
QueryResponse,
QueryRequest,
} from '@sponge_theory/spt-neo-rag-client';
const client = new NeoRagClient(baseUrl, apiKey);
// All responses are fully typed
const kb: KnowledgeBaseResponse = await client.knowledgeBases.createKnowledgeBase({
name: 'Typed KB',
});
const query: QueryRequest = {
query: 'Test',
knowledge_base_id: kb.id,
top_k: 5,
};
const result: QueryResponse = await client.queries.query(query);API Reference
NeoRagClient
Main client class providing access to all API functionality.
Constructor
new NeoRagClient(baseUrl: string, apiKey?: string, timeout?: number)Properties
knowledgeBases: Knowledge base operationsqueries: Query operationsdocuments: Document operationstasks: Task monitoringhealth: Health check operations
Methods
login(username, password): Authenticate with credentialslogout(): End the current sessionsetApiKey(apiKey): Set API key authenticationgetCurrentUser(): Get current user informationregister(email, password, name): Register new userchangePassword(current, new): Change user passwordrequestPasswordReset(email): Request password resetquery(query, options): Execute a query (convenience method)streamQuery(query, options): Stream query responsesetLiteLLMApiKey(key): Set LiteLLM API key
Endpoint Classes
Each endpoint class provides specialized methods for a specific domain:
- KnowledgeBaseEndpoints: Knowledge base CRUD operations
- QueryEndpoints: Query execution and strategy management
- DocumentEndpoints: Document upload, management, and retrieval
- TaskEndpoints: Background task monitoring
- HealthEndpoints: System health checks
Documentation
- API Coverage Analysis - ✅ 100% Complete - All 165+ endpoints implemented
- Endpoint Verification Report - Verification of correct API mapping
- Online Documentation - Full SDK documentation with examples
- API Reference - Complete REST API documentation
Contributing
Contributions are welcome! The SDK now has 100% API coverage.
Ways to Contribute:
- Add tests for new endpoints
- Improve documentation and examples
- Report bugs or suggest enhancements
- Add convenience methods
- Improve TypeScript types
How to Contribute:
- Follow the existing patterns in
src/endpoints/ - Ensure TypeScript types are properly defined
- Add tests for new functionality
- Submit a PR to the main SPT Neo RAG repository
See the main repository for contribution guidelines.
License
MIT License - see LICENSE file for details.
Support
- Documentation: https://docs.neo-rag.com
- Repository: https://github.com/sponge-theory/spt-neo-rag
- Issues: https://github.com/sponge-theory/spt-neo-rag/issues
- Email: [email protected]
Version
Current version: 1.0.0 ✅ 100% API Coverage
This client library provides complete parity with the SPT Neo RAG API and matches the Python SDK in functionality.
