@juspay/neurolink 9.88.12 → 9.90.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/README.md +4 -3
  3. package/dist/adapters/tts/googleTTSHandler.d.ts +10 -0
  4. package/dist/adapters/tts/googleTTSHandler.js +27 -18
  5. package/dist/agent/directTools.js +1 -1
  6. package/dist/browser/neurolink.min.js +370 -356
  7. package/dist/index.d.ts +1 -1
  8. package/dist/index.js +1 -1
  9. package/dist/lib/adapters/tts/googleTTSHandler.d.ts +10 -0
  10. package/dist/lib/adapters/tts/googleTTSHandler.js +27 -18
  11. package/dist/lib/agent/directTools.js +1 -1
  12. package/dist/lib/index.d.ts +1 -1
  13. package/dist/lib/index.js +1 -1
  14. package/dist/lib/neurolink.js +1 -1
  15. package/dist/lib/rag/index.d.ts +1 -0
  16. package/dist/lib/rag/index.js +2 -0
  17. package/dist/lib/rag/stores/chroma.d.ts +90 -0
  18. package/dist/lib/rag/stores/chroma.js +281 -0
  19. package/dist/lib/rag/stores/index.d.ts +21 -0
  20. package/dist/lib/rag/stores/index.js +22 -0
  21. package/dist/lib/rag/stores/pgvector.d.ts +95 -0
  22. package/dist/lib/rag/stores/pgvector.js +400 -0
  23. package/dist/lib/rag/stores/pinecone.d.ts +85 -0
  24. package/dist/lib/rag/stores/pinecone.js +159 -0
  25. package/dist/lib/types/index.d.ts +2 -0
  26. package/dist/lib/types/index.js +2 -0
  27. package/dist/lib/types/rag.d.ts +30 -0
  28. package/dist/lib/types/vectorStoreChroma.d.ts +67 -0
  29. package/dist/lib/types/vectorStoreChroma.js +12 -0
  30. package/dist/lib/types/vectorStorePinecone.d.ts +48 -0
  31. package/dist/lib/types/vectorStorePinecone.js +12 -0
  32. package/dist/neurolink.js +1 -1
  33. package/dist/rag/index.d.ts +1 -0
  34. package/dist/rag/index.js +2 -0
  35. package/dist/rag/stores/chroma.d.ts +90 -0
  36. package/dist/rag/stores/chroma.js +280 -0
  37. package/dist/rag/stores/index.d.ts +21 -0
  38. package/dist/rag/stores/index.js +21 -0
  39. package/dist/rag/stores/pgvector.d.ts +95 -0
  40. package/dist/rag/stores/pgvector.js +399 -0
  41. package/dist/rag/stores/pinecone.d.ts +85 -0
  42. package/dist/rag/stores/pinecone.js +158 -0
  43. package/dist/types/index.d.ts +2 -0
  44. package/dist/types/index.js +2 -0
  45. package/dist/types/rag.d.ts +30 -0
  46. package/dist/types/vectorStoreChroma.d.ts +67 -0
  47. package/dist/types/vectorStoreChroma.js +11 -0
  48. package/dist/types/vectorStorePinecone.d.ts +48 -0
  49. package/dist/types/vectorStorePinecone.js +11 -0
  50. package/package.json +12 -8
package/dist/index.d.ts CHANGED
@@ -426,7 +426,7 @@ export { AgentExecuteRequestSchema, AlreadyRunningError, AuthenticationError, Au
426
426
  * console.log(response.answer);
427
427
  * ```
428
428
  */
429
- export { assembleContext, batchRerank, CharacterChunker, ChunkerRegistry, CohereRelevanceScorer, CrossEncoderReranker, CSVLoader, chunkText, createChunker, createContextWindow, createHybridSearch, createRAGPipeline, createVectorQueryTool, executeWithCircuitBreaker, extractMetadata, formatContextWithCitations, GraphRAG, getAvailableStrategies, getCircuitBreaker, getDefaultChunkerConfig, getRecommendedStrategy, HTMLChunker, HTMLLoader, InMemoryBM25Index, InMemoryVectorStore, JSONChunker as RAGJSONChunker, JSONLoader, LaTeXChunker, LLMMetadataExtractor, linearCombination, loadDocument, loadDocuments, MarkdownChunker, MarkdownLoader, MDocument, PDFLoader, prepareRAGTool, processDocument, RAGCircuitBreaker, RAGCircuitBreakerManager, RAGPipeline, RAGRetryHandler, RecursiveChunker, ragCircuitBreakerManager, reciprocalRankFusion, rerank, SemanticChunker, SentenceChunker, simpleRerank, summarizeContext, TextLoader, TokenChunker, WebLoader, } from "./rag/index.js";
429
+ export { assembleContext, batchRerank, CharacterChunker, ChunkerRegistry, CohereRelevanceScorer, CrossEncoderReranker, CSVLoader, chunkText, createChunker, createContextWindow, createHybridSearch, createRAGPipeline, createVectorQueryTool, executeWithCircuitBreaker, extractMetadata, formatContextWithCitations, GraphRAG, getAvailableStrategies, getCircuitBreaker, getDefaultChunkerConfig, getRecommendedStrategy, HTMLChunker, HTMLLoader, InMemoryBM25Index, InMemoryVectorStore, JSONChunker as RAGJSONChunker, JSONLoader, LaTeXChunker, LLMMetadataExtractor, linearCombination, loadDocument, loadDocuments, MarkdownChunker, MarkdownLoader, MDocument, PDFLoader, prepareRAGTool, processDocument, RAGCircuitBreaker, RAGCircuitBreakerManager, RAGPipeline, RAGRetryHandler, RecursiveChunker, ragCircuitBreakerManager, reciprocalRankFusion, rerank, SemanticChunker, ChromaVectorStore, PgVectorStore, PineconeVectorStore, SentenceChunker, simpleRerank, summarizeContext, TextLoader, TokenChunker, WebLoader, } from "./rag/index.js";
430
430
  export { ContextBuilder } from "./evaluation/contextBuilder.js";
431
431
  export { AuthProviderFactory, createAuthProvider, AuthProviderRegistry, AuthError as AuthErrorFactory, AuthErrorCodes, BaseAuthProvider, InMemorySessionStorage, AuthProviderError, createAuthMiddleware as createAuthProviderMiddleware, createRBACMiddleware, createProtectedMiddleware, createExpressAuthMiddleware, createRequestContext, extractToken, AuthMiddlewareError, AuthMiddlewareErrorCodes, UserRateLimiter, MemoryRateLimitStorage, RedisRateLimitStorage, createRateLimitByUserMiddleware, createAuthenticatedRateLimitMiddleware, createRateLimitStorage, SessionManager, MemorySessionStorage, RedisSessionStorage, createSessionStorage, AuthContextHolder, globalAuthContext, getAuthContext, getCurrentUser, getCurrentSession, isAuthenticated, hasRole, hasAnyRole, hasPermission, hasAllPermissions, requireAuth, requireRole, requirePermission, requireUser, runWithAuthContext, createAuthenticatedContext, RequestContext, NEUROLINK_RESOURCE_ID_KEY, NEUROLINK_THREAD_ID_KEY, createAuthValidatorFromProvider, } from "./auth/index.js";
432
432
  export { detectAndRedactPII } from "./utils/piiDetector.js";
package/dist/index.js CHANGED
@@ -683,7 +683,7 @@ extractMetadata, formatContextWithCitations,
683
683
  // Graph RAG
684
684
  GraphRAG, getAvailableStrategies, getCircuitBreaker, getDefaultChunkerConfig, getRecommendedStrategy, HTMLChunker, HTMLLoader, InMemoryBM25Index, InMemoryVectorStore, JSONChunker as RAGJSONChunker, JSONLoader, LaTeXChunker, LLMMetadataExtractor, linearCombination, loadDocument, loadDocuments, MarkdownChunker, MarkdownLoader, MDocument, PDFLoader,
685
685
  // RAG Integration for generate/stream
686
- prepareRAGTool, processDocument, RAGCircuitBreaker, RAGCircuitBreakerManager, RAGPipeline, RAGRetryHandler, RecursiveChunker, ragCircuitBreakerManager, reciprocalRankFusion, rerank, SemanticChunker, SentenceChunker, simpleRerank, summarizeContext, TextLoader, TokenChunker, WebLoader, } from "./rag/index.js";
686
+ prepareRAGTool, processDocument, RAGCircuitBreaker, RAGCircuitBreakerManager, RAGPipeline, RAGRetryHandler, RecursiveChunker, ragCircuitBreakerManager, reciprocalRankFusion, rerank, SemanticChunker, ChromaVectorStore, PgVectorStore, PineconeVectorStore, SentenceChunker, simpleRerank, summarizeContext, TextLoader, TokenChunker, WebLoader, } from "./rag/index.js";
687
687
  // Legacy RAGAS evaluation classes are now exported from the unified
688
688
  // evaluation block above (via ./evaluation/index.js barrel).
689
689
  // ContextBuilder is the only class not covered by the barrel export.
@@ -24,6 +24,7 @@ export declare class GoogleTTSHandler implements TTSHandler {
24
24
  * before invoking provider handlers, not inside this class.
25
25
  */
26
26
  readonly maxTextLength: number;
27
+ private readonly credentialsPath;
27
28
  constructor(credentialsPath?: string);
28
29
  /**
29
30
  * Validate that the provider is properly configured
@@ -31,6 +32,15 @@ export declare class GoogleTTSHandler implements TTSHandler {
31
32
  * @returns True if provider can generate TTS
32
33
  */
33
34
  isConfigured(): boolean;
35
+ /**
36
+ * Lazily construct (and cache) the Google Cloud TTS client.
37
+ *
38
+ * `@google-cloud/text-to-speech` is an optional dependency: importing it
39
+ * only happens here, on first actual use, so a handler instance can be
40
+ * constructed (e.g. during auto-registration at module load) without the
41
+ * package being installed.
42
+ */
43
+ private getClient;
34
44
  /**
35
45
  * Get available voices for the provider
36
46
  *
@@ -1,12 +1,3 @@
1
- /**
2
- * Google Cloud Text-to-Speech Handler
3
- *
4
- * Handler for Google Cloud Text-to-Speech API integration.
5
- *
6
- * @module adapters/tts/googleTTSHandler
7
- * @see https://cloud.google.com/text-to-speech/docs
8
- */
9
- import { TextToSpeechClient } from "@google-cloud/text-to-speech";
10
1
  import { TTSError, TTS_ERROR_CODES } from "../../utils/ttsProcessor.js";
11
2
  import { ErrorCategory, ErrorSeverity } from "../../constants/enums.js";
12
3
  import { logger } from "../../utils/logger.js";
@@ -36,11 +27,10 @@ export class GoogleTTSHandler {
36
27
  * before invoking provider handlers, not inside this class.
37
28
  */
38
29
  maxTextLength = GoogleTTSHandler.DEFAULT_MAX_TEXT_LENGTH;
30
+ credentialsPath;
39
31
  constructor(credentialsPath) {
40
- const path = credentialsPath ?? process.env.GOOGLE_APPLICATION_CREDENTIALS;
41
- if (path) {
42
- this.client = new TextToSpeechClient({ keyFilename: path });
43
- }
32
+ this.credentialsPath =
33
+ credentialsPath ?? process.env.GOOGLE_APPLICATION_CREDENTIALS;
44
34
  }
45
35
  /**
46
36
  * Validate that the provider is properly configured
@@ -48,7 +38,24 @@ export class GoogleTTSHandler {
48
38
  * @returns True if provider can generate TTS
49
39
  */
50
40
  isConfigured() {
51
- return this.client !== null;
41
+ return this.credentialsPath !== undefined;
42
+ }
43
+ /**
44
+ * Lazily construct (and cache) the Google Cloud TTS client.
45
+ *
46
+ * `@google-cloud/text-to-speech` is an optional dependency: importing it
47
+ * only happens here, on first actual use, so a handler instance can be
48
+ * constructed (e.g. during auto-registration at module load) without the
49
+ * package being installed.
50
+ */
51
+ async getClient() {
52
+ if (!this.client) {
53
+ const { TextToSpeechClient } = await import("@google-cloud/text-to-speech");
54
+ this.client = new TextToSpeechClient({
55
+ keyFilename: this.credentialsPath,
56
+ });
57
+ }
58
+ return this.client;
52
59
  }
53
60
  /**
54
61
  * Get available voices for the provider
@@ -60,7 +67,7 @@ export class GoogleTTSHandler {
60
67
  * @returns List of available voices
61
68
  */
62
69
  async getVoices(languageCode) {
63
- if (!this.client) {
70
+ if (!this.isConfigured()) {
64
71
  throw new TTSError({
65
72
  code: TTS_ERROR_CODES.PROVIDER_NOT_CONFIGURED,
66
73
  message: "Google Cloud TTS client not initialized. Set GOOGLE_APPLICATION_CREDENTIALS or pass credentials path.",
@@ -69,6 +76,7 @@ export class GoogleTTSHandler {
69
76
  retriable: false,
70
77
  });
71
78
  }
79
+ const client = await this.getClient();
72
80
  const span = SpanSerializer.createSpan(SpanType.TTS, "tts.google.listVoices", {
73
81
  "tts.operation": "listVoices",
74
82
  "tts.provider": "google",
@@ -84,7 +92,7 @@ export class GoogleTTSHandler {
84
92
  return this.voicesCache.voices;
85
93
  }
86
94
  // Call Google Cloud listVoices API
87
- const [response] = await this.client.listVoices(languageCode ? { languageCode } : {});
95
+ const [response] = await client.listVoices(languageCode ? { languageCode } : {});
88
96
  if (!response.voices || response.voices.length === 0) {
89
97
  logger.warn("Google Cloud TTS returned no voices");
90
98
  const endedSpan = SpanSerializer.endSpan(span, SpanStatus.OK);
@@ -149,7 +157,7 @@ export class GoogleTTSHandler {
149
157
  * @returns Audio buffer with metadata
150
158
  */
151
159
  async synthesize(text, options) {
152
- if (!this.client) {
160
+ if (!this.isConfigured()) {
153
161
  throw new TTSError({
154
162
  code: TTS_ERROR_CODES.PROVIDER_NOT_CONFIGURED,
155
163
  message: "Google Cloud TTS client not initialized. Set GOOGLE_APPLICATION_CREDENTIALS or pass credentials path.",
@@ -158,6 +166,7 @@ export class GoogleTTSHandler {
158
166
  retriable: false,
159
167
  });
160
168
  }
169
+ const client = await this.getClient();
161
170
  const voiceId = options.voice ?? "en-US-Neural2-C";
162
171
  const span = SpanSerializer.createSpan(SpanType.TTS, "tts.google.synthesize", {
163
172
  "tts.operation": "synthesize",
@@ -196,7 +205,7 @@ export class GoogleTTSHandler {
196
205
  volumeGainDb: options.volumeGainDb ?? 0.0,
197
206
  },
198
207
  };
199
- const [response] = await this.client.synthesizeSpeech(request, {
208
+ const [response] = await client.synthesizeSpeech(request, {
200
209
  timeout: GoogleTTSHandler.DEFAULT_API_TIMEOUT_MS,
201
210
  });
202
211
  const audioContent = response.audioContent;
@@ -3,7 +3,6 @@ import * as fs from "fs";
3
3
  import * as path from "path";
4
4
  import { execFile } from "child_process";
5
5
  import { logger } from "../utils/logger.js";
6
- import { VertexAI } from "@google-cloud/vertexai";
7
6
  import { CSVProcessor } from "../utils/csvProcessor.js";
8
7
  import { shouldEnableBashTool } from "../utils/toolUtils.js";
9
8
  import { tool } from "../utils/tool.js";
@@ -604,6 +603,7 @@ export const directAgentTools = {
604
603
  };
605
604
  }
606
605
  const limitedResults = Math.min(Math.max(maxResults, 1), 5);
606
+ const { VertexAI } = await import("@google-cloud/vertexai");
607
607
  const vertex_ai = new VertexAI({
608
608
  project: hasProjectId,
609
609
  location: projectLocation,
@@ -426,7 +426,7 @@ export { AgentExecuteRequestSchema, AlreadyRunningError, AuthenticationError, Au
426
426
  * console.log(response.answer);
427
427
  * ```
428
428
  */
429
- export { assembleContext, batchRerank, CharacterChunker, ChunkerRegistry, CohereRelevanceScorer, CrossEncoderReranker, CSVLoader, chunkText, createChunker, createContextWindow, createHybridSearch, createRAGPipeline, createVectorQueryTool, executeWithCircuitBreaker, extractMetadata, formatContextWithCitations, GraphRAG, getAvailableStrategies, getCircuitBreaker, getDefaultChunkerConfig, getRecommendedStrategy, HTMLChunker, HTMLLoader, InMemoryBM25Index, InMemoryVectorStore, JSONChunker as RAGJSONChunker, JSONLoader, LaTeXChunker, LLMMetadataExtractor, linearCombination, loadDocument, loadDocuments, MarkdownChunker, MarkdownLoader, MDocument, PDFLoader, prepareRAGTool, processDocument, RAGCircuitBreaker, RAGCircuitBreakerManager, RAGPipeline, RAGRetryHandler, RecursiveChunker, ragCircuitBreakerManager, reciprocalRankFusion, rerank, SemanticChunker, SentenceChunker, simpleRerank, summarizeContext, TextLoader, TokenChunker, WebLoader, } from "./rag/index.js";
429
+ export { assembleContext, batchRerank, CharacterChunker, ChunkerRegistry, CohereRelevanceScorer, CrossEncoderReranker, CSVLoader, chunkText, createChunker, createContextWindow, createHybridSearch, createRAGPipeline, createVectorQueryTool, executeWithCircuitBreaker, extractMetadata, formatContextWithCitations, GraphRAG, getAvailableStrategies, getCircuitBreaker, getDefaultChunkerConfig, getRecommendedStrategy, HTMLChunker, HTMLLoader, InMemoryBM25Index, InMemoryVectorStore, JSONChunker as RAGJSONChunker, JSONLoader, LaTeXChunker, LLMMetadataExtractor, linearCombination, loadDocument, loadDocuments, MarkdownChunker, MarkdownLoader, MDocument, PDFLoader, prepareRAGTool, processDocument, RAGCircuitBreaker, RAGCircuitBreakerManager, RAGPipeline, RAGRetryHandler, RecursiveChunker, ragCircuitBreakerManager, reciprocalRankFusion, rerank, SemanticChunker, ChromaVectorStore, PgVectorStore, PineconeVectorStore, SentenceChunker, simpleRerank, summarizeContext, TextLoader, TokenChunker, WebLoader, } from "./rag/index.js";
430
430
  export { ContextBuilder } from "./evaluation/contextBuilder.js";
431
431
  export { AuthProviderFactory, createAuthProvider, AuthProviderRegistry, AuthError as AuthErrorFactory, AuthErrorCodes, BaseAuthProvider, InMemorySessionStorage, AuthProviderError, createAuthMiddleware as createAuthProviderMiddleware, createRBACMiddleware, createProtectedMiddleware, createExpressAuthMiddleware, createRequestContext, extractToken, AuthMiddlewareError, AuthMiddlewareErrorCodes, UserRateLimiter, MemoryRateLimitStorage, RedisRateLimitStorage, createRateLimitByUserMiddleware, createAuthenticatedRateLimitMiddleware, createRateLimitStorage, SessionManager, MemorySessionStorage, RedisSessionStorage, createSessionStorage, AuthContextHolder, globalAuthContext, getAuthContext, getCurrentUser, getCurrentSession, isAuthenticated, hasRole, hasAnyRole, hasPermission, hasAllPermissions, requireAuth, requireRole, requirePermission, requireUser, runWithAuthContext, createAuthenticatedContext, RequestContext, NEUROLINK_RESOURCE_ID_KEY, NEUROLINK_THREAD_ID_KEY, createAuthValidatorFromProvider, } from "./auth/index.js";
432
432
  export { detectAndRedactPII } from "./utils/piiDetector.js";
package/dist/lib/index.js CHANGED
@@ -683,7 +683,7 @@ extractMetadata, formatContextWithCitations,
683
683
  // Graph RAG
684
684
  GraphRAG, getAvailableStrategies, getCircuitBreaker, getDefaultChunkerConfig, getRecommendedStrategy, HTMLChunker, HTMLLoader, InMemoryBM25Index, InMemoryVectorStore, JSONChunker as RAGJSONChunker, JSONLoader, LaTeXChunker, LLMMetadataExtractor, linearCombination, loadDocument, loadDocuments, MarkdownChunker, MarkdownLoader, MDocument, PDFLoader,
685
685
  // RAG Integration for generate/stream
686
- prepareRAGTool, processDocument, RAGCircuitBreaker, RAGCircuitBreakerManager, RAGPipeline, RAGRetryHandler, RecursiveChunker, ragCircuitBreakerManager, reciprocalRankFusion, rerank, SemanticChunker, SentenceChunker, simpleRerank, summarizeContext, TextLoader, TokenChunker, WebLoader, } from "./rag/index.js";
686
+ prepareRAGTool, processDocument, RAGCircuitBreaker, RAGCircuitBreakerManager, RAGPipeline, RAGRetryHandler, RecursiveChunker, ragCircuitBreakerManager, reciprocalRankFusion, rerank, SemanticChunker, ChromaVectorStore, PgVectorStore, PineconeVectorStore, SentenceChunker, simpleRerank, summarizeContext, TextLoader, TokenChunker, WebLoader, } from "./rag/index.js";
687
687
  // Legacy RAGAS evaluation classes are now exported from the unified
688
688
  // evaluation block above (via ./evaluation/index.js barrel).
689
689
  // ContextBuilder is the only class not covered by the barrel export.
@@ -171,7 +171,7 @@ const isNonRetryableProviderError = sharedIsNonRetryableProviderError;
171
171
  *
172
172
  * Main SDK class providing unified access to 14+ AI providers with enterprise features:
173
173
  * - Multi-provider support (OpenAI, Anthropic, Google AI Studio, Google Vertex, AWS Bedrock, etc.)
174
- * - MCP (Model Context Protocol) tool integration with 58+ external servers
174
+ * - MCP (Model Context Protocol) tool integration connect any MCP-compliant server
175
175
  * - Human-in-the-Loop (HITL) security workflows for regulated industries
176
176
  * - Redis-based conversation memory and persistence
177
177
  * - Enterprise middleware system for monitoring and control
@@ -56,6 +56,7 @@ export { prepareRAGTool } from "./ragIntegration.js";
56
56
  export { batchRerank, CohereRelevanceScorer, CrossEncoderReranker, createReranker, getAvailableRerankers, getAvailableRerankerTypes, getRegisteredRerankerMetadata, getReranker, getRerankerDefaultConfig, getRerankerMetadata, RerankerFactory, RerankerRegistry, rerank, rerankerFactory, rerankerRegistry, simpleRerank, } from "./reranker/index.js";
57
57
  export * from "./resilience/index.js";
58
58
  export { createHybridSearch, createVectorQueryTool, InMemoryBM25Index, InMemoryVectorStore, linearCombination, reciprocalRankFusion, } from "./retrieval/index.js";
59
+ export * from "./stores/index.js";
59
60
  export * from "../types/index.js";
60
61
  import type { Chunk, ChunkingStrategy, ExtractParams } from "../types/index.js";
61
62
  /**
@@ -76,6 +76,8 @@ RerankerRegistry, rerank, rerankerFactory, rerankerRegistry, simpleRerank, } fro
76
76
  export * from "./resilience/index.js";
77
77
  // Retrieval
78
78
  export { createHybridSearch, createVectorQueryTool, InMemoryBM25Index, InMemoryVectorStore, linearCombination, reciprocalRankFusion, } from "./retrieval/index.js";
79
+ // Vector store adapters (Pinecone, pgvector, Chroma — client-injection)
80
+ export * from "./stores/index.js";
79
81
  // Types
80
82
  export * from "../types/index.js";
81
83
  // Convenience functions
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Chroma vector store adapter
3
+ *
4
+ * Implements the `VectorStore` contract (see `src/lib/types/rag.ts`) against
5
+ * a Chroma collection. This module has zero runtime dependency on the
6
+ * `chromadb` package: callers construct their own `ChromaClient` (or any
7
+ * compatible object) and inject it here. The structural interfaces below
8
+ * mirror the subset of the `chromadb` API this adapter relies on
9
+ * (`getOrCreateCollection`, `collection.upsert/query/delete`).
10
+ *
11
+ * ## Distance -> similarity scoring
12
+ *
13
+ * Chroma returns *distances*, not similarities, and the meaning of that
14
+ * distance depends entirely on the collection's configured `hnsw:space`
15
+ * (this adapter does not — and cannot — set that; it is chosen when the
16
+ * collection is created on the Chroma side). `distanceMetric` tells this
17
+ * adapter which space the collection uses so it can invert the distance
18
+ * into a `score` consistent with `InMemoryVectorStore` (higher = more
19
+ * similar):
20
+ *
21
+ * - `"cosine"` (default): Chroma returns `distance = 1 - cosineSimilarity`,
22
+ * so `score = 1 - distance` reproduces `InMemoryVectorStore`'s cosine
23
+ * score exactly.
24
+ * - `"ip"`: Chroma returns `distance = 1 - dot(a, b)`, so
25
+ * `score = 1 - distance` yields the raw dot product — only equal to
26
+ * cosine similarity if both vectors are unit-normalized.
27
+ * - `"l2"`: Chroma returns squared Euclidean distance, range
28
+ * `[0, Infinity)`, which has no exact inverse into a cosine-similarity
29
+ * scale. It is converted via `score = 1 / (1 + distance)`, a
30
+ * monotonically decreasing-in-distance map into `(0, 1]`. This preserves
31
+ * result ordering but is NOT numerically comparable to cosine scores.
32
+ *
33
+ * Passing a `distanceMetric` that does not match the collection's actual
34
+ * `hnsw:space` will silently produce meaningless scores (Chroma has no way
35
+ * to report its configured space back to the client), so callers must keep
36
+ * the two in sync.
37
+ *
38
+ * ## Metadata round-tripping
39
+ *
40
+ * Chroma metadata values must be strings, numbers, or booleans. Values that
41
+ * are `undefined` are dropped (Chroma rejects `undefined`); any other
42
+ * non-primitive value (object, array, `null`) is `JSON.stringify`-ed on
43
+ * write. This is lossy: such values come back as JSON-encoded strings on
44
+ * read, not their original type. Store only primitive metadata values if
45
+ * you need exact round-tripping.
46
+ *
47
+ * ## indexName -> collection mapping
48
+ *
49
+ * `indexName` is used verbatim as the Chroma collection name (1:1,
50
+ * lazily created via `getOrCreateCollection` and cached for the lifetime of
51
+ * this adapter instance).
52
+ */
53
+ import type { ChromaClientLike, ChromaVectorStoreOptions, ChromaWhere, MetadataFilter, VectorQueryResult, VectorStore } from "../../types/index.js";
54
+ /**
55
+ * Translates a `MetadataFilter` into a Chroma `where` clause.
56
+ *
57
+ * Throws a clear error for any operator Chroma's metadata `where` clause
58
+ * cannot express ($not, $nor, $exists, $contains, $regex, $size) rather than
59
+ * silently dropping the constraint and mis-filtering results.
60
+ */
61
+ export declare function translateMetadataFilter(filter: MetadataFilter): ChromaWhere;
62
+ export declare class ChromaVectorStore implements VectorStore {
63
+ private readonly client;
64
+ private readonly collections;
65
+ private readonly distanceMetric;
66
+ constructor(client: ChromaClientLike, options?: ChromaVectorStoreOptions);
67
+ private getCollection;
68
+ /**
69
+ * Add or update vectors in an index (Chroma collection).
70
+ */
71
+ upsert(indexName: string, items: Array<{
72
+ id: string;
73
+ vector: number[];
74
+ metadata?: Record<string, unknown>;
75
+ }>): Promise<void>;
76
+ /**
77
+ * Query vectors by similarity.
78
+ */
79
+ query(params: {
80
+ indexName: string;
81
+ queryVector: number[];
82
+ topK?: number;
83
+ filter?: MetadataFilter;
84
+ includeVectors?: boolean;
85
+ }): Promise<VectorQueryResult[]>;
86
+ /**
87
+ * Delete vectors from an index (Chroma collection) by id.
88
+ */
89
+ delete(indexName: string, ids: string[]): Promise<void>;
90
+ }
@@ -0,0 +1,281 @@
1
+ /**
2
+ * Chroma vector store adapter
3
+ *
4
+ * Implements the `VectorStore` contract (see `src/lib/types/rag.ts`) against
5
+ * a Chroma collection. This module has zero runtime dependency on the
6
+ * `chromadb` package: callers construct their own `ChromaClient` (or any
7
+ * compatible object) and inject it here. The structural interfaces below
8
+ * mirror the subset of the `chromadb` API this adapter relies on
9
+ * (`getOrCreateCollection`, `collection.upsert/query/delete`).
10
+ *
11
+ * ## Distance -> similarity scoring
12
+ *
13
+ * Chroma returns *distances*, not similarities, and the meaning of that
14
+ * distance depends entirely on the collection's configured `hnsw:space`
15
+ * (this adapter does not — and cannot — set that; it is chosen when the
16
+ * collection is created on the Chroma side). `distanceMetric` tells this
17
+ * adapter which space the collection uses so it can invert the distance
18
+ * into a `score` consistent with `InMemoryVectorStore` (higher = more
19
+ * similar):
20
+ *
21
+ * - `"cosine"` (default): Chroma returns `distance = 1 - cosineSimilarity`,
22
+ * so `score = 1 - distance` reproduces `InMemoryVectorStore`'s cosine
23
+ * score exactly.
24
+ * - `"ip"`: Chroma returns `distance = 1 - dot(a, b)`, so
25
+ * `score = 1 - distance` yields the raw dot product — only equal to
26
+ * cosine similarity if both vectors are unit-normalized.
27
+ * - `"l2"`: Chroma returns squared Euclidean distance, range
28
+ * `[0, Infinity)`, which has no exact inverse into a cosine-similarity
29
+ * scale. It is converted via `score = 1 / (1 + distance)`, a
30
+ * monotonically decreasing-in-distance map into `(0, 1]`. This preserves
31
+ * result ordering but is NOT numerically comparable to cosine scores.
32
+ *
33
+ * Passing a `distanceMetric` that does not match the collection's actual
34
+ * `hnsw:space` will silently produce meaningless scores (Chroma has no way
35
+ * to report its configured space back to the client), so callers must keep
36
+ * the two in sync.
37
+ *
38
+ * ## Metadata round-tripping
39
+ *
40
+ * Chroma metadata values must be strings, numbers, or booleans. Values that
41
+ * are `undefined` are dropped (Chroma rejects `undefined`); any other
42
+ * non-primitive value (object, array, `null`) is `JSON.stringify`-ed on
43
+ * write. This is lossy: such values come back as JSON-encoded strings on
44
+ * read, not their original type. Store only primitive metadata values if
45
+ * you need exact round-tripping.
46
+ *
47
+ * ## indexName -> collection mapping
48
+ *
49
+ * `indexName` is used verbatim as the Chroma collection name (1:1,
50
+ * lazily created via `getOrCreateCollection` and cached for the lifetime of
51
+ * this adapter instance).
52
+ */
53
+ // Structural Chroma client/collection types (`ChromaClientLike`,
54
+ // `ChromaCollectionLike`, `ChromaUpsertParams`, etc.) live in
55
+ // `src/lib/types/vectorStoreChroma.ts` per this repo's canonical-type-
56
+ // location rule (see CLAUDE.md Critical Rules 2 & 12) and are imported from
57
+ // the types barrel above. This file only re-exports runtime values
58
+ // (`ChromaVectorStore`, `translateMetadataFilter`) — consumers who need the
59
+ // structural types should import them from `@juspay/neurolink` (root) or
60
+ // the types barrel directly, per Critical Rule 13.
61
+ // ---------------------------------------------------------------------------
62
+ // MetadataFilter -> Chroma `where` translation
63
+ // ---------------------------------------------------------------------------
64
+ const CHROMA_SUPPORTED_FIELD_OPS = new Set([
65
+ "$eq",
66
+ "$ne",
67
+ "$gt",
68
+ "$gte",
69
+ "$lt",
70
+ "$lte",
71
+ "$in",
72
+ "$nin",
73
+ ]);
74
+ const CHROMA_UNSUPPORTED_FIELD_OP_REASONS = {
75
+ $exists: 'Chroma metadata filtering has no existence check on the "where" clause.',
76
+ $contains: 'Chroma metadata filtering has no substring-match operator on the "where" clause (Chroma\'s substring matching only applies to document text via "where_document", not metadata field values).',
77
+ $regex: 'Chroma metadata filtering has no regular-expression operator on the "where" clause.',
78
+ $size: 'Chroma metadata filtering has no array-length operator on the "where" clause.',
79
+ };
80
+ function unsupportedFieldOpError(opKey, field) {
81
+ const reason = CHROMA_UNSUPPORTED_FIELD_OP_REASONS[opKey] ??
82
+ `Chroma metadata filtering does not support the "${opKey}" operator on the "where" clause.`;
83
+ return new Error(`Unsupported operator "${opKey}" (field "${field}"): ${reason}`);
84
+ }
85
+ /**
86
+ * Translates a field-level filter value (either a direct-equality primitive
87
+ * or an operator bag) into a Chroma `where` clause fragment for that field.
88
+ *
89
+ * Returns `undefined` when the filter value carries no enforceable
90
+ * constraint (an array, or an operator bag with no recognized keys) — this
91
+ * mirrors `InMemoryVectorStore.matchesFilter`, which treats any non-null
92
+ * object value as an "operator bag" and silently applies none of its checks
93
+ * when no recognized `$`-key is present, i.e. the field matches
94
+ * unconditionally. Omitting the field from the Chroma `where` clause
95
+ * reproduces that same "always matches" behavior.
96
+ */
97
+ function translateFieldFilter(field, value) {
98
+ if (Array.isArray(value)) {
99
+ return undefined;
100
+ }
101
+ if (value === null || typeof value !== "object") {
102
+ return { [field]: { $eq: value } };
103
+ }
104
+ const ops = value;
105
+ const opKeys = Object.keys(ops);
106
+ if (opKeys.length === 0) {
107
+ return undefined;
108
+ }
109
+ const chromaOps = {};
110
+ for (const opKey of opKeys) {
111
+ if (!CHROMA_SUPPORTED_FIELD_OPS.has(opKey)) {
112
+ throw unsupportedFieldOpError(opKey, field);
113
+ }
114
+ chromaOps[opKey] = ops[opKey];
115
+ }
116
+ return { [field]: chromaOps };
117
+ }
118
+ function translateLogicalOperator(key, value) {
119
+ switch (key) {
120
+ case "$and":
121
+ return {
122
+ $and: value.map(translateMetadataFilter),
123
+ };
124
+ case "$or":
125
+ return {
126
+ $or: value.map(translateMetadataFilter),
127
+ };
128
+ case "$not":
129
+ throw new Error('Chroma metadata filtering has no negation operator on the "where" clause; "$not" cannot be translated. Rewrite the filter using $ne/$nin instead.');
130
+ case "$nor":
131
+ throw new Error('"$nor" is declared on MetadataFilter but is not implemented by InMemoryVectorStore either, and Chroma has no negation operator on the "where" clause. Rewrite using $and of $ne/$nin clauses.');
132
+ default:
133
+ throw new Error(`Unknown logical operator "${key}" in MetadataFilter.`);
134
+ }
135
+ }
136
+ /**
137
+ * Translates a `MetadataFilter` into a Chroma `where` clause.
138
+ *
139
+ * Throws a clear error for any operator Chroma's metadata `where` clause
140
+ * cannot express ($not, $nor, $exists, $contains, $regex, $size) rather than
141
+ * silently dropping the constraint and mis-filtering results.
142
+ */
143
+ export function translateMetadataFilter(filter) {
144
+ const clauses = [];
145
+ for (const [key, value] of Object.entries(filter)) {
146
+ const clause = key.startsWith("$")
147
+ ? translateLogicalOperator(key, value)
148
+ : translateFieldFilter(key, value);
149
+ if (clause !== undefined) {
150
+ clauses.push(clause);
151
+ }
152
+ }
153
+ if (clauses.length === 0) {
154
+ return {};
155
+ }
156
+ if (clauses.length === 1) {
157
+ return clauses[0];
158
+ }
159
+ // Chroma requires a single top-level operator; combine multiple field/
160
+ // logical clauses with an explicit $and (mirrors matchesFilter ANDing
161
+ // every top-level entry).
162
+ return { $and: clauses };
163
+ }
164
+ // ---------------------------------------------------------------------------
165
+ // Metadata <-> Chroma metadata conversion
166
+ // ---------------------------------------------------------------------------
167
+ function toChromaMetadataValue(value) {
168
+ if (typeof value === "string" ||
169
+ typeof value === "number" ||
170
+ typeof value === "boolean") {
171
+ return value;
172
+ }
173
+ // Chroma metadata values must be string | number | boolean. Non-primitive
174
+ // values (object, array, null) are JSON-stringified — lossy on read back,
175
+ // see module doc comment.
176
+ return JSON.stringify(value);
177
+ }
178
+ function toChromaMetadata(metadata) {
179
+ const result = {};
180
+ for (const [key, value] of Object.entries(metadata)) {
181
+ if (value === undefined) {
182
+ // Chroma rejects `undefined` metadata values outright.
183
+ continue;
184
+ }
185
+ result[key] = toChromaMetadataValue(value);
186
+ }
187
+ return result;
188
+ }
189
+ function distanceToScore(distance, metric) {
190
+ switch (metric) {
191
+ case "cosine":
192
+ case "ip":
193
+ return 1 - distance;
194
+ case "l2":
195
+ return 1 / (1 + distance);
196
+ default: {
197
+ const exhaustive = metric;
198
+ throw new Error(`Unknown Chroma distance metric: ${String(exhaustive)}`);
199
+ }
200
+ }
201
+ }
202
+ // ---------------------------------------------------------------------------
203
+ // ChromaVectorStore
204
+ // ---------------------------------------------------------------------------
205
+ export class ChromaVectorStore {
206
+ client;
207
+ collections = new Map();
208
+ distanceMetric;
209
+ constructor(client, options = {}) {
210
+ this.client = client;
211
+ this.distanceMetric = options.distanceMetric ?? "cosine";
212
+ }
213
+ getCollection(indexName) {
214
+ let collection = this.collections.get(indexName);
215
+ if (!collection) {
216
+ collection = this.client.getOrCreateCollection({ name: indexName });
217
+ this.collections.set(indexName, collection);
218
+ }
219
+ return collection;
220
+ }
221
+ /**
222
+ * Add or update vectors in an index (Chroma collection).
223
+ */
224
+ async upsert(indexName, items) {
225
+ if (items.length === 0) {
226
+ return;
227
+ }
228
+ const collection = await this.getCollection(indexName);
229
+ await collection.upsert({
230
+ ids: items.map((item) => item.id),
231
+ embeddings: items.map((item) => item.vector),
232
+ metadatas: items.map((item) => toChromaMetadata(item.metadata ?? {})),
233
+ });
234
+ }
235
+ /**
236
+ * Query vectors by similarity.
237
+ */
238
+ async query(params) {
239
+ const { indexName, queryVector, topK = 10, filter, includeVectors = false, } = params;
240
+ const collection = await this.getCollection(indexName);
241
+ const include = ["metadatas", "distances"];
242
+ if (includeVectors) {
243
+ include.push("embeddings");
244
+ }
245
+ const response = await collection.query({
246
+ queryEmbeddings: [queryVector],
247
+ nResults: topK,
248
+ ...(filter ? { where: translateMetadataFilter(filter) } : {}),
249
+ include,
250
+ });
251
+ const ids = response.ids[0] ?? [];
252
+ const metadatasRow = response.metadatas?.[0] ?? [];
253
+ const distancesRow = response.distances?.[0] ?? [];
254
+ const embeddingsRow = response.embeddings?.[0] ?? [];
255
+ return ids.map((id, i) => {
256
+ const metadata = (metadatasRow[i] ?? {});
257
+ const distance = distancesRow[i];
258
+ const score = distance === null || distance === undefined
259
+ ? undefined
260
+ : distanceToScore(distance, this.distanceMetric);
261
+ return {
262
+ id,
263
+ score,
264
+ text: metadata.text,
265
+ metadata,
266
+ ...(includeVectors ? { vector: embeddingsRow[i] ?? [] } : {}),
267
+ };
268
+ });
269
+ }
270
+ /**
271
+ * Delete vectors from an index (Chroma collection) by id.
272
+ */
273
+ async delete(indexName, ids) {
274
+ if (ids.length === 0) {
275
+ return;
276
+ }
277
+ const collection = await this.getCollection(indexName);
278
+ await collection.delete({ ids });
279
+ }
280
+ }
281
+ //# sourceMappingURL=chroma.js.map
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Vector Store Adapters
3
+ *
4
+ * Client-injection adapters implementing the `VectorStore` contract
5
+ * (see `src/lib/types/rag.ts`) against real vector database backends.
6
+ * Each adapter accepts an already-constructed vendor client typed as a
7
+ * minimal structural interface — no vendor SDK is a runtime dependency
8
+ * of this package; callers bring their own client instance.
9
+ *
10
+ * @example
11
+ * ```typescript
12
+ * import { PineconeVectorStore } from '@juspay/neurolink/rag';
13
+ * import { Pinecone } from '@pinecone-database/pinecone';
14
+ *
15
+ * const client = new Pinecone({ apiKey: '...' });
16
+ * const store = new PineconeVectorStore(client.index('my-index'));
17
+ * ```
18
+ */
19
+ export * from "./pinecone.js";
20
+ export * from "./pgvector.js";
21
+ export * from "./chroma.js";
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Vector Store Adapters
3
+ *
4
+ * Client-injection adapters implementing the `VectorStore` contract
5
+ * (see `src/lib/types/rag.ts`) against real vector database backends.
6
+ * Each adapter accepts an already-constructed vendor client typed as a
7
+ * minimal structural interface — no vendor SDK is a runtime dependency
8
+ * of this package; callers bring their own client instance.
9
+ *
10
+ * @example
11
+ * ```typescript
12
+ * import { PineconeVectorStore } from '@juspay/neurolink/rag';
13
+ * import { Pinecone } from '@pinecone-database/pinecone';
14
+ *
15
+ * const client = new Pinecone({ apiKey: '...' });
16
+ * const store = new PineconeVectorStore(client.index('my-index'));
17
+ * ```
18
+ */
19
+ export * from "./pinecone.js";
20
+ export * from "./pgvector.js";
21
+ export * from "./chroma.js";
22
+ //# sourceMappingURL=index.js.map