@langchain/core
Version:
Core LangChain.js abstractions and schemas
1 lines • 40.3 kB
Source Map (JSON)
{"version":3,"file":"vectorstores.cjs","names":["BaseRetriever","fields: VectorStoreRetrieverInput<V>","query: string","runManager?: CallbackManagerForRetrieverRun","documents: DocumentInterface[]","options?: AddDocumentOptions","Serializable","embeddings: EmbeddingsInterface","dbConfig: Record<string, any>","_params?: Record<string, any>","filter: this[\"FilterType\"] | undefined","_callbacks: Callbacks | undefined","_texts: string[]","_metadatas: object[] | object","_embeddings: EmbeddingsInterface","_dbConfig: Record<string, any>","_docs: DocumentInterface[]","kOrFields?: number | Partial<VectorStoreRetrieverInput<this>>","filter?: this[\"FilterType\"]","callbacks?: Callbacks","tags?: string[]","metadata?: Record<string, unknown>","verbose?: boolean","_directory: string"],"sources":["../src/vectorstores.ts"],"sourcesContent":["import type { EmbeddingsInterface } from \"./embeddings.js\";\nimport type { DocumentInterface } from \"./documents/document.js\";\nimport {\n BaseRetriever,\n BaseRetrieverInterface,\n type BaseRetrieverInput,\n} from \"./retrievers/index.js\";\nimport { Serializable } from \"./load/serializable.js\";\nimport {\n CallbackManagerForRetrieverRun,\n Callbacks,\n} from \"./callbacks/manager.js\";\n\n/**\n * Type for options when adding a document to the VectorStore.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AddDocumentOptions = Record<string, any>;\n\n/**\n * Options for configuring a maximal marginal relevance (MMR) search.\n *\n * MMR search optimizes for both similarity to the query and diversity\n * among the results, balancing the retrieval of relevant documents\n * with variation in the content returned.\n *\n * Fields:\n *\n * - `fetchK` (optional): The initial number of documents to retrieve from the\n * vector store before applying the MMR algorithm. This larger set provides a\n * pool of documents from which the algorithm can select the most diverse\n * results based on relevance to the query.\n *\n * - `filter` (optional): A filter of type `FilterType` to refine the search\n * results, allowing additional conditions to target specific subsets\n * of documents.\n *\n * - `k`: The number of documents to return in the final results. This is the\n * primary count of documents that are most relevant to the query.\n *\n * - `lambda` (optional): A value between 0 and 1 that determines the balance\n * between relevance and diversity:\n * - A `lambda` of 0 emphasizes diversity, maximizing content variation.\n * - A `lambda` of 1 emphasizes similarity to the query, focusing on relevance.\n * Values between 0 and 1 provide a mix of relevance and diversity.\n *\n * @template FilterType - The type used for filtering results, as defined\n * by the vector store.\n */\nexport type MaxMarginalRelevanceSearchOptions<FilterType> = {\n k: number;\n fetchK?: number;\n lambda?: number;\n filter?: FilterType;\n};\n\n/**\n * Options for configuring a maximal marginal relevance (MMR) search\n * when using the `VectorStoreRetriever`.\n *\n * These parameters control how the MMR algorithm balances relevance to the\n * query and diversity among the retrieved documents.\n *\n * Fields:\n * - `fetchK` (optional): Specifies the initial number of documents to fetch\n * before applying the MMR algorithm. This larger set provides a pool of\n * documents from which the algorithm can select the most diverse results\n * based on relevance to the query.\n *\n * - `lambda` (optional): A value between 0 and 1 that determines the balance\n * between relevance and diversity:\n * - A `lambda` of 0 maximizes diversity among the results, prioritizing varied content.\n * - A `lambda` of 1 maximizes similarity to the query, prioritizing relevance.\n * Values between 0 and 1 provide a mix of relevance and diversity.\n */\nexport type VectorStoreRetrieverMMRSearchKwargs = {\n fetchK?: number;\n lambda?: number;\n};\n\n/**\n * Input configuration options for creating a `VectorStoreRetriever` instance.\n *\n * This type combines properties from `BaseRetrieverInput` with specific settings\n * for the `VectorStoreRetriever`, including options for similarity or maximal\n * marginal relevance (MMR) search types.\n *\n * Fields:\n *\n * - `callbacks` (optional): An array of callback functions that handle various\n * events during retrieval, such as logging, error handling, or progress updates.\n *\n * - `tags` (optional): An array of strings used to add contextual tags to\n * retrieval operations, allowing for easier categorization and tracking.\n *\n * - `metadata` (optional): A record of key-value pairs to store additional\n * contextual information for retrieval operations, which can be useful\n * for logging or auditing purposes.\n *\n * - `verbose` (optional): A boolean flag that, if set to `true`, enables\n * detailed logging and output during the retrieval process. Defaults to `false`.\n *\n * - `vectorStore`: The `VectorStore` instance implementing `VectorStoreInterface`\n * that will be used for document storage and retrieval.\n *\n * - `k` (optional): Specifies the number of documents to retrieve per search\n * query. Defaults to 4 if not specified.\n *\n * - `filter` (optional): A filter of type `FilterType` (defined by the vector store)\n * to refine the set of documents returned, allowing for targeted search results.\n *\n * - `searchType`: Determines the type of search to perform:\n * - `\"similarity\"`: Executes a similarity search, retrieving documents based purely\n * on vector similarity to the query.\n * - `\"mmr\"`: Executes a maximal marginal relevance (MMR) search, balancing similarity\n * and diversity in the search results.\n *\n * - `searchKwargs` (optional): Used only if `searchType` is `\"mmr\"`, this object\n * provides additional options for MMR search, including:\n * - `fetchK`: Specifies the number of documents to initially fetch before applying\n * the MMR algorithm, providing a pool from which the most diverse results are selected.\n * - `lambda`: A diversity parameter, where 0 emphasizes diversity and 1 emphasizes\n * relevance to the query. Values between 0 and 1 provide a balance of relevance and diversity.\n *\n * @template V - The type of vector store implementing `VectorStoreInterface`.\n */\nexport type VectorStoreRetrieverInput<V extends VectorStoreInterface> =\n BaseRetrieverInput &\n (\n | {\n vectorStore: V;\n k?: number;\n filter?: V[\"FilterType\"];\n searchType?: \"similarity\";\n }\n | {\n vectorStore: V;\n k?: number;\n filter?: V[\"FilterType\"];\n searchType: \"mmr\";\n searchKwargs?: VectorStoreRetrieverMMRSearchKwargs;\n }\n );\n\n/**\n * Interface for a retriever that uses a vector store to store and retrieve\n * document embeddings. This retriever interface allows for adding documents\n * to the underlying vector store and conducting retrieval operations.\n *\n * `VectorStoreRetrieverInterface` extends `BaseRetrieverInterface` to provide\n * document retrieval capabilities based on vector similarity.\n *\n * @interface VectorStoreRetrieverInterface\n * @extends BaseRetrieverInterface\n */\nexport interface VectorStoreRetrieverInterface<\n V extends VectorStoreInterface = VectorStoreInterface\n> extends BaseRetrieverInterface {\n vectorStore: V;\n\n /**\n * Adds an array of documents to the vector store.\n *\n * This method embeds the provided documents and stores them within the\n * vector store. Additional options can be specified for custom behavior\n * during the addition process.\n *\n * @param documents - An array of documents to embed and add to the vector store.\n * @param options - Optional settings to customize document addition.\n * @returns A promise that resolves to an array of document IDs or `void`,\n * depending on the implementation.\n */\n addDocuments(\n documents: DocumentInterface[],\n options?: AddDocumentOptions\n ): Promise<string[] | void>;\n}\n\n/**\n * Class for retrieving documents from a `VectorStore` based on vector similarity\n * or maximal marginal relevance (MMR).\n *\n * `VectorStoreRetriever` extends `BaseRetriever`, implementing methods for\n * adding documents to the underlying vector store and performing document\n * retrieval with optional configurations.\n *\n * @class VectorStoreRetriever\n * @extends BaseRetriever\n * @implements VectorStoreRetrieverInterface\n * @template V - Type of vector store implementing `VectorStoreInterface`.\n */\nexport class VectorStoreRetriever<\n V extends VectorStoreInterface = VectorStoreInterface\n >\n extends BaseRetriever\n implements VectorStoreRetrieverInterface\n{\n static lc_name() {\n return \"VectorStoreRetriever\";\n }\n\n get lc_namespace() {\n return [\"langchain_core\", \"vectorstores\"];\n }\n\n /**\n * The instance of `VectorStore` used for storing and retrieving document embeddings.\n * This vector store must implement the `VectorStoreInterface` to be compatible\n * with the retriever’s operations.\n */\n vectorStore: V;\n\n /**\n * Specifies the number of documents to retrieve for each search query.\n * Defaults to 4 if not specified, providing a basic result count for similarity or MMR searches.\n */\n k = 4;\n\n /**\n * Determines the type of search operation to perform on the vector store.\n *\n * - `\"similarity\"` (default): Conducts a similarity search based purely on vector similarity\n * to the query.\n * - `\"mmr\"`: Executes a maximal marginal relevance (MMR) search, balancing relevance and\n * diversity in the retrieved results.\n */\n searchType = \"similarity\";\n\n /**\n * Additional options specific to maximal marginal relevance (MMR) search, applicable\n * only if `searchType` is set to `\"mmr\"`.\n *\n * Includes:\n * - `fetchK`: The initial number of documents fetched before applying the MMR algorithm,\n * allowing for a larger selection from which to choose the most diverse results.\n * - `lambda`: A parameter between 0 and 1 to adjust the relevance-diversity balance,\n * where 0 prioritizes diversity and 1 prioritizes relevance.\n */\n searchKwargs?: VectorStoreRetrieverMMRSearchKwargs;\n\n /**\n * Optional filter applied to search results, defined by the `FilterType` of the vector store.\n * Allows for refined, targeted results by restricting the returned documents based\n * on specified filter criteria.\n */\n filter?: V[\"FilterType\"];\n\n /**\n * Returns the type of vector store, as defined by the `vectorStore` instance.\n *\n * @returns {string} The vector store type.\n */\n _vectorstoreType(): string {\n return this.vectorStore._vectorstoreType();\n }\n\n /**\n * Initializes a new instance of `VectorStoreRetriever` with the specified configuration.\n *\n * This constructor configures the retriever to interact with a given `VectorStore`\n * and supports different retrieval strategies, including similarity search and maximal\n * marginal relevance (MMR) search. Various options allow customization of the number\n * of documents retrieved per query, filtering based on conditions, and fine-tuning\n * MMR-specific parameters.\n *\n * @param fields - Configuration options for setting up the retriever:\n *\n * - `vectorStore` (required): The `VectorStore` instance implementing `VectorStoreInterface`\n * that will be used to store and retrieve document embeddings. This is the core component\n * of the retriever, enabling vector-based similarity and MMR searches.\n *\n * - `k` (optional): Specifies the number of documents to retrieve per search query. If not\n * provided, defaults to 4. This count determines the number of most relevant documents returned\n * for each search operation, balancing performance with comprehensiveness.\n *\n * - `searchType` (optional): Defines the search approach used by the retriever, allowing for\n * flexibility between two methods:\n * - `\"similarity\"` (default): A similarity-based search, retrieving documents with high vector\n * similarity to the query. This type prioritizes relevance and is often used when diversity\n * among results is less critical.\n * - `\"mmr\"`: Maximal Marginal Relevance search, which combines relevance with diversity. MMR\n * is useful for scenarios where varied content is essential, as it selects results that\n * both match the query and introduce content diversity.\n *\n * - `filter` (optional): A filter of type `FilterType`, defined by the vector store, that allows\n * for refined and targeted search results. This filter applies specified conditions to limit\n * which documents are eligible for retrieval, offering control over the scope of results.\n *\n * - `searchKwargs` (optional, applicable only if `searchType` is `\"mmr\"`): Additional settings\n * for configuring MMR-specific behavior. These parameters allow further tuning of the MMR\n * search process:\n * - `fetchK`: The initial number of documents fetched from the vector store before the MMR\n * algorithm is applied. Fetching a larger set enables the algorithm to select a more\n * diverse subset of documents.\n * - `lambda`: A parameter controlling the relevance-diversity balance, where 0 emphasizes\n * diversity and 1 prioritizes relevance. Intermediate values provide a blend of the two,\n * allowing customization based on the importance of content variety relative to query relevance.\n */\n constructor(fields: VectorStoreRetrieverInput<V>) {\n super(fields);\n this.vectorStore = fields.vectorStore;\n this.k = fields.k ?? this.k;\n this.searchType = fields.searchType ?? this.searchType;\n this.filter = fields.filter;\n if (fields.searchType === \"mmr\") {\n this.searchKwargs = fields.searchKwargs;\n }\n }\n\n /**\n * Retrieves relevant documents based on the specified query, using either\n * similarity or maximal marginal relevance (MMR) search.\n *\n * If `searchType` is set to `\"mmr\"`, performs an MMR search to balance\n * similarity and diversity among results. If `searchType` is `\"similarity\"`,\n * retrieves results purely based on similarity to the query.\n *\n * @param query - The query string used to find relevant documents.\n * @param runManager - Optional callback manager for tracking retrieval progress.\n * @returns A promise that resolves to an array of `DocumentInterface` instances\n * representing the most relevant documents to the query.\n * @throws {Error} Throws an error if MMR search is requested but not supported\n * by the vector store.\n * @protected\n */\n async _getRelevantDocuments(\n query: string,\n runManager?: CallbackManagerForRetrieverRun\n ): Promise<DocumentInterface[]> {\n if (this.searchType === \"mmr\") {\n if (typeof this.vectorStore.maxMarginalRelevanceSearch !== \"function\") {\n throw new Error(\n `The vector store backing this retriever, ${this._vectorstoreType()} does not support max marginal relevance search.`\n );\n }\n return this.vectorStore.maxMarginalRelevanceSearch(\n query,\n {\n k: this.k,\n filter: this.filter,\n ...this.searchKwargs,\n },\n runManager?.getChild(\"vectorstore\")\n );\n }\n return this.vectorStore.similaritySearch(\n query,\n this.k,\n this.filter,\n runManager?.getChild(\"vectorstore\")\n );\n }\n\n /**\n * Adds an array of documents to the vector store, embedding them as part of\n * the storage process.\n *\n * This method delegates document embedding and storage to the `addDocuments`\n * method of the underlying vector store.\n *\n * @param documents - An array of documents to embed and add to the vector store.\n * @param options - Optional settings to customize document addition.\n * @returns A promise that resolves to an array of document IDs or `void`,\n * depending on the vector store's implementation.\n */\n async addDocuments(\n documents: DocumentInterface[],\n options?: AddDocumentOptions\n ): Promise<string[] | void> {\n return this.vectorStore.addDocuments(documents, options);\n }\n}\n\n/**\n * Interface defining the structure and operations of a vector store, which\n * facilitates the storage, retrieval, and similarity search of document vectors.\n *\n * `VectorStoreInterface` provides methods for adding, deleting, and searching\n * documents based on vector embeddings, including support for similarity\n * search with optional filtering and relevance-based retrieval.\n *\n * @extends Serializable\n */\nexport interface VectorStoreInterface extends Serializable {\n /**\n * Defines the filter type used in search and delete operations. Can be an\n * object for structured conditions or a string for simpler filtering.\n */\n FilterType: object | string;\n\n /**\n * Instance of `EmbeddingsInterface` used to generate vector embeddings for\n * documents, enabling vector-based search operations.\n */\n embeddings: EmbeddingsInterface;\n\n /**\n * Returns a string identifying the type of vector store implementation,\n * useful for distinguishing between different vector storage backends.\n *\n * @returns {string} A string indicating the vector store type.\n */\n _vectorstoreType(): string;\n\n /**\n * Adds precomputed vectors and their corresponding documents to the vector store.\n *\n * @param vectors - An array of vectors, with each vector representing a document.\n * @param documents - An array of `DocumentInterface` instances corresponding to each vector.\n * @param options - Optional configurations for adding documents, potentially covering indexing or metadata handling.\n * @returns A promise that resolves to an array of document IDs or void, depending on implementation.\n */\n addVectors(\n vectors: number[][],\n documents: DocumentInterface[],\n options?: AddDocumentOptions\n ): Promise<string[] | void>;\n\n /**\n * Adds an array of documents to the vector store.\n *\n * @param documents - An array of documents to be embedded and stored in the vector store.\n * @param options - Optional configurations for embedding and storage operations.\n * @returns A promise that resolves to an array of document IDs or void, depending on implementation.\n */\n addDocuments(\n documents: DocumentInterface[],\n options?: AddDocumentOptions\n ): Promise<string[] | void>;\n\n /**\n * Deletes documents from the vector store based on the specified parameters.\n *\n * @param _params - A flexible object containing key-value pairs that define\n * the conditions for selecting documents to delete.\n * @returns A promise that resolves once the deletion operation is complete.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n delete(_params?: Record<string, any>): Promise<void>;\n\n /**\n * Searches for documents similar to a given vector query and returns them\n * with similarity scores.\n *\n * @param query - A vector representing the query for similarity search.\n * @param k - The number of similar documents to return.\n * @param filter - Optional filter based on `FilterType` to restrict results.\n * @returns A promise that resolves to an array of tuples, each containing a\n * `DocumentInterface` and its corresponding similarity score.\n */\n similaritySearchVectorWithScore(\n query: number[],\n k: number,\n filter?: this[\"FilterType\"]\n ): Promise<[DocumentInterface, number][]>;\n\n /**\n * Searches for documents similar to a text query, embedding the query\n * and retrieving documents based on vector similarity.\n *\n * @param query - The text query to search for.\n * @param k - Optional number of similar documents to return.\n * @param filter - Optional filter based on `FilterType` to restrict results.\n * @param callbacks - Optional callbacks for tracking progress or events\n * during the search process.\n * @returns A promise that resolves to an array of `DocumentInterface`\n * instances representing similar documents.\n */\n similaritySearch(\n query: string,\n k?: number,\n filter?: this[\"FilterType\"],\n callbacks?: Callbacks\n ): Promise<DocumentInterface[]>;\n\n /**\n * Searches for documents similar to a text query and includes similarity\n * scores in the result.\n *\n * @param query - The text query to search for.\n * @param k - Optional number of similar documents to return.\n * @param filter - Optional filter based on `FilterType` to restrict results.\n * @param callbacks - Optional callbacks for tracking progress or events\n * during the search process.\n * @returns A promise that resolves to an array of tuples, each containing\n * a `DocumentInterface` and its similarity score.\n */\n similaritySearchWithScore(\n query: string,\n k?: number,\n filter?: this[\"FilterType\"],\n callbacks?: Callbacks\n ): Promise<[DocumentInterface, number][]>;\n\n /**\n * Return documents selected using the maximal marginal relevance.\n * Maximal marginal relevance optimizes for similarity to the query AND diversity\n * among selected documents.\n *\n * @param {string} query - Text to look up documents similar to.\n * @param {number} options.k - Number of documents to return.\n * @param {number} options.fetchK - Number of documents to fetch before passing to the MMR algorithm.\n * @param {number} options.lambda - Number between 0 and 1 that determines the degree of diversity among the results,\n * where 0 corresponds to maximum diversity and 1 to minimum diversity.\n * @param {this[\"FilterType\"]} options.filter - Optional filter\n * @param _callbacks\n *\n * @returns {Promise<DocumentInterface[]>} - List of documents selected by maximal marginal relevance.\n */\n maxMarginalRelevanceSearch?(\n query: string,\n options: MaxMarginalRelevanceSearchOptions<this[\"FilterType\"]>,\n callbacks: Callbacks | undefined\n ): Promise<DocumentInterface[]>;\n\n /**\n * Converts the vector store into a retriever, making it suitable for use in\n * retrieval-based workflows and allowing additional configuration.\n *\n * @param kOrFields - Optional parameter for specifying either the number of\n * documents to retrieve or partial retriever configurations.\n * @param filter - Optional filter based on `FilterType` for retrieval restriction.\n * @param callbacks - Optional callbacks for tracking retrieval events or progress.\n * @param tags - General-purpose tags to add contextual information to the retriever.\n * @param metadata - General-purpose metadata providing additional context\n * for retrieval.\n * @param verbose - If `true`, enables detailed logging during retrieval.\n * @returns An instance of `VectorStoreRetriever` configured with the specified options.\n */\n asRetriever(\n kOrFields?: number | Partial<VectorStoreRetrieverInput<this>>,\n filter?: this[\"FilterType\"],\n callbacks?: Callbacks,\n tags?: string[],\n metadata?: Record<string, unknown>,\n verbose?: boolean\n ): VectorStoreRetriever<this>;\n}\n\n/**\n * Abstract class representing a vector storage system for performing\n * similarity searches on embedded documents.\n *\n * `VectorStore` provides methods for adding precomputed vectors or documents,\n * removing documents based on criteria, and performing similarity searches\n * with optional scoring. Subclasses are responsible for implementing specific\n * storage mechanisms and the exact behavior of certain abstract methods.\n *\n * @abstract\n * @extends Serializable\n * @implements VectorStoreInterface\n */\nexport abstract class VectorStore\n extends Serializable\n implements VectorStoreInterface\n{\n declare FilterType: object | string;\n\n /**\n * Namespace within LangChain to uniquely identify this vector store's\n * location, based on the vector store type.\n *\n * @internal\n */\n // Only ever instantiated in main LangChain\n lc_namespace = [\"langchain\", \"vectorstores\", this._vectorstoreType()];\n\n /**\n * Embeddings interface for generating vector embeddings from text queries,\n * enabling vector-based similarity searches.\n */\n embeddings: EmbeddingsInterface;\n\n /**\n * Initializes a new vector store with embeddings and database configuration.\n *\n * @param embeddings - Instance of `EmbeddingsInterface` used to embed queries.\n * @param dbConfig - Configuration settings for the database or storage system.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n constructor(embeddings: EmbeddingsInterface, dbConfig: Record<string, any>) {\n super(dbConfig);\n this.embeddings = embeddings;\n }\n\n /**\n * Returns a string representing the type of vector store, which subclasses\n * must implement to identify their specific vector storage type.\n *\n * @returns {string} A string indicating the vector store type.\n * @abstract\n */\n abstract _vectorstoreType(): string;\n\n /**\n * Adds precomputed vectors and corresponding documents to the vector store.\n *\n * @param vectors - An array of vectors representing each document.\n * @param documents - Array of documents associated with each vector.\n * @param options - Optional configuration for adding vectors, such as indexing.\n * @returns A promise resolving to an array of document IDs or void, based on implementation.\n * @abstract\n */\n abstract addVectors(\n vectors: number[][],\n documents: DocumentInterface[],\n options?: AddDocumentOptions\n ): Promise<string[] | void>;\n\n /**\n * Adds documents to the vector store, embedding them first through the\n * `embeddings` instance.\n *\n * @param documents - Array of documents to embed and add.\n * @param options - Optional configuration for embedding and storing documents.\n * @returns A promise resolving to an array of document IDs or void, based on implementation.\n * @abstract\n */\n abstract addDocuments(\n documents: DocumentInterface[],\n options?: AddDocumentOptions\n ): Promise<string[] | void>;\n\n /**\n * Deletes documents from the vector store based on the specified parameters.\n *\n * @param _params - Flexible key-value pairs defining conditions for document deletion.\n * @returns A promise that resolves once the deletion is complete.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n async delete(_params?: Record<string, any>): Promise<void> {\n throw new Error(\"Not implemented.\");\n }\n\n /**\n * Performs a similarity search using a vector query and returns results\n * along with their similarity scores.\n *\n * @param query - Vector representing the search query.\n * @param k - Number of similar results to return.\n * @param filter - Optional filter based on `FilterType` to restrict results.\n * @returns A promise resolving to an array of tuples containing documents and their similarity scores.\n * @abstract\n */\n abstract similaritySearchVectorWithScore(\n query: number[],\n k: number,\n filter?: this[\"FilterType\"]\n ): Promise<[DocumentInterface, number][]>;\n\n /**\n * Searches for documents similar to a text query by embedding the query and\n * performing a similarity search on the resulting vector.\n *\n * @param query - Text query for finding similar documents.\n * @param k - Number of similar results to return. Defaults to 4.\n * @param filter - Optional filter based on `FilterType`.\n * @param _callbacks - Optional callbacks for monitoring search progress\n * @returns A promise resolving to an array of `DocumentInterface` instances representing similar documents.\n */\n async similaritySearch(\n query: string,\n k = 4,\n filter: this[\"FilterType\"] | undefined = undefined,\n _callbacks: Callbacks | undefined = undefined // implement passing to embedQuery later\n ): Promise<DocumentInterface[]> {\n const results = await this.similaritySearchVectorWithScore(\n await this.embeddings.embedQuery(query),\n k,\n filter\n );\n\n return results.map((result) => result[0]);\n }\n\n /**\n * Searches for documents similar to a text query by embedding the query,\n * and returns results with similarity scores.\n *\n * @param query - Text query for finding similar documents.\n * @param k - Number of similar results to return. Defaults to 4.\n * @param filter - Optional filter based on `FilterType`.\n * @param _callbacks - Optional callbacks for monitoring search progress\n * @returns A promise resolving to an array of tuples, each containing a\n * document and its similarity score.\n */\n async similaritySearchWithScore(\n query: string,\n k = 4,\n filter: this[\"FilterType\"] | undefined = undefined,\n _callbacks: Callbacks | undefined = undefined // implement passing to embedQuery later\n ): Promise<[DocumentInterface, number][]> {\n return this.similaritySearchVectorWithScore(\n await this.embeddings.embedQuery(query),\n k,\n filter\n );\n }\n\n /**\n * Return documents selected using the maximal marginal relevance.\n * Maximal marginal relevance optimizes for similarity to the query AND diversity\n * among selected documents.\n *\n * @param {string} query - Text to look up documents similar to.\n * @param {number} options.k - Number of documents to return.\n * @param {number} options.fetchK - Number of documents to fetch before passing to the MMR algorithm.\n * @param {number} options.lambda - Number between 0 and 1 that determines the degree of diversity among the results,\n * where 0 corresponds to maximum diversity and 1 to minimum diversity.\n * @param {this[\"FilterType\"]} options.filter - Optional filter\n * @param _callbacks\n *\n * @returns {Promise<DocumentInterface[]>} - List of documents selected by maximal marginal relevance.\n */\n async maxMarginalRelevanceSearch?(\n query: string,\n options: MaxMarginalRelevanceSearchOptions<this[\"FilterType\"]>,\n _callbacks: Callbacks | undefined // implement passing to embedQuery later\n ): Promise<DocumentInterface[]>;\n\n /**\n * Creates a `VectorStore` instance from an array of text strings and optional\n * metadata, using the specified embeddings and database configuration.\n *\n * Subclasses must implement this method to define how text and metadata\n * are embedded and stored in the vector store. Throws an error if not overridden.\n *\n * @param _texts - Array of strings representing the text documents to be stored.\n * @param _metadatas - Metadata for the texts, either as an array (one for each text)\n * or a single object (applied to all texts).\n * @param _embeddings - Instance of `EmbeddingsInterface` to embed the texts.\n * @param _dbConfig - Database configuration settings.\n * @returns A promise that resolves to a new `VectorStore` instance.\n * @throws {Error} Throws an error if this method is not overridden by a subclass.\n */\n static fromTexts(\n _texts: string[],\n _metadatas: object[] | object,\n _embeddings: EmbeddingsInterface,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n _dbConfig: Record<string, any>\n ): Promise<VectorStore> {\n throw new Error(\n \"the Langchain vectorstore implementation you are using forgot to override this, please report a bug\"\n );\n }\n\n /**\n * Creates a `VectorStore` instance from an array of documents, using the specified\n * embeddings and database configuration.\n *\n * Subclasses must implement this method to define how documents are embedded\n * and stored. Throws an error if not overridden.\n *\n * @param _docs - Array of `DocumentInterface` instances representing the documents to be stored.\n * @param _embeddings - Instance of `EmbeddingsInterface` to embed the documents.\n * @param _dbConfig - Database configuration settings.\n * @returns A promise that resolves to a new `VectorStore` instance.\n * @throws {Error} Throws an error if this method is not overridden by a subclass.\n */\n static fromDocuments(\n _docs: DocumentInterface[],\n _embeddings: EmbeddingsInterface,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n _dbConfig: Record<string, any>\n ): Promise<VectorStore> {\n throw new Error(\n \"the Langchain vectorstore implementation you are using forgot to override this, please report a bug\"\n );\n }\n\n /**\n * Creates a `VectorStoreRetriever` instance with flexible configuration options.\n *\n * @param kOrFields\n * - If a number is provided, it sets the `k` parameter (number of items to retrieve).\n * - If an object is provided, it should contain various configuration options.\n * @param filter\n * - Optional filter criteria to limit the items retrieved based on the specified filter type.\n * @param callbacks\n * - Optional callbacks that may be triggered at specific stages of the retrieval process.\n * @param tags\n * - Tags to categorize or label the `VectorStoreRetriever`. Defaults to an empty array if not provided.\n * @param metadata\n * - Additional metadata as key-value pairs to add contextual information for the retrieval process.\n * @param verbose\n * - If `true`, enables detailed logging for the retrieval process. Defaults to `false`.\n *\n * @returns\n * - A configured `VectorStoreRetriever` instance based on the provided parameters.\n *\n * @example\n * Basic usage with a `k` value:\n * ```typescript\n * const retriever = myVectorStore.asRetriever(5);\n * ```\n *\n * Usage with a configuration object:\n * ```typescript\n * const retriever = myVectorStore.asRetriever({\n * k: 10,\n * filter: myFilter,\n * tags: ['example', 'test'],\n * verbose: true,\n * searchType: 'mmr',\n * searchKwargs: { alpha: 0.5 },\n * });\n * ```\n */\n asRetriever(\n kOrFields?: number | Partial<VectorStoreRetrieverInput<this>>,\n filter?: this[\"FilterType\"],\n callbacks?: Callbacks,\n tags?: string[],\n metadata?: Record<string, unknown>,\n verbose?: boolean\n ): VectorStoreRetriever<this> {\n if (typeof kOrFields === \"number\") {\n return new VectorStoreRetriever({\n vectorStore: this,\n k: kOrFields,\n filter,\n tags: [...(tags ?? []), this._vectorstoreType()],\n metadata,\n verbose,\n callbacks,\n });\n } else {\n const params = {\n vectorStore: this,\n k: kOrFields?.k,\n filter: kOrFields?.filter,\n tags: [...(kOrFields?.tags ?? []), this._vectorstoreType()],\n metadata: kOrFields?.metadata,\n verbose: kOrFields?.verbose,\n callbacks: kOrFields?.callbacks,\n searchType: kOrFields?.searchType,\n };\n if (kOrFields?.searchType === \"mmr\") {\n return new VectorStoreRetriever({\n ...params,\n searchKwargs: kOrFields.searchKwargs,\n });\n }\n return new VectorStoreRetriever({ ...params });\n }\n }\n}\n\n/**\n * Abstract class extending `VectorStore` that defines a contract for saving\n * and loading vector store instances.\n *\n * The `SaveableVectorStore` class allows vector store implementations to\n * persist their data and retrieve it when needed.The format for saving and\n * loading data is left to the implementing subclass.\n *\n * Subclasses must implement the `save` method to handle their custom\n * serialization logic, while the `load` method enables reconstruction of a\n * vector store from saved data, requiring compatible embeddings through the\n * `EmbeddingsInterface`.\n *\n * @abstract\n * @extends VectorStore\n */\nexport abstract class SaveableVectorStore extends VectorStore {\n /**\n * Saves the current state of the vector store to the specified directory.\n *\n * This method must be implemented by subclasses to define their own\n * serialization process for persisting vector data. The implementation\n * determines the structure and format of the saved data.\n *\n * @param directory - The directory path where the vector store data\n * will be saved.\n * @abstract\n */\n abstract save(directory: string): Promise<void>;\n\n /**\n * Loads a vector store instance from the specified directory, using the\n * provided embeddings to ensure compatibility.\n *\n * This static method reconstructs a `SaveableVectorStore` from previously\n * saved data. Implementations should interpret the saved data format to\n * recreate the vector store instance.\n *\n * @param _directory - The directory path from which the vector store\n * data will be loaded.\n * @param _embeddings - An instance of `EmbeddingsInterface` to align\n * the embeddings with the loaded vector data.\n * @returns A promise that resolves to a `SaveableVectorStore` instance\n * constructed from the saved data.\n */\n static load(\n _directory: string,\n _embeddings: EmbeddingsInterface\n ): Promise<SaveableVectorStore> {\n throw new Error(\"Not implemented\");\n }\n}\n"],"mappings":"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"}