import { p as RagConfig, v as UniversalRagConfig, V as VectorDBConfig, w as UpsertDocument, y as VectorMatch, G as GraphDBConfig, H as GraphNode, J as Edge, K as GraphSearchResult, L as LLMConfig, f as EmbeddingConfig, I as ILLMProvider, x as VectorDBProvider, i as LLMProvider, g as EmbeddingProvider, R as RAGConfig, u as UIConfig, U as UITransformationResponse, C as ChatMessage, d as ChatOptions, E as EmbedOptions, h as IngestDocument, e as ChatResponse } from './ILLMProvider-DO5gj-e5.js'; export { A as AuthMode, M as BarChartData, N as CarouselProduct, Q as IRetriever, j as LatencyBreakdown, S as LineChartDataPoint, X as MessageRole, Y as MetricCardData, O as ObservabilityTrace, Z as PieChartData, P as Product, k as ProjectAiSettings, l as ProjectAuthSettings, m as ProjectBrandingSettings, c as ProjectChatSettings, n as ProjectTelemetrySettings, o as ProjectWidgetSettings, q as RagMessage, r as RetrievalConfig, _ as RetrievalResult, s as RetrievedChunk, $ as RetrivoraChunkMetadata, a0 as RetrivoraIngestedDocument, a1 as ScatterPlotDataPoint, a2 as SuggestionsResponse, a3 as TableData, T as ThemeMode, t as TokenUsage, a as UseRagChatOptions, b as UseRagChatReturn, a4 as VisualizationType, W as WidgetPosition, z as WorkflowConfig, B as createDefaultProjectSettings, D as normalizeProjectSettings, F as projectSettingsToUiConfig } from './ILLMProvider-DO5gj-e5.js'; import { o as DecisionContext, q as IntentCategory, I as IRenderRule, G as RenderDecision, p as IRendererStrategy } from './index-8vijDPfT.js'; export { V as ArchitectureCardProps, A as AuthenticationException, B as BatchOptions, f as BatchProcessor, g as BatchResult, h as ChartType, e as ChatViewportSize, C as ChatWidgetProps, a as ChatWindowProps, i as Chunk, j as ChunkOptions, c as ClientConfig, m as ConfigFetcher, b as ConfigProviderProps, n as ConfigurationException, W as DocumentChunker, D as DocumentUploadProps, E as EmbeddingFailedException, X as LicenseConfigResolver, L as LicenseTierConfig, r as LicenseValidationError, s as LicenseValidationRequest, t as LicenseValidationResponse, u as LicenseValidator, M as MessageBubbleProps, Y as Pipeline, Z as PipelineStep, P as ProductCardProps, d as ProductCarouselProps, v as ProviderCredentials, w as ProviderNotFoundException, _ as ProviderPill, x as RateLimitException, R as RemoteConfig, y as RemoteEmbeddingConfig, z as RemoteLLMConfig, F as RemoteVectorConfig, $ as RenderSectionDecision, H as RenderType, J as RetrievalException, K as Retrivora, N as RetrivoraError, O as RetrivoraErrorCode, Q as SDKVersionUnsupportedError, T as SDK_VERSION, a0 as Snippet, S as SourceCardProps, a1 as wrapError } from './index-8vijDPfT.js'; import { I as IProviderValidator, a as IProviderHealthChecker, H as HealthCheckResult } from './index-DkOhRqEc.js'; export { C as ConfigValidator, b as HandlerOptions, V as ValidationError, c as VectorPlugin, d as createChatHandler, e as createFeedbackHandler, f as createHealthHandler, g as createHistoryHandler, h as createIngestHandler, i as createRagHandler, j as createSessionsHandler, k as createStreamHandler, l as createUploadHandler, s as sseErrorFrame, m as sseFrame, n as sseMetaFrame, o as sseTextFrame } from './index-DkOhRqEc.js'; import 'react'; import 'next/server'; /** * Decoded payload of a Retrivora license JWT. */ interface LicensePayload { projectId: string; expiresAt: number; tier: string; licenseStatus?: string; minimumSupportedVersion?: string; forceUpgrade?: boolean; } /** * Validates licenses against the central Retrivora API. * Replaces the old zero-latency local cryptographic verifier. */ declare class LicenseVerifier { private static readonly cache; private static readonly CACHE_TTL_MS; /** * Computes a deterministic hardware fingerprint to enforce node-locked licensing. */ private static generateMachineFingerprint; /** * Validates the license key asynchronously by calling the Retrivora backend. * * @param licenseKey - Base64url signed JWT license key. * @param currentProjectId - Project namespace ID. * @param provider - Optional provider for tier checks. */ static verifyAsync(licenseKey: string | undefined, currentProjectId: string, provider?: string): Promise; static verifyIP(licenseKey: string | undefined): Promise; static extractTier(licenseKey: string | undefined): string; } /** * ConfigResolver — validates and normalizes host configuration. * It merges host-provided config with environment defaults. * * The `getRagConfig()` result is memoized at module level so that * environment variables are only parsed once per process, avoiding * repeated work in serverless cold starts and per-request handler calls. */ declare class ConfigResolver { /** * Resolves the final configuration by merging host-provided config with environment defaults. * @param hostConfig - Partial configuration passed from the host application. */ static resolve(hostConfig?: Partial, env?: Record): RagConfig; /** * Resolves the public SDK config shape used by `new Retrivora({...})`. * Supports aliases from the product prompt while preserving existing env * fallback behavior. */ static resolveUniversal(hostConfig?: UniversalRagConfig, env?: Record): RagConfig; /** * Validates the configuration for required fields. */ static validate(config: RagConfig): void; private static mergeRetrievalWorkflow; } /** * BaseVectorProvider — Abstract base class for all vector database providers. * Each provider (Pinecone, Milvus, Redis, etc.) must extend this class. */ declare abstract class BaseVectorProvider { protected readonly config: VectorDBConfig; protected indexName: string; protected projectId?: string; protected namespace?: string; constructor(config: VectorDBConfig); /** * Initialise the connection (create tables, verify index, etc.) */ abstract initialize(): Promise; /** * Insert or update a single vector + content pair. */ abstract upsert(doc: UpsertDocument, namespace?: string): Promise; /** * Batch upsert for efficient ingestion of many documents. */ abstract batchUpsert(docs: UpsertDocument[], namespace?: string): Promise; /** * Find the top-K most similar vectors to the query vector. */ abstract query(vector: number[], topK: number, namespace?: string, filter?: Record): Promise; /** * Delete a stored vector by ID. */ abstract delete(id: string | number, namespace?: string): Promise; /** * Delete all vectors in a namespace (full data reset for a project). */ abstract deleteNamespace(namespace: string): Promise; /** * Check if the underlying DB is reachable. */ abstract ping(): Promise; /** * Gracefully close the connection. */ abstract disconnect(): Promise; /** * Returns a validator for this provider's configuration. */ static getValidator?(): IProviderValidator; /** * Returns a health checker for this provider. */ static getHealthChecker?(): IProviderHealthChecker; /** * Remove internal keys (starting with __) and queryText from a filter object * before passing it to an external provider that might not support them. */ protected sanitizeFilter(filter?: Record): Record; } /** * BaseGraphProvider — Abstract base class for Graph DB providers. */ declare abstract class BaseGraphProvider { protected config: GraphDBConfig; constructor(config: GraphDBConfig); /** * Initialise connection to the graph database. */ abstract initialize(): Promise; /** * Add nodes to the graph. */ abstract addNodes(nodes: GraphNode[]): Promise; /** * Add edges (relationships) to the graph. */ abstract addEdges(edges: Edge[]): Promise; /** * Query the graph for relevant nodes and edges. */ abstract query(queryText: string, limit?: number): Promise; /** * Check if the database is reachable. */ abstract ping(): Promise; /** * Close connection. */ abstract disconnect(): Promise; } /** * ProviderRegistry — dynamic provider loader for Vector DBs and LLMs. */ type VectorProviderClass = { new (config: VectorDBConfig): BaseVectorProvider; getValidator?: () => IProviderValidator; getHealthChecker?: () => IProviderHealthChecker; }; declare class ProviderRegistry { private static vectorProviders; private static graphProviders; private static vectorValidators; private static vectorHealthCheckers; private static llmValidators; private static llmHealthCheckers; static registerVectorProvider(name: string, providerClass: VectorProviderClass): void; static getVectorValidator(provider: string): Promise; static getVectorHealthChecker(provider: string): Promise; private static loadVectorProviderClass; static createVectorProvider(config: VectorDBConfig): Promise; static createGraphProvider(config: GraphDBConfig): Promise; static createLLMProvider(llmConfig: LLMConfig, embeddingConfig?: EmbeddingConfig): ILLMProvider; static registerLLMProvider(name: string, factory: (config: LLMConfig) => ILLMProvider): void; static createEmbeddingProvider(embeddingConfig: EmbeddingConfig): ILLMProvider; } /** * ProviderHealthCheck.ts — Pre-flight validation for vector DB and LLM providers. * Performs connectivity tests, credential validation, and capability checks. */ declare class ProviderHealthCheck { /** * Validates vector database configuration before initialization. */ static checkVectorProvider(config: VectorDBConfig): Promise; private static fallbackVectorHealthCheck; /** * Validates LLM provider configuration. */ static checkLLMProvider(config: LLMConfig): Promise; /** * Runs comprehensive health checks on all configured providers in parallel. */ static checkAll(vectorDbConfig: VectorDBConfig, llmConfig: LLMConfig, embeddingConfig?: EmbeddingConfig): Promise<{ vectorDb: HealthCheckResult; llm: HealthCheckResult; embedding?: HealthCheckResult; allHealthy: boolean; }>; } /** * serverConfig.ts — reads RagConfig from environment variables at runtime. * * This keeps secrets server-side and never exposes them to the browser. * Consumer projects set these env vars in their .env.local file. * * Supported VECTOR_DB_PROVIDER values and their required env vars: * pinecone → PINECONE_API_KEY, PINECONE_INDEX * pgvector / * postgresql → PGVECTOR_CONNECTION_STRING, VECTOR_DB_INDEX * mongodb → MONGODB_URI, MONGODB_DB, MONGODB_COLLECTION * qdrant → QDRANT_URL, QDRANT_API_KEY * milvus → MILVUS_URL (e.g. http://localhost:19530) * chromadb → CHROMADB_URL (e.g. http://localhost:8000) * weaviate → WEAVIATE_URL, WEAVIATE_API_KEY * redis → REDIS_URL, REDIS_API_KEY * rest / * universal_rest→ VECTOR_BASE_URL, VECTOR_DB_REST_API_KEY */ /** * Runtime tier configuration injected from the /api/v1/config + /api/v1/credentials * API responses at app startup. This overrides static env-var defaults so that * the tier-based model selection from the license is applied to all SDK calls. */ interface RuntimeTierConfig { llmModel?: string; embeddingModel?: string; /** Custom system prompt from project configuration */ systemPrompt?: string; /** LiteLLM master key for authenticating with llm.retrivora.com */ litellmApiKey?: string; /** LiteLLM gateway base URL (defaults to https://llm.retrivora.com/api/v1) */ llmBaseUrl?: string; embeddingBaseUrl?: string; maxTokens?: number; topK?: number; chunkSize?: number; chunkOverlap?: number; tier?: string; allowedModels?: string[]; } /** * Inject tier-based config fetched from /api/v1/config + /api/v1/credentials. * Call this once after successful license init (e.g. in validate-env.ts). */ declare function injectRuntimeConfig(config: RuntimeTierConfig): void; /** Returns the currently injected runtime config, or null if not yet set. */ declare function getRuntimeConfig(): RuntimeTierConfig | null; declare function getRagConfig(baseConfig?: Partial, env?: Record): RagConfig; /** * ConfigBuilder — Fluent, type-safe configuration builder for RagConfig * * Simplifies host application setup with a builder pattern while maintaining * type safety and validation. * * Features: * - Fluent API for easy configuration * - Type-safe provider selection * - Automatic environment variable resolution * - Built-in validation at build() time * - Support for presets * * @example * const config = new ConfigBuilder() * .vectorDb('pinecone', { apiKey: process.env.PINECONE_API_KEY }) * .llm('openai', 'gpt-4o', process.env.OPENAI_API_KEY) * .embedding('openai', 'text-embedding-3-small') * .projectId('my-app') * .build(); * * const plugin = new VectorPlugin(config); */ declare class ConfigBuilder { private _projectId?; private _vectorDb?; private _llm?; private _embedding?; private _ui?; private _rag?; private _graphDb?; /** * Set the project/application ID for namespacing */ projectId(id: string): this; /** * Configure the vector database provider */ vectorDb(provider: VectorDBProvider | 'universal-rest' | 'auto', options?: Record): this; /** * Configure the LLM provider for chat */ llm(provider: LLMProvider | 'auto', model?: string, apiKey?: string, options?: Record): this; /** * Configure the embedding provider */ embedding(provider: EmbeddingProvider | 'auto', model?: string, apiKey?: string, options?: Record): this; /** * Configure the graph database provider */ graphDb(provider: string | 'auto', options?: Record): this; /** * Set RAG-specific pipeline parameters */ rag(options: RAGConfig): this; /** * Set UI branding and appearance options. * Accepts the full UIConfig interface. */ ui(options: UIConfig): this; /** * Build and return the final RagConfig. * Throws if required fields (projectId, vectorDb, llm, embedding) are not set. */ build(): RagConfig; /** * Build and return as JSON for serialization */ toJSON(): string; private _autoDetectVectorDb; private _autoDetectLLM; private _autoDetectEmbedding; private _autoDetectGraphDb; } /** * Preset configurations for common provider combinations */ declare const PRESETS: { /** OpenAI + Pinecone: Production-ready cloud setup */ readonly 'openai-pinecone': { readonly vectorDb: "pinecone"; readonly llm: "openai"; readonly embedding: "openai"; }; /** Claude + Qdrant: Open-source vector DB + proprietary LLM */ readonly 'claude-qdrant': { readonly vectorDb: "qdrant"; readonly llm: "anthropic"; readonly embedding: "openai"; }; /** Local development: Ollama + local Qdrant */ readonly 'local-dev': { readonly vectorDb: "qdrant"; readonly llm: "ollama"; readonly embedding: "ollama"; }; /** Fully open-source: Ollama LLM + Qdrant + Ollama embeddings */ readonly 'fully-open-source': { readonly vectorDb: "qdrant"; readonly llm: "ollama"; readonly embedding: "ollama"; }; /** PostgreSQL stack: pgvector + OpenAI */ readonly 'postgres-openai': { readonly vectorDb: "postgresql"; readonly llm: "openai"; readonly embedding: "openai"; }; /** Enterprise MongoDB: MongoDB Atlas with OpenAI */ readonly 'mongodb-openai': { readonly vectorDb: "mongodb"; readonly llm: "openai"; readonly embedding: "openai"; }; /** Redis stack for caching + search */ readonly 'redis-openai': { readonly vectorDb: "redis"; readonly llm: "openai"; readonly embedding: "openai"; }; }; type PresetName = keyof typeof PRESETS; /** * Helper to create a ConfigBuilder pre-seeded with a named preset. */ declare function createFromPreset(presetName: PresetName): ConfigBuilder; /** * EmbeddingStrategy — Unified strategy for handling different embedding scenarios * * Automatically determines whether to: * 1. Use the LLM provider's built-in embedding (integrated) * 2. Use a separate embedding provider (fallback) * 3. Use an external embedding service * * This removes special-case handling from Pipeline and consolidates embedding logic. */ declare enum EmbeddingStrategy { /** * LLM provider handles both chat and embeddings * Example: OpenAI for both GPT and embeddings */ INTEGRATED = "integrated", /** * Use separate embedding provider different from LLM * Example: Anthropic (chat) + OpenAI (embeddings) */ SEPARATE = "separate", /** * Use standalone embedding service * Example: Dedicated embedding API */ EXTERNAL = "external" } interface EmbeddingStrategyResult { strategy: EmbeddingStrategy; embeddingProvider: ILLMProvider; llmProvider: ILLMProvider; } /** * Determines the optimal embedding strategy and initializes providers */ declare class EmbeddingStrategyResolver { /** * Determine strategy based on LLM and embedding configs */ static determineStrategy(llmConfig: LLMConfig, embeddingConfig?: EmbeddingConfig): EmbeddingStrategy; /** * Resolve and initialize providers according to the strategy */ static resolve(llmConfig: LLMConfig, embeddingConfig?: EmbeddingConfig): Promise; /** * Check if an LLM provider natively supports embeddings */ private static supportsEmbedding; /** * Get a human-readable description of the strategy */ static getDescription(strategy: EmbeddingStrategy): string; } /** * Pre-configured templates for popular AI and Vector services. * Use these as defaults in the Universal Adapters. */ declare const LLM_PROFILES: { 'openai-compatible': { chatPath: string; embedPath: string; responseExtractPath: string; embedExtractPath: string; chatPayloadTemplate: string; }; litellm: { chatPath: string; embedPath: string; responseExtractPath: string; embedExtractPath: string; chatPayloadTemplate: string; }; 'anthropic-claude': { chatPath: string; responseExtractPath: string; headers: { 'anthropic-version': string; }; chatPayloadTemplate: string; }; 'google-gemini': { chatPath: string; responseExtractPath: string; chatPayloadTemplate: string; }; 'github-copilot': { chatPayloadTemplate: string; chatPath: string; embedPath: string; responseExtractPath: string; embedExtractPath: string; }; 'ollama-standard': { chatPath: string; embedPath: string; responseExtractPath: string; embedExtractPath: string; chatPayloadTemplate: string; embedPayloadTemplate: string; }; }; declare const VECTOR_PROFILES: { 'pinecone-rest': { queryPath: string; upsertPath: string; responseExtractPath: string; idPath: string; scorePath: string; contentPath: string; metadataPath: string; queryPayloadTemplate: string; }; 'mongodb-atlas': { queryPath: string; responseExtractPath: string; idPath: string; scorePath: string; contentPath: string; metadataPath: string; queryPayloadTemplate: string; }; chromadb: { queryPath: string; upsertPath: string; responseExtractPath: string; idPath: string; scorePath: string; contentPath: string; metadataPath: string; }; qdrant: { queryPath: string; upsertPath: string; responseExtractPath: string; idPath: string; scorePath: string; contentPath: string; metadataPath: string; }; }; /** * DocumentParser — handles text extraction from various file formats. * Supported: .txt, .md, .json, .csv, .pdf, .docx, .doc, .xlsx, .xls */ declare class DocumentParser { /** * Extract text from a File or Buffer based on its type. */ static parse(file: File | Buffer, fileName: string, mimeType: string): Promise; private static readAsText; } interface DataSignals { rowCount: number; hasNumericFields: boolean; hasDateFields: boolean; hasCategoricalFields: boolean; isProductLike: boolean; numericFieldCount: number; categoricalFieldCount: number; } declare class IntentClassifier { /** * Fast, zero-latency classifier that maps a user query and optional data context * into a high-level IntentCategory. */ static classify(context: DecisionContext): { intent: IntentCategory; signals: DataSignals; }; /** * Extract key data structure signals from retrieved documents. */ static extractDataSignals(context: DecisionContext): DataSignals; private static isInformationLookup; private static isComparisonQuery; private static isProductQuery; private static isRecommendationQuery; private static isTrendQuery; private static isRankingQuery; private static isAnalyticsQuery; } declare class RuleEngine { private rules; constructor(); /** * Register standard rules in priority order. */ private registerDefaultRules; /** * Add or replace a rule in the engine. * Automatically keeps rules sorted by descending priority. */ registerRule(rule: IRenderRule): void; /** * Evaluate context against rules in descending priority order. * Returns the first non-null RenderDecision. */ evaluate(context: DecisionContext, intent: IntentCategory): RenderDecision; /** * List all registered rules. */ getRegisteredRules(): Array<{ name: string; priority: number; }>; } declare class TextRendererStrategy implements IRendererStrategy { readonly type = "text"; render(data: unknown, options?: Record): UITransformationResponse; } declare class TableRendererStrategy implements IRendererStrategy { readonly type = "table"; render(data: unknown, options?: Record): UITransformationResponse; } declare class CarouselRendererStrategy implements IRendererStrategy { readonly type = "carousel"; render(data: unknown, options?: Record): UITransformationResponse; } declare class ChartRendererStrategy implements IRendererStrategy { readonly type = "chart"; render(data: unknown, options?: Record): UITransformationResponse; } declare class MixedRendererStrategy implements IRendererStrategy { readonly type = "mixed"; render(data: unknown, options?: Record): UITransformationResponse; } declare class RendererRegistry { private static strategies; /** * Register a new renderer strategy. * Enables seamless addition of custom visualizers (Timeline, Maps, Flow Diagrams, etc.). */ static registerStrategy(strategy: IRendererStrategy): void; /** * Retrieve a registered renderer strategy by type string. */ static getStrategy(type: string): IRendererStrategy; /** * Check if a renderer strategy is registered. */ static hasStrategy(type: string): boolean; /** * List all registered strategy types. */ static getRegisteredTypes(): string[]; } /** * High-Performance Visualization Decision Engine. * Intelligently determines whether to render text, table, carousel, chart, or mixed sections * BEFORE expensive visual generation or LLM visual calls execute. */ declare class VisualizationDecisionEngine { private static ruleEngine; private static cache; /** * Evaluate user query, documents, and context to produce a RenderDecision. * Execution time is < 1ms for cached or rule-matched queries. */ static decideVisualization(userQuery: string, retrievedDocuments?: VectorMatch[], llmResponse?: string, metadata?: Record): RenderDecision; /** * Convenience helper to decide AND render the data into a UITransformationResponse. */ static render(userQuery: string, retrievedDocuments?: VectorMatch[], llmResponse?: string, metadata?: Record): UITransformationResponse; /** * Register a custom rule in the rule engine. */ static registerRule(rule: IRenderRule): void; /** * Register a custom renderer strategy. */ static registerRendererStrategy(strategy: IRendererStrategy): void; /** * Clear the decision cache. */ static clearCache(): void; /** * Get size of current decision cache. */ static getCacheSize(): number; } /** * Top-level function export matching prompt specification. */ declare function decideVisualization(userQuery: string, retrievedDocuments?: VectorMatch[], llmResponse?: string, metadata?: Record): RenderDecision; declare class Rule1SpecificInfoRule implements IRenderRule { readonly name = "Rule1SpecificInfo"; readonly priority = 100; evaluate(context: DecisionContext, intent: IntentCategory): RenderDecision | null; } declare class Rule2ComparisonRule implements IRenderRule { readonly name = "Rule2Comparison"; readonly priority = 90; evaluate(context: DecisionContext, intent: IntentCategory): RenderDecision | null; } declare class Rule3ProductDiscoveryRule implements IRenderRule { readonly name = "Rule3ProductDiscovery"; readonly priority = 85; evaluate(context: DecisionContext, intent: IntentCategory): RenderDecision | null; } declare class Rule4AnalyticalRule implements IRenderRule { readonly name = "Rule4Analytical"; readonly priority = 80; evaluate(context: DecisionContext, intent: IntentCategory): RenderDecision | null; } declare class Rule5MixedResponseRule implements IRenderRule { readonly name = "Rule5MixedResponse"; readonly priority = 95; evaluate(context: DecisionContext, _intent: IntentCategory): RenderDecision | null; } declare class Rule6SmallResultSetRule implements IRenderRule { readonly name = "Rule6SmallResultSet"; readonly priority = 110; evaluate(context: DecisionContext, _intent: IntentCategory): RenderDecision | null; } declare class Rule7LargeTableRule implements IRenderRule { readonly name = "Rule7LargeTable"; readonly priority = 82; evaluate(context: DecisionContext, intent: IntentCategory): RenderDecision | null; } /** * PineconeProvider — Pinecone vector database implementation. */ declare class PineconeProvider extends BaseVectorProvider { private client; private apiKey; private licenseKey?; constructor(config: VectorDBConfig); private getControlPlaneUrl; static getValidator(): IProviderValidator; static getHealthChecker(): IProviderHealthChecker; initialize(): Promise; private getActiveIndex; upsert(doc: UpsertDocument, namespace?: string): Promise; batchUpsert(docs: UpsertDocument[], namespace?: string): Promise; query(vector: number[], topK: number, namespace?: string, filter?: Record): Promise; delete(id: string | number, namespace?: string): Promise; deleteNamespace(namespace: string): Promise; ping(): Promise; disconnect(): Promise; } /** * PostgreSQLProvider — PostgreSQL implementation using the pgvector extension. */ declare class PostgreSQLProvider extends BaseVectorProvider { private pool; private readonly dimensions; private readonly connectionString; private readonly tableName; constructor(config: VectorDBConfig); static getValidator(): IProviderValidator; static getHealthChecker(): IProviderHealthChecker; initialize(): Promise; upsert(doc: UpsertDocument, namespace?: string): Promise; batchUpsert(docs: UpsertDocument[], namespace?: string): Promise; query(vector: number[], topK: number, namespace?: string, filter?: Record): Promise; delete(id: string | number, namespace?: string): Promise; deleteNamespace(namespace: string): Promise; ping(): Promise; disconnect(): Promise; } /** * MultiTablePostgresProvider — PostgreSQL implementation that searches across * multiple existing tables with pre-existing embeddings. * * Extends BaseVectorProvider so it can be registered with ProviderRegistry. * Upsert operations are not supported — data is assumed to be managed externally * or via custom ingestion scripts that write directly to each table. */ declare class MultiTablePostgresProvider extends BaseVectorProvider { private pool; private readonly dimensions; private readonly connectionString; private tables; private searchFields; private readonly uploadTable; constructor(config: VectorDBConfig); initialize(): Promise; /** * Upsert a document by dynamically provisioning a table and columns. */ upsert(doc: UpsertDocument, namespace?: string): Promise; /** * Batch upsert documents by dynamically provisioning tables and columns based on CSV headers. */ batchUpsert(docs: UpsertDocument[], namespace?: string): Promise; /** * Query all configured tables and merge results, sorted by cosine similarity score. */ query(vector: number[], topK: number, _namespace?: string, _filter?: Record): Promise; delete(_id: string | number, _namespace?: string): Promise; deleteNamespace(_namespace: string): Promise; ping(): Promise; disconnect(): Promise; } /** * MongoDBProvider — MongoDB Atlas Vector Search implementation. */ declare class MongoDBProvider extends BaseVectorProvider { private client; private db?; private collection?; private dbName; private collectionName; private embeddingKey; private contentKey; private metadataKey; private initialized; constructor(config: VectorDBConfig); static getValidator(): IProviderValidator; static getHealthChecker(): IProviderHealthChecker; initialize(): Promise; upsert(doc: UpsertDocument, namespace?: string): Promise; batchUpsert(docs: UpsertDocument[], namespace?: string): Promise; query(vector: number[], topK: number, namespace?: string, filter?: Record): Promise; delete(id: string | number, namespace?: string): Promise; deleteNamespace(namespace: string): Promise; protected sanitizeFilter(filter?: Record): Record; ping(): Promise; disconnect(): Promise; } /** * MilvusProvider — Milvus implementation using its REST API v1. * * Required options: * { baseUrl: string } — e.g. "http://localhost:19530" * OR { uri: string } — alias for baseUrl * OR { host: string, port: number } — auto-constructs baseUrl * * Optional: { apiKey?: string, headers?: Record } */ declare class MilvusProvider extends BaseVectorProvider { private http; constructor(config: VectorDBConfig); initialize(): Promise; upsert(doc: UpsertDocument, namespace?: string): Promise; batchUpsert(docs: UpsertDocument[], namespace?: string): Promise; query(vector: number[], topK: number, namespace?: string, _filter?: Record): Promise; delete(id: string | number, namespace?: string): Promise; deleteNamespace(namespace: string): Promise; ping(): Promise; disconnect(): Promise; } /** * QdrantProvider — implementation for Qdrant using its REST API. * Fully dynamic: automatically discovers and indexes schema from available data. */ declare class QdrantProvider extends BaseVectorProvider { private http; private contentField; private metadataField; private isFlatPayload; private schemaDiscovered; constructor(config: VectorDBConfig); initialize(): Promise; /** * Samples points from the collection to discover available payload fields. */ private discoverSchema; /** * Ensures the collection exists. Creates it if missing. */ private ensureCollection; /** * Ensures that a payload field has an index. */ private ensureIndex; upsert(doc: UpsertDocument, namespace?: string): Promise; batchUpsert(docs: UpsertDocument[], namespace?: string): Promise; query(vector: number[], topK: number, namespace?: string, _filter?: Record): Promise; delete(id: string | number): Promise; deleteNamespace(_namespace: string): Promise; ping(): Promise; private normalizeId; disconnect(): Promise; } /** * ChromaDBProvider — ChromaDB implementation using its REST API. * * Required options: { baseUrl: string } — e.g. "http://localhost:8000" * Optional: { host?: string, port?: number } — used to construct baseUrl when baseUrl not set */ declare class ChromaDBProvider extends BaseVectorProvider { private http; private collectionId; constructor(config: VectorDBConfig); /** * Get or create the ChromaDB collection. */ initialize(): Promise; upsert(doc: UpsertDocument, namespace?: string): Promise; batchUpsert(docs: UpsertDocument[], namespace?: string): Promise; query(vector: number[], topK: number, namespace?: string, _filter?: Record): Promise; delete(id: string, namespace?: string): Promise; deleteNamespace(namespace: string): Promise; ping(): Promise; disconnect(): Promise; } /** * RedisProvider — Redis Vector Search implementation using Upstash REST API. * * Required options: * { baseUrl: string } — Upstash REST endpoint * OR { url: string } — alias for baseUrl * OR { host: string, port: number } — auto-constructs baseUrl * * Optional: { apiKey?: string } — bearer token (required for Upstash) * * Note: This provider targets the Upstash Vector REST API. * For bare Redis with RediSearch, use a custom REST wrapper or the * UniversalVectorProvider with custom templates. */ declare class RedisProvider extends BaseVectorProvider { private http; constructor(config: VectorDBConfig); initialize(): Promise; upsert(doc: UpsertDocument, namespace?: string): Promise; batchUpsert(docs: UpsertDocument[], namespace?: string): Promise; query(vector: number[], topK: number, namespace?: string, _filter?: Record): Promise; delete(id: string, namespace?: string): Promise; deleteNamespace(namespace: string): Promise; /** * Check reachability of the Upstash Vector API. */ ping(): Promise; disconnect(): Promise; } /** * WeaviateProvider — Weaviate implementation using its REST/GraphQL API. * * Required options: * { baseUrl: string } — e.g. "http://localhost:8080" * OR { url: string } — alias accepted for backwards compatibility * * Optional: { apiKey?: string } */ declare class WeaviateProvider extends BaseVectorProvider { private http; constructor(config: VectorDBConfig); initialize(): Promise; upsert(doc: UpsertDocument, namespace?: string): Promise; batchUpsert(docs: UpsertDocument[], namespace?: string): Promise; query(vector: number[], topK: number, namespace?: string, _filter?: Record): Promise; delete(id: string, _namespace?: string): Promise; deleteNamespace(namespace: string): Promise; ping(): Promise; disconnect(): Promise; private extractPrimitiveMetadata; private buildWhereFilter; private weaviateOperand; } /** * UniversalVectorProvider — Template-based REST integration for any vector database * * Enables connecting to any REST-based vector database with minimal configuration * through request/response mapping templates. * * Features: * - Template-based request/response mapping * - Automatic JSON path extraction * - Retry logic with exponential backoff * - Request batching * - Custom header support */ declare class UniversalVectorProvider extends BaseVectorProvider { private http; private readonly opts; constructor(config: VectorDBConfig); initialize(): Promise; upsert(doc: UpsertDocument, namespace?: string): Promise; batchUpsert(docs: UpsertDocument[], namespace?: string): Promise; query(vector: number[], topK: number, namespace?: string, filter?: Record): Promise; delete(id: string | number, namespace?: string): Promise; deleteNamespace(namespace: string): Promise; ping(): Promise; disconnect(): Promise; } /** * LLMFactory — instantiates the correct ILLMProvider based on llmConfig.provider. */ declare class LLMFactory { /** * Register a custom LLM provider factory at runtime. * * Use this to add support for any LLM backend (Azure OpenAI, Cohere, Mistral, * Bedrock, etc.) without modifying this library's source code. * * @example * // In your Next.js app initialization: * import { LLMFactory } from '@retrivora-ai/rag-engine/server'; * import { MyCustomProvider } from './providers/MyCustomProvider'; * * LLMFactory.register('my-provider', (config) => new MyCustomProvider(config)); * * // Then set in your .env.local: * // LLM_PROVIDER=my-provider */ static register(name: string, factory: (config: LLMConfig) => ILLMProvider): void; /** * Unregister a previously registered custom provider. */ static unregister(name: string): void; /** * List all registered provider names (built-in + custom). */ static listProviders(): string[]; static create(llmConfig: LLMConfig, embeddingConfig?: EmbeddingConfig): ILLMProvider; static getValidator(provider: LLMProvider): IProviderValidator | null; static getHealthChecker(provider: LLMProvider): IProviderHealthChecker | null; private static getProviderClass; /** * Creates a dedicated embedding-only provider. */ static createEmbeddingProvider(embeddingConfig: EmbeddingConfig): ILLMProvider; } /** * OpenAI LLM Provider */ declare class OpenAIProvider implements ILLMProvider { private readonly client; private readonly llmConfig; private readonly embeddingConfig?; constructor(llmConfig: LLMConfig, embeddingConfig?: EmbeddingConfig); static getValidator(): IProviderValidator; static getHealthChecker(): IProviderHealthChecker; chat(messages: ChatMessage[], context: string, options?: ChatOptions): Promise; chatStream(messages: ChatMessage[], context: string, options?: ChatOptions): AsyncIterable; embed(text: string, options?: EmbedOptions): Promise; batchEmbed(texts: string[], options?: EmbedOptions): Promise; ping(): Promise; } /** * Anthropic (Claude) LLM Provider */ declare class AnthropicProvider implements ILLMProvider { private readonly client; private readonly llmConfig; private readonly embeddingConfig?; constructor(llmConfig: LLMConfig, embeddingConfig?: EmbeddingConfig); static getValidator(): IProviderValidator; static getHealthChecker(): IProviderHealthChecker; chat(messages: ChatMessage[], context: string, options?: ChatOptions): Promise; chatStream(messages: ChatMessage[], context: string, options?: ChatOptions): AsyncIterable; embed(text: string, options?: EmbedOptions): Promise; batchEmbed(texts: string[], options?: EmbedOptions): Promise; ping(): Promise; } /** * Ollama LLM Provider (local / self-hosted) */ declare class OllamaProvider implements ILLMProvider { private readonly http; private readonly llmConfig; private readonly embeddingConfig?; constructor(llmConfig: LLMConfig, embeddingConfig?: EmbeddingConfig); static getValidator(): IProviderValidator; static getHealthChecker(): IProviderHealthChecker; chat(messages: ChatMessage[], context: string, options?: ChatOptions): Promise; chatStream(messages: ChatMessage[], context: string, options?: ChatOptions): AsyncIterable; embed(text: string, options?: EmbedOptions): Promise; batchEmbed(texts: string[], options?: EmbedOptions): Promise; ping(): Promise; } /** * Groq LLM Provider */ declare class GroqProvider implements ILLMProvider { private readonly client; private readonly llmConfig; constructor(llmConfig: LLMConfig, embeddingConfig?: EmbeddingConfig); static getValidator(): IProviderValidator; static getHealthChecker(): IProviderHealthChecker; chat(messages: ChatMessage[], context: string, options?: ChatOptions): Promise; chatStream(messages: ChatMessage[], context: string, options?: ChatOptions): AsyncIterable; embed(text: string, options?: EmbedOptions): Promise; batchEmbed(texts: string[], options?: EmbedOptions): Promise; ping(): Promise; } /** * Qwen LLM Provider (via Alibaba DashScope / ModelStudio compatible mode) */ declare class QwenProvider implements ILLMProvider { private readonly client; private readonly llmConfig; private readonly embeddingConfig?; constructor(llmConfig: LLMConfig, embeddingConfig?: EmbeddingConfig); static getValidator(): IProviderValidator; static getHealthChecker(): IProviderHealthChecker; chat(messages: ChatMessage[], context: string, options?: ChatOptions): Promise; chatStream(messages: ChatMessage[], context: string, options?: ChatOptions): AsyncIterable; embed(text: string, options?: EmbedOptions): Promise; batchEmbed(texts: string[], options?: EmbedOptions): Promise; ping(): Promise; } declare class UniversalLLMAdapter implements ILLMProvider { private readonly http; private readonly model; private readonly opts; private readonly systemPrompt; private readonly maxTokens; private readonly temperature; private readonly baseUrl; private readonly apiKey?; private readonly resolvedHeaders; constructor(config: LLMConfig | EmbeddingConfig); chat(messages: ChatMessage[], context?: string): Promise; /** * Streaming chat using native fetch + ReadableStream. * Parses OpenAI-compatible SSE frames: `data: {...}\n\n` */ chatStream(messages: ChatMessage[], context?: string): AsyncIterable; embed(text: string): Promise; batchEmbed(texts: string[]): Promise; ping(): Promise; } /** * LicensedRetrivora — End-user facing SDK that only requires: * - License Key (JWT from Retrivora) * - Project ID (workspace identifier) * * Everything else (models, vector DB, embeddings) is resolved from * the Retrivora admin dashboard based on tier. * * NOTE: This is a SERVER-ONLY module. Import from '@retrivora-ai/rag-engine/server' * Do NOT import in client components. */ interface LicensedRetrivoraOptions { licenseKey: string; projectId: string; userTelemetryUrl?: string; enableTelemetry?: boolean; } /** * End-user facing SDK for Retrivora RAG engine */ declare class LicensedRetrivora { private licenseKey; private projectId; private pipeline?; private ragConfig?; private tierConfig?; private initialized; constructor(options: LicensedRetrivoraOptions); /** * Generates a unique ID for correlating telemetry events. * Format: `{timestamp}-{random}` — not cryptographically secure, used for * tracing only. */ private generateId; /** * Initialize the SDK by validating license and fetching config */ initialize(): Promise; /** * Ingest documents (upload files to vector database) * Returns success/failure status to end-user */ ingest(documents: IngestDocument[]): Promise<{ success: boolean; message: string; documentIds?: string[]; }>; /** * Execute a user query and get response * Returns only the response text and sources (abstracted from underlying models) */ query(queryText: string, options?: { topK?: number; }): Promise; /** * Get license tier information (for UI display if needed) */ getTierInfo(): Promise<{ tier: string; model: string; embeddingModel: string; }>; /** * Cleanup and shutdown */ shutdown(): Promise; /** * Check if SDK is initialized */ isInitialized(): boolean; /** * Get current RAG configuration (for debugging). * * Fix DX-3: throws when called before `initialize()` so callers receive a * clear, actionable error instead of a silent `undefined` that causes a * confusing null-reference error downstream. Consistent with the behavior * of `query()` and `ingest()`. */ getConfig(): RagConfig; } /** * Convenience function to create and initialize SDK in one call */ declare function createRetrivora(options: LicensedRetrivoraOptions): Promise; /** * TelemetryService — Tracks LLM calls, embedding operations, and user interactions * for billing, analytics, and usage monitoring. * * Sends telemetry to both: * - Admin dashboard (retrivora.com) * - User's own dashboard (if configured) * * Fix PERF-5: replaced the `axios` runtime dependency with native `fetch`. * Axios added ~25KB gzipped to every consumer's bundle purely for non-critical * fire-and-forget POST calls. fetch is available in Node.js 18+ and all * Next.js deployment targets (Vercel, Edge, Node runtime). */ declare enum EventType { EMBEDDING_GENERATED = "embedding_generated", LLM_CHAT_COMPLETION = "llm_chat_completion", DOCUMENT_INGESTED = "document_ingested", QUERY_EXECUTED = "query_executed", ERROR_OCCURRED = "error_occurred", CONFIGURATION_LOADED = "configuration_loaded" } interface TelemetryEvent { eventType: EventType; projectId: string; timestamp: number; operationId?: string; durationMs?: number; model?: string; inputTokens?: number; outputTokens?: number; totalTokens?: number; embeddingModel?: string; vectorDimensions?: number; textLength?: number; documentId?: string; documentName?: string; documentSize?: number; chunksGenerated?: number; queryText?: string; resultCount?: number; errorCode?: string; errorMessage?: string; stackTrace?: string; metadata?: Record; } /** * Telemetry service for tracking usage, billing, and analytics */ declare class TelemetryService { private static readonly RETRIVORA_TELEMETRY_URL; private static readonly USER_TELEMETRY_URL_ENV_KEY; private projectId; private licenseKey; private userTelemetryUrl?; private batchSize; private flushIntervalMs; private eventQueue; private flushTimer?; private enabled; /** Default headers added to every telemetry POST request. */ private baseHeaders; constructor(projectId: string, licenseKey: string, userTelemetryUrl?: string); /** * Record a telemetry event */ recordEvent(event: Partial): void; /** * Record LLM completion event */ recordLLMCompletion(data: { model: string; inputTokens: number; outputTokens: number; durationMs: number; operationId?: string; metadata?: Record; }): void; /** * Record embedding generation event */ recordEmbeddingGenerated(data: { embeddingModel: string; vectorDimensions: number; textLength: number; durationMs: number; operationId?: string; }): void; /** * Record document ingestion event */ recordDocumentIngested(data: { documentId: string; documentName: string; documentSize: number; chunksGenerated: number; durationMs: number; }): void; /** * Record query execution event */ recordQueryExecuted(data: { queryText: string; resultCount: number; durationMs: number; operationId?: string; }): void; /** * Record error event */ recordError(error: Error, context?: Record): void; /** * Flush all queued events to telemetry endpoints */ flush(): Promise; /** * Start automatic flush interval */ private startAutoFlush; /** * Stop telemetry service and flush remaining events */ shutdown(): Promise; /** * Disable telemetry temporarily */ disable(): void; /** * Enable telemetry */ enable(): void; /** * Get current queue size (for debugging) */ getQueueSize(): number; } /** * Get or create global telemetry service instance */ declare function getTelemetryService(): TelemetryService | null; /** * Initialize global telemetry service */ declare function initializeTelemetryService(projectId: string, licenseKey: string, userTelemetryUrl?: string): TelemetryService; /** * Shutdown global telemetry service */ declare function shutdownTelemetryService(): Promise; export { AnthropicProvider, BaseVectorProvider, CarouselRendererStrategy, ChartRendererStrategy, ChatMessage, ChatOptions, ChatResponse, ChromaDBProvider, ConfigBuilder, ConfigResolver, DecisionContext, DocumentParser, Edge, EmbedOptions, EmbeddingConfig, EmbeddingProvider, EmbeddingStrategy, EmbeddingStrategyResolver, EventType, GraphNode, GraphSearchResult, GroqProvider, HealthCheckResult, ILLMProvider, IProviderHealthChecker, IProviderValidator, IRenderRule, IRendererStrategy, IngestDocument, IntentCategory, IntentClassifier, LLMConfig, LLMFactory, LLMProvider, LLM_PROFILES, type LicensePayload, LicenseVerifier, LicensedRetrivora, type LicensedRetrivoraOptions, MilvusProvider, MixedRendererStrategy, MongoDBProvider, MultiTablePostgresProvider, OllamaProvider, OpenAIProvider, PRESETS, PineconeProvider, PostgreSQLProvider, ProviderHealthCheck, ProviderRegistry, QdrantProvider, QwenProvider, RAGConfig, RagConfig, RedisProvider, RenderDecision, RendererRegistry, Rule1SpecificInfoRule, Rule2ComparisonRule, Rule3ProductDiscoveryRule, Rule4AnalyticalRule, Rule5MixedResponseRule, Rule6SmallResultSetRule, Rule7LargeTableRule, RuleEngine, type RuntimeTierConfig, TableRendererStrategy, type TelemetryEvent, TelemetryService, TextRendererStrategy, UIConfig, UITransformationResponse, UniversalLLMAdapter, UniversalRagConfig, UniversalVectorProvider, UpsertDocument, VECTOR_PROFILES, VectorDBConfig, VectorDBProvider, VectorMatch, VisualizationDecisionEngine, WeaviateProvider, createFromPreset, createRetrivora, decideVisualization, getRagConfig, getRuntimeConfig, getTelemetryService, initializeTelemetryService, injectRuntimeConfig, shutdownTelemetryService };