/** * Gemini RAG Service * * Provides integration with Google Gemini API for RAG (Retrieval-Augmented Generation) * operations including file upload, vector store management, and semantic search. * * @module @wundr/mcp-server/services/gemini */ import type { IRAGService, RAGSearchOptions, RAGSearchResult, RAGServiceConfig, RAGStore, StoreConfig, StoreStats } from '../../tools/rag/types'; import { FileProcessorOptions } from './file-processor'; import { ChunkOptions } from './chunker'; export * from './chunker'; export * from './file-processor'; /** * Extended configuration for Gemini RAG Service */ export interface GeminiRAGConfig extends RAGServiceConfig { /** Model to use for generation (default: 'gemini-1.5-flash') */ generationModel?: string; /** Default chunk options */ chunkOptions?: ChunkOptions; /** Default file processor options */ fileProcessorOptions?: FileProcessorOptions; /** Maximum retries for API calls */ maxRetries?: number; /** Base delay for retry backoff in ms */ retryBaseDelay?: number; /** Enable debug logging */ debug?: boolean; } /** * Vector store configuration for creation */ export interface VectorStoreConfig { /** Store name */ name: string; /** Store description */ description?: string; /** Whether store persists across sessions */ persistent?: boolean; /** Embedding dimension (default: 768 for text-embedding-004) */ dimension?: number; /** Store configuration */ storeConfig?: StoreConfig; } /** * Document in vector store */ export interface VectorDocument { /** Unique document ID */ id: string; /** Source file path */ filePath: string; /** Document content */ content: string; /** Embedding vector */ embedding: number[]; /** Document metadata */ metadata: DocumentMetadata; /** Chunk information */ chunk: { index: number; startLine: number; endLine: number; totalChunks: number; }; } /** * Document metadata */ export interface DocumentMetadata { /** Source file path */ filePath: string; /** File name */ fileName: string; /** File extension */ extension: string; /** Programming language */ language?: string; /** Relative path */ relativePath?: string; /** Line range */ lineRange: { start: number; end: number; }; /** Custom metadata */ custom?: Record; } /** * Search query options */ export interface SearchOptions extends RAGSearchOptions { /** Rerank results using LLM */ rerank?: boolean; /** Include embeddings in results */ includeEmbeddings?: boolean; /** Metadata filters */ filters?: MetadataFilterItem[]; } /** * Metadata filter for search */ export interface MetadataFilterItem { /** Field to filter on */ field: string; /** Filter operator */ operator: 'eq' | 'ne' | 'gt' | 'lt' | 'gte' | 'lte' | 'in' | 'contains'; /** Filter value */ value: string | number | boolean | string[]; } /** * Search result with extended metadata */ export interface ExtendedSearchResult { /** Document ID */ documentId: string; /** Similarity score (0-1) */ score: number; /** Document content */ content: string; /** Document metadata */ metadata: DocumentMetadata; /** Chunk information */ chunk: { index: number; startLine: number; endLine: number; }; /** Embedding vector (if requested) */ embedding?: number[]; } /** * File upload options */ export interface UploadOptions { /** Custom metadata to add */ metadata?: Record; /** Override chunk options */ chunkOptions?: ChunkOptions; /** Process in parallel */ parallel?: boolean; /** Batch size for parallel processing */ batchSize?: number; } /** * Upload result */ export interface UploadResult { /** Store ID files were uploaded to */ storeId: string; /** Files successfully uploaded */ filesUploaded: string[]; /** Files that failed */ filesFailed: Array<{ path: string; error: string; }>; /** Total documents created */ documentsCreated: number; /** Total chunks created */ chunksCreated: number; /** Upload duration in ms */ durationMs: number; } /** * GeminiRAGService provides semantic search capabilities using Gemini embeddings. * * Features: * - Real Gemini API integration for embeddings * - Vector store management (create, delete, list) * - File upload and indexing with chunking * - Semantic search with metadata filtering * - Retry logic and error handling * - LLM-based reranking */ export declare class GeminiRAGService implements IRAGService { private readonly config; private readonly client; private readonly stores; private readonly searchCache; private readonly fileProcessor; private readonly chunker; constructor(config?: GeminiRAGConfig); /** * Log debug message */ private log; /** * Execute with retry logic */ private withRetry; /** * Check if error is retryable */ private isRetryableError; /** * Sleep helper */ private sleep; /** * Calculate cosine similarity between two vectors */ private cosineSimilarity; /** * Get nested value from object */ private getNestedValue; /** * Check if metadata matches filters */ private matchesFilters; /** * Build cache key for search results */ private buildCacheKey; /** * Get cached search result if valid */ private getCachedResult; /** * Generate embeddings for text using Gemini API */ generateEmbedding(text: string): Promise; /** * Generate embeddings for multiple texts (batched) */ generateEmbeddings(texts: string[]): Promise; /** * Search for relevant content based on a query */ search(query: string, targetPath: string, options?: RAGSearchOptions): Promise; /** * Execute multiple searches in parallel */ searchMultiple(queries: readonly string[], targetPath: string, options?: RAGSearchOptions): Promise; /** * Index a directory for search */ indexDirectory(path: string): Promise; /** * Check if a path is indexed */ isIndexed(path: string): Promise; /** * Create a new vector store */ createStore(config: VectorStoreConfig): Promise; /** * Get a vector store by ID */ getStore(storeId: string): Promise; /** * Delete a vector store */ deleteStore(storeId: string): Promise; /** * List all vector stores */ listStores(): Promise; /** * Update store metadata */ private updateStoreMetadata; /** * Convert path to store ID */ private pathToStoreId; /** * Find store by path */ private findStoreByPath; /** * Upload a single file to a store */ uploadFile(storeId: string, filePath: string, options?: UploadOptions): Promise; /** * Upload multiple files to a store */ uploadFiles(storeId: string, filePaths: string[], options?: UploadOptions): Promise; /** * Upload all files in a directory to a store */ uploadDirectory(storeId: string, directory: string, options?: UploadOptions): Promise; /** * Search a store with extended options (filtering, reranking) */ searchStore(storeId: string, query: string, options?: SearchOptions): Promise; /** * Rerank results using LLM */ private rerankResults; /** * Match a file path against a glob-like pattern */ private matchPattern; /** * Get document by ID */ getDocument(storeId: string, documentId: string): Promise; /** * Delete document by ID */ deleteDocument(storeId: string, documentId: string): Promise; /** * Delete all documents from a file */ deleteFileDocuments(storeId: string, filePath: string): Promise; /** * Clear all documents from a store */ clearStore(storeId: string): Promise; /** * Get store statistics */ getStoreStats(storeId: string): Promise; /** * Export store to JSON (for persistence) */ exportStore(storeId: string): Promise; /** * Import store from JSON */ importStore(json: string): Promise; /** * Clear all caches */ clearCache(): void; /** * Clear only search cache (keep index) */ clearSearchCache(): void; /** * Estimate token count for a string * Uses a simple character-based estimation (approximately 4 characters per token) */ estimateTokens(text: string): number; } /** * Create a new GeminiRAGService instance */ export declare function createGeminiRAGService(config?: GeminiRAGConfig): GeminiRAGService; /** * Get or create the default GeminiRAGService instance */ export declare function getDefaultRAGService(): GeminiRAGService; //# sourceMappingURL=index.d.ts.map