langchain 0.0.173 → 0.0.174
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.
- package/dist/callbacks/manager.cjs +2 -1
- package/dist/callbacks/manager.js +2 -1
- package/dist/memory/index.cjs +2 -1
- package/dist/memory/index.d.ts +1 -1
- package/dist/memory/index.js +1 -1
- package/dist/prompts/selectors/SemanticSimilarityExampleSelector.cjs +15 -18
- package/dist/prompts/selectors/SemanticSimilarityExampleSelector.d.ts +12 -6
- package/dist/prompts/selectors/SemanticSimilarityExampleSelector.js +15 -18
- package/dist/vectorstores/pinecone.cjs +46 -9
- package/dist/vectorstores/pinecone.d.ts +20 -2
- package/dist/vectorstores/pinecone.js +46 -9
- package/package.json +1 -1
|
@@ -504,7 +504,8 @@ class CallbackManager extends BaseCallbackManager {
|
|
|
504
504
|
? localHandlers.map(ensureHandler)
|
|
505
505
|
: localHandlers?.handlers, false);
|
|
506
506
|
}
|
|
507
|
-
const verboseEnabled = (0, env_js_1.getEnvironmentVariable)("LANGCHAIN_VERBOSE") ||
|
|
507
|
+
const verboseEnabled = (0, env_js_1.getEnvironmentVariable)("LANGCHAIN_VERBOSE") === "true" ||
|
|
508
|
+
options?.verbose;
|
|
508
509
|
const tracingV2Enabled = (0, env_js_1.getEnvironmentVariable)("LANGCHAIN_TRACING_V2") === "true";
|
|
509
510
|
const tracingEnabled = tracingV2Enabled ||
|
|
510
511
|
((0, env_js_1.getEnvironmentVariable)("LANGCHAIN_TRACING") ?? false);
|
|
@@ -495,7 +495,8 @@ export class CallbackManager extends BaseCallbackManager {
|
|
|
495
495
|
? localHandlers.map(ensureHandler)
|
|
496
496
|
: localHandlers?.handlers, false);
|
|
497
497
|
}
|
|
498
|
-
const verboseEnabled = getEnvironmentVariable("LANGCHAIN_VERBOSE") ||
|
|
498
|
+
const verboseEnabled = getEnvironmentVariable("LANGCHAIN_VERBOSE") === "true" ||
|
|
499
|
+
options?.verbose;
|
|
499
500
|
const tracingV2Enabled = getEnvironmentVariable("LANGCHAIN_TRACING_V2") === "true";
|
|
500
501
|
const tracingEnabled = tracingV2Enabled ||
|
|
501
502
|
(getEnvironmentVariable("LANGCHAIN_TRACING") ?? false);
|
package/dist/memory/index.cjs
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.ConversationSummaryBufferMemory = exports.CombinedMemory = exports.ENTITY_MEMORY_CONVERSATION_TEMPLATE = exports.EntityMemory = exports.VectorStoreRetrieverMemory = exports.MotorheadMemory = exports.ChatMessageHistory = exports.BaseChatMemory = exports.BufferWindowMemory = exports.BaseConversationSummaryMemory = exports.ConversationSummaryMemory = exports.getBufferString = exports.getInputValue = exports.BaseMemory = exports.BufferMemory = void 0;
|
|
3
|
+
exports.ConversationSummaryBufferMemory = exports.CombinedMemory = exports.ENTITY_MEMORY_CONVERSATION_TEMPLATE = exports.EntityMemory = exports.VectorStoreRetrieverMemory = exports.MotorheadMemory = exports.ChatMessageHistory = exports.BaseChatMemory = exports.BufferWindowMemory = exports.BaseConversationSummaryMemory = exports.ConversationSummaryMemory = exports.getBufferString = exports.getOutputValue = exports.getInputValue = exports.BaseMemory = exports.BufferMemory = void 0;
|
|
4
4
|
var buffer_memory_js_1 = require("./buffer_memory.cjs");
|
|
5
5
|
Object.defineProperty(exports, "BufferMemory", { enumerable: true, get: function () { return buffer_memory_js_1.BufferMemory; } });
|
|
6
6
|
var base_js_1 = require("./base.cjs");
|
|
7
7
|
Object.defineProperty(exports, "BaseMemory", { enumerable: true, get: function () { return base_js_1.BaseMemory; } });
|
|
8
8
|
Object.defineProperty(exports, "getInputValue", { enumerable: true, get: function () { return base_js_1.getInputValue; } });
|
|
9
|
+
Object.defineProperty(exports, "getOutputValue", { enumerable: true, get: function () { return base_js_1.getOutputValue; } });
|
|
9
10
|
Object.defineProperty(exports, "getBufferString", { enumerable: true, get: function () { return base_js_1.getBufferString; } });
|
|
10
11
|
var summary_js_1 = require("./summary.cjs");
|
|
11
12
|
Object.defineProperty(exports, "ConversationSummaryMemory", { enumerable: true, get: function () { return summary_js_1.ConversationSummaryMemory; } });
|
package/dist/memory/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export { BufferMemory, type BufferMemoryInput } from "./buffer_memory.js";
|
|
2
|
-
export { BaseMemory, getInputValue, getBufferString, type InputValues, type OutputValues, type MemoryVariables, } from "./base.js";
|
|
2
|
+
export { BaseMemory, getInputValue, getOutputValue, getBufferString, type InputValues, type OutputValues, type MemoryVariables, } from "./base.js";
|
|
3
3
|
export { ConversationSummaryMemory, type ConversationSummaryMemoryInput, BaseConversationSummaryMemory, type BaseConversationSummaryMemoryInput, } from "./summary.js";
|
|
4
4
|
export { BufferWindowMemory, type BufferWindowMemoryInput, } from "./buffer_window_memory.js";
|
|
5
5
|
export { BaseChatMemory, type BaseChatMemoryInput } from "./chat_memory.js";
|
package/dist/memory/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export { BufferMemory } from "./buffer_memory.js";
|
|
2
|
-
export { BaseMemory, getInputValue, getBufferString, } from "./base.js";
|
|
2
|
+
export { BaseMemory, getInputValue, getOutputValue, getBufferString, } from "./base.js";
|
|
3
3
|
export { ConversationSummaryMemory, BaseConversationSummaryMemory, } from "./summary.js";
|
|
4
4
|
export { BufferWindowMemory, } from "./buffer_window_memory.js";
|
|
5
5
|
export { BaseChatMemory } from "./chat_memory.js";
|
|
@@ -15,18 +15,12 @@ function sortedValues(values) {
|
|
|
15
15
|
class SemanticSimilarityExampleSelector extends base_js_1.BaseExampleSelector {
|
|
16
16
|
constructor(data) {
|
|
17
17
|
super(data);
|
|
18
|
-
Object.defineProperty(this, "
|
|
18
|
+
Object.defineProperty(this, "vectorStoreRetriever", {
|
|
19
19
|
enumerable: true,
|
|
20
20
|
configurable: true,
|
|
21
21
|
writable: true,
|
|
22
22
|
value: void 0
|
|
23
23
|
});
|
|
24
|
-
Object.defineProperty(this, "k", {
|
|
25
|
-
enumerable: true,
|
|
26
|
-
configurable: true,
|
|
27
|
-
writable: true,
|
|
28
|
-
value: 4
|
|
29
|
-
});
|
|
30
24
|
Object.defineProperty(this, "exampleKeys", {
|
|
31
25
|
enumerable: true,
|
|
32
26
|
configurable: true,
|
|
@@ -39,17 +33,20 @@ class SemanticSimilarityExampleSelector extends base_js_1.BaseExampleSelector {
|
|
|
39
33
|
writable: true,
|
|
40
34
|
value: void 0
|
|
41
35
|
});
|
|
42
|
-
Object.defineProperty(this, "filter", {
|
|
43
|
-
enumerable: true,
|
|
44
|
-
configurable: true,
|
|
45
|
-
writable: true,
|
|
46
|
-
value: void 0
|
|
47
|
-
});
|
|
48
|
-
this.vectorStore = data.vectorStore;
|
|
49
|
-
this.k = data.k ?? 4;
|
|
50
36
|
this.exampleKeys = data.exampleKeys;
|
|
51
37
|
this.inputKeys = data.inputKeys;
|
|
52
|
-
|
|
38
|
+
if (data.vectorStore !== undefined) {
|
|
39
|
+
this.vectorStoreRetriever = data.vectorStore.asRetriever({
|
|
40
|
+
k: data.k ?? 4,
|
|
41
|
+
filter: data.filter,
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
else if (data.vectorStoreRetriever) {
|
|
45
|
+
this.vectorStoreRetriever = data.vectorStoreRetriever;
|
|
46
|
+
}
|
|
47
|
+
else {
|
|
48
|
+
throw new Error(`You must specify one of "vectorStore" and "vectorStoreRetriever".`);
|
|
49
|
+
}
|
|
53
50
|
}
|
|
54
51
|
/**
|
|
55
52
|
* Method that adds a new example to the vectorStore. The example is
|
|
@@ -60,7 +57,7 @@ class SemanticSimilarityExampleSelector extends base_js_1.BaseExampleSelector {
|
|
|
60
57
|
async addExample(example) {
|
|
61
58
|
const inputKeys = this.inputKeys ?? Object.keys(example);
|
|
62
59
|
const stringExample = sortedValues(inputKeys.reduce((acc, key) => ({ ...acc, [key]: example[key] }), {})).join(" ");
|
|
63
|
-
await this.
|
|
60
|
+
await this.vectorStoreRetriever.addDocuments([
|
|
64
61
|
new document_js_1.Document({
|
|
65
62
|
pageContent: stringExample,
|
|
66
63
|
metadata: example,
|
|
@@ -77,7 +74,7 @@ class SemanticSimilarityExampleSelector extends base_js_1.BaseExampleSelector {
|
|
|
77
74
|
async selectExamples(inputVariables) {
|
|
78
75
|
const inputKeys = this.inputKeys ?? Object.keys(inputVariables);
|
|
79
76
|
const query = sortedValues(inputKeys.reduce((acc, key) => ({ ...acc, [key]: inputVariables[key] }), {})).join(" ");
|
|
80
|
-
const exampleDocs = await this.
|
|
77
|
+
const exampleDocs = await this.vectorStoreRetriever.invoke(query);
|
|
81
78
|
const examples = exampleDocs.map((doc) => doc.metadata);
|
|
82
79
|
if (this.exampleKeys) {
|
|
83
80
|
// If example keys are provided, filter examples to those keys.
|
|
@@ -1,28 +1,34 @@
|
|
|
1
1
|
import { Embeddings } from "../../embeddings/base.js";
|
|
2
|
-
import { VectorStore } from "../../vectorstores/base.js";
|
|
2
|
+
import { VectorStore, VectorStoreRetriever } from "../../vectorstores/base.js";
|
|
3
3
|
import { Example } from "../../schema/index.js";
|
|
4
4
|
import { BaseExampleSelector } from "../base.js";
|
|
5
5
|
/**
|
|
6
6
|
* Interface for the input data of the SemanticSimilarityExampleSelector
|
|
7
7
|
* class.
|
|
8
8
|
*/
|
|
9
|
-
export
|
|
9
|
+
export type SemanticSimilarityExampleSelectorInput<V extends VectorStore = VectorStore> = {
|
|
10
10
|
vectorStore: V;
|
|
11
11
|
k?: number;
|
|
12
12
|
filter?: V["FilterType"];
|
|
13
13
|
exampleKeys?: string[];
|
|
14
14
|
inputKeys?: string[];
|
|
15
|
-
|
|
15
|
+
vectorStoreRetriever?: never;
|
|
16
|
+
} | {
|
|
17
|
+
vectorStoreRetriever: VectorStoreRetriever<V>;
|
|
18
|
+
exampleKeys?: string[];
|
|
19
|
+
inputKeys?: string[];
|
|
20
|
+
vectorStore?: never;
|
|
21
|
+
k?: never;
|
|
22
|
+
filter?: never;
|
|
23
|
+
};
|
|
16
24
|
/**
|
|
17
25
|
* Class that selects examples based on semantic similarity. It extends
|
|
18
26
|
* the BaseExampleSelector class.
|
|
19
27
|
*/
|
|
20
28
|
export declare class SemanticSimilarityExampleSelector<V extends VectorStore = VectorStore> extends BaseExampleSelector {
|
|
21
|
-
|
|
22
|
-
k: number;
|
|
29
|
+
vectorStoreRetriever: VectorStoreRetriever<V>;
|
|
23
30
|
exampleKeys?: string[];
|
|
24
31
|
inputKeys?: string[];
|
|
25
|
-
filter?: V["FilterType"];
|
|
26
32
|
constructor(data: SemanticSimilarityExampleSelectorInput<V>);
|
|
27
33
|
/**
|
|
28
34
|
* Method that adds a new example to the vectorStore. The example is
|
|
@@ -12,18 +12,12 @@ function sortedValues(values) {
|
|
|
12
12
|
export class SemanticSimilarityExampleSelector extends BaseExampleSelector {
|
|
13
13
|
constructor(data) {
|
|
14
14
|
super(data);
|
|
15
|
-
Object.defineProperty(this, "
|
|
15
|
+
Object.defineProperty(this, "vectorStoreRetriever", {
|
|
16
16
|
enumerable: true,
|
|
17
17
|
configurable: true,
|
|
18
18
|
writable: true,
|
|
19
19
|
value: void 0
|
|
20
20
|
});
|
|
21
|
-
Object.defineProperty(this, "k", {
|
|
22
|
-
enumerable: true,
|
|
23
|
-
configurable: true,
|
|
24
|
-
writable: true,
|
|
25
|
-
value: 4
|
|
26
|
-
});
|
|
27
21
|
Object.defineProperty(this, "exampleKeys", {
|
|
28
22
|
enumerable: true,
|
|
29
23
|
configurable: true,
|
|
@@ -36,17 +30,20 @@ export class SemanticSimilarityExampleSelector extends BaseExampleSelector {
|
|
|
36
30
|
writable: true,
|
|
37
31
|
value: void 0
|
|
38
32
|
});
|
|
39
|
-
Object.defineProperty(this, "filter", {
|
|
40
|
-
enumerable: true,
|
|
41
|
-
configurable: true,
|
|
42
|
-
writable: true,
|
|
43
|
-
value: void 0
|
|
44
|
-
});
|
|
45
|
-
this.vectorStore = data.vectorStore;
|
|
46
|
-
this.k = data.k ?? 4;
|
|
47
33
|
this.exampleKeys = data.exampleKeys;
|
|
48
34
|
this.inputKeys = data.inputKeys;
|
|
49
|
-
|
|
35
|
+
if (data.vectorStore !== undefined) {
|
|
36
|
+
this.vectorStoreRetriever = data.vectorStore.asRetriever({
|
|
37
|
+
k: data.k ?? 4,
|
|
38
|
+
filter: data.filter,
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
else if (data.vectorStoreRetriever) {
|
|
42
|
+
this.vectorStoreRetriever = data.vectorStoreRetriever;
|
|
43
|
+
}
|
|
44
|
+
else {
|
|
45
|
+
throw new Error(`You must specify one of "vectorStore" and "vectorStoreRetriever".`);
|
|
46
|
+
}
|
|
50
47
|
}
|
|
51
48
|
/**
|
|
52
49
|
* Method that adds a new example to the vectorStore. The example is
|
|
@@ -57,7 +54,7 @@ export class SemanticSimilarityExampleSelector extends BaseExampleSelector {
|
|
|
57
54
|
async addExample(example) {
|
|
58
55
|
const inputKeys = this.inputKeys ?? Object.keys(example);
|
|
59
56
|
const stringExample = sortedValues(inputKeys.reduce((acc, key) => ({ ...acc, [key]: example[key] }), {})).join(" ");
|
|
60
|
-
await this.
|
|
57
|
+
await this.vectorStoreRetriever.addDocuments([
|
|
61
58
|
new Document({
|
|
62
59
|
pageContent: stringExample,
|
|
63
60
|
metadata: example,
|
|
@@ -74,7 +71,7 @@ export class SemanticSimilarityExampleSelector extends BaseExampleSelector {
|
|
|
74
71
|
async selectExamples(inputVariables) {
|
|
75
72
|
const inputKeys = this.inputKeys ?? Object.keys(inputVariables);
|
|
76
73
|
const query = sortedValues(inputKeys.reduce((acc, key) => ({ ...acc, [key]: inputVariables[key] }), {})).join(" ");
|
|
77
|
-
const exampleDocs = await this.
|
|
74
|
+
const exampleDocs = await this.vectorStoreRetriever.invoke(query);
|
|
78
75
|
const examples = exampleDocs.map((doc) => doc.metadata);
|
|
79
76
|
if (this.exampleKeys) {
|
|
80
77
|
// If example keys are provided, filter examples to those keys.
|
|
@@ -33,6 +33,7 @@ const flat_1 = __importDefault(require("flat"));
|
|
|
33
33
|
const base_js_1 = require("./base.cjs");
|
|
34
34
|
const document_js_1 = require("../document.cjs");
|
|
35
35
|
const async_caller_js_1 = require("../util/async_caller.cjs");
|
|
36
|
+
const math_js_1 = require("../util/math.cjs");
|
|
36
37
|
/**
|
|
37
38
|
* Class that extends the VectorStore class and provides methods to
|
|
38
39
|
* interact with the Pinecone vector database.
|
|
@@ -166,15 +167,7 @@ class PineconeStore extends base_js_1.VectorStore {
|
|
|
166
167
|
throw new Error("Either ids or delete_all must be provided.");
|
|
167
168
|
}
|
|
168
169
|
}
|
|
169
|
-
|
|
170
|
-
* Method that performs a similarity search in the Pinecone database and
|
|
171
|
-
* returns the results along with their scores.
|
|
172
|
-
* @param query Query vector for the similarity search.
|
|
173
|
-
* @param k Number of top results to return.
|
|
174
|
-
* @param filter Optional filter to apply to the search.
|
|
175
|
-
* @returns Promise that resolves with an array of documents and their scores.
|
|
176
|
-
*/
|
|
177
|
-
async similaritySearchVectorWithScore(query, k, filter) {
|
|
170
|
+
async _runPineconeQuery(query, k, filter, options) {
|
|
178
171
|
if (filter && this.filter) {
|
|
179
172
|
throw new Error("cannot provide both `filter` and `this.filter`");
|
|
180
173
|
}
|
|
@@ -185,7 +178,20 @@ class PineconeStore extends base_js_1.VectorStore {
|
|
|
185
178
|
topK: k,
|
|
186
179
|
vector: query,
|
|
187
180
|
filter: _filter,
|
|
181
|
+
...options,
|
|
188
182
|
});
|
|
183
|
+
return results;
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* Method that performs a similarity search in the Pinecone database and
|
|
187
|
+
* returns the results along with their scores.
|
|
188
|
+
* @param query Query vector for the similarity search.
|
|
189
|
+
* @param k Number of top results to return.
|
|
190
|
+
* @param filter Optional filter to apply to the search.
|
|
191
|
+
* @returns Promise that resolves with an array of documents and their scores.
|
|
192
|
+
*/
|
|
193
|
+
async similaritySearchVectorWithScore(query, k, filter) {
|
|
194
|
+
const results = await this._runPineconeQuery(query, k, filter);
|
|
189
195
|
const result = [];
|
|
190
196
|
if (results.matches) {
|
|
191
197
|
for (const res of results.matches) {
|
|
@@ -198,6 +204,37 @@ class PineconeStore extends base_js_1.VectorStore {
|
|
|
198
204
|
}
|
|
199
205
|
return result;
|
|
200
206
|
}
|
|
207
|
+
/**
|
|
208
|
+
* Return documents selected using the maximal marginal relevance.
|
|
209
|
+
* Maximal marginal relevance optimizes for similarity to the query AND diversity
|
|
210
|
+
* among selected documents.
|
|
211
|
+
*
|
|
212
|
+
* @param {string} query - Text to look up documents similar to.
|
|
213
|
+
* @param {number} options.k - Number of documents to return.
|
|
214
|
+
* @param {number} options.fetchK=20 - Number of documents to fetch before passing to the MMR algorithm.
|
|
215
|
+
* @param {number} options.lambda=0.5 - Number between 0 and 1 that determines the degree of diversity among the results,
|
|
216
|
+
* where 0 corresponds to maximum diversity and 1 to minimum diversity.
|
|
217
|
+
* @param {PineconeMetadata} options.filter - Optional filter to apply to the search.
|
|
218
|
+
*
|
|
219
|
+
* @returns {Promise<Document[]>} - List of documents selected by maximal marginal relevance.
|
|
220
|
+
*/
|
|
221
|
+
async maxMarginalRelevanceSearch(query, options) {
|
|
222
|
+
const queryEmbedding = await this.embeddings.embedQuery(query);
|
|
223
|
+
const results = await this._runPineconeQuery(queryEmbedding, options.fetchK ?? 20, options.filter, { includeValues: true });
|
|
224
|
+
const matches = results?.matches ?? [];
|
|
225
|
+
const embeddingList = matches.map((match) => match.values);
|
|
226
|
+
const mmrIndexes = (0, math_js_1.maximalMarginalRelevance)(queryEmbedding, embeddingList, options.lambda, options.k);
|
|
227
|
+
const topMmrMatches = mmrIndexes.map((idx) => matches[idx]);
|
|
228
|
+
const finalResult = [];
|
|
229
|
+
for (const res of topMmrMatches) {
|
|
230
|
+
const { [this.textKey]: pageContent, ...metadata } = (res.metadata ??
|
|
231
|
+
{});
|
|
232
|
+
if (res.score) {
|
|
233
|
+
finalResult.push(new document_js_1.Document({ metadata, pageContent }));
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
return finalResult;
|
|
237
|
+
}
|
|
201
238
|
/**
|
|
202
239
|
* Static method that creates a new instance of the PineconeStore class
|
|
203
240
|
* from texts.
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { Index as PineconeIndex } from "@pinecone-database/pinecone";
|
|
2
|
-
import { VectorStore } from "./base.js";
|
|
1
|
+
import { RecordMetadata, Index as PineconeIndex } from "@pinecone-database/pinecone";
|
|
2
|
+
import { MaxMarginalRelevanceSearchOptions, VectorStore } from "./base.js";
|
|
3
3
|
import { Embeddings } from "../embeddings/base.js";
|
|
4
4
|
import { Document } from "../document.js";
|
|
5
5
|
import { AsyncCaller } from "../util/async_caller.js";
|
|
@@ -57,6 +57,9 @@ export declare class PineconeStore extends VectorStore {
|
|
|
57
57
|
* @returns Promise that resolves when the delete operation is complete.
|
|
58
58
|
*/
|
|
59
59
|
delete(params: PineconeDeleteParams): Promise<void>;
|
|
60
|
+
protected _runPineconeQuery(query: number[], k: number, filter?: PineconeMetadata, options?: {
|
|
61
|
+
includeValues: boolean;
|
|
62
|
+
}): Promise<import("@pinecone-database/pinecone").QueryResponse<RecordMetadata>>;
|
|
60
63
|
/**
|
|
61
64
|
* Method that performs a similarity search in the Pinecone database and
|
|
62
65
|
* returns the results along with their scores.
|
|
@@ -66,6 +69,21 @@ export declare class PineconeStore extends VectorStore {
|
|
|
66
69
|
* @returns Promise that resolves with an array of documents and their scores.
|
|
67
70
|
*/
|
|
68
71
|
similaritySearchVectorWithScore(query: number[], k: number, filter?: PineconeMetadata): Promise<[Document, number][]>;
|
|
72
|
+
/**
|
|
73
|
+
* Return documents selected using the maximal marginal relevance.
|
|
74
|
+
* Maximal marginal relevance optimizes for similarity to the query AND diversity
|
|
75
|
+
* among selected documents.
|
|
76
|
+
*
|
|
77
|
+
* @param {string} query - Text to look up documents similar to.
|
|
78
|
+
* @param {number} options.k - Number of documents to return.
|
|
79
|
+
* @param {number} options.fetchK=20 - Number of documents to fetch before passing to the MMR algorithm.
|
|
80
|
+
* @param {number} options.lambda=0.5 - Number between 0 and 1 that determines the degree of diversity among the results,
|
|
81
|
+
* where 0 corresponds to maximum diversity and 1 to minimum diversity.
|
|
82
|
+
* @param {PineconeMetadata} options.filter - Optional filter to apply to the search.
|
|
83
|
+
*
|
|
84
|
+
* @returns {Promise<Document[]>} - List of documents selected by maximal marginal relevance.
|
|
85
|
+
*/
|
|
86
|
+
maxMarginalRelevanceSearch(query: string, options: MaxMarginalRelevanceSearchOptions<this["FilterType"]>): Promise<Document[]>;
|
|
69
87
|
/**
|
|
70
88
|
* Static method that creates a new instance of the PineconeStore class
|
|
71
89
|
* from texts.
|
|
@@ -4,6 +4,7 @@ import flatten from "flat";
|
|
|
4
4
|
import { VectorStore } from "./base.js";
|
|
5
5
|
import { Document } from "../document.js";
|
|
6
6
|
import { AsyncCaller } from "../util/async_caller.js";
|
|
7
|
+
import { maximalMarginalRelevance } from "../util/math.js";
|
|
7
8
|
/**
|
|
8
9
|
* Class that extends the VectorStore class and provides methods to
|
|
9
10
|
* interact with the Pinecone vector database.
|
|
@@ -137,15 +138,7 @@ export class PineconeStore extends VectorStore {
|
|
|
137
138
|
throw new Error("Either ids or delete_all must be provided.");
|
|
138
139
|
}
|
|
139
140
|
}
|
|
140
|
-
|
|
141
|
-
* Method that performs a similarity search in the Pinecone database and
|
|
142
|
-
* returns the results along with their scores.
|
|
143
|
-
* @param query Query vector for the similarity search.
|
|
144
|
-
* @param k Number of top results to return.
|
|
145
|
-
* @param filter Optional filter to apply to the search.
|
|
146
|
-
* @returns Promise that resolves with an array of documents and their scores.
|
|
147
|
-
*/
|
|
148
|
-
async similaritySearchVectorWithScore(query, k, filter) {
|
|
141
|
+
async _runPineconeQuery(query, k, filter, options) {
|
|
149
142
|
if (filter && this.filter) {
|
|
150
143
|
throw new Error("cannot provide both `filter` and `this.filter`");
|
|
151
144
|
}
|
|
@@ -156,7 +149,20 @@ export class PineconeStore extends VectorStore {
|
|
|
156
149
|
topK: k,
|
|
157
150
|
vector: query,
|
|
158
151
|
filter: _filter,
|
|
152
|
+
...options,
|
|
159
153
|
});
|
|
154
|
+
return results;
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* Method that performs a similarity search in the Pinecone database and
|
|
158
|
+
* returns the results along with their scores.
|
|
159
|
+
* @param query Query vector for the similarity search.
|
|
160
|
+
* @param k Number of top results to return.
|
|
161
|
+
* @param filter Optional filter to apply to the search.
|
|
162
|
+
* @returns Promise that resolves with an array of documents and their scores.
|
|
163
|
+
*/
|
|
164
|
+
async similaritySearchVectorWithScore(query, k, filter) {
|
|
165
|
+
const results = await this._runPineconeQuery(query, k, filter);
|
|
160
166
|
const result = [];
|
|
161
167
|
if (results.matches) {
|
|
162
168
|
for (const res of results.matches) {
|
|
@@ -169,6 +175,37 @@ export class PineconeStore extends VectorStore {
|
|
|
169
175
|
}
|
|
170
176
|
return result;
|
|
171
177
|
}
|
|
178
|
+
/**
|
|
179
|
+
* Return documents selected using the maximal marginal relevance.
|
|
180
|
+
* Maximal marginal relevance optimizes for similarity to the query AND diversity
|
|
181
|
+
* among selected documents.
|
|
182
|
+
*
|
|
183
|
+
* @param {string} query - Text to look up documents similar to.
|
|
184
|
+
* @param {number} options.k - Number of documents to return.
|
|
185
|
+
* @param {number} options.fetchK=20 - Number of documents to fetch before passing to the MMR algorithm.
|
|
186
|
+
* @param {number} options.lambda=0.5 - Number between 0 and 1 that determines the degree of diversity among the results,
|
|
187
|
+
* where 0 corresponds to maximum diversity and 1 to minimum diversity.
|
|
188
|
+
* @param {PineconeMetadata} options.filter - Optional filter to apply to the search.
|
|
189
|
+
*
|
|
190
|
+
* @returns {Promise<Document[]>} - List of documents selected by maximal marginal relevance.
|
|
191
|
+
*/
|
|
192
|
+
async maxMarginalRelevanceSearch(query, options) {
|
|
193
|
+
const queryEmbedding = await this.embeddings.embedQuery(query);
|
|
194
|
+
const results = await this._runPineconeQuery(queryEmbedding, options.fetchK ?? 20, options.filter, { includeValues: true });
|
|
195
|
+
const matches = results?.matches ?? [];
|
|
196
|
+
const embeddingList = matches.map((match) => match.values);
|
|
197
|
+
const mmrIndexes = maximalMarginalRelevance(queryEmbedding, embeddingList, options.lambda, options.k);
|
|
198
|
+
const topMmrMatches = mmrIndexes.map((idx) => matches[idx]);
|
|
199
|
+
const finalResult = [];
|
|
200
|
+
for (const res of topMmrMatches) {
|
|
201
|
+
const { [this.textKey]: pageContent, ...metadata } = (res.metadata ??
|
|
202
|
+
{});
|
|
203
|
+
if (res.score) {
|
|
204
|
+
finalResult.push(new Document({ metadata, pageContent }));
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
return finalResult;
|
|
208
|
+
}
|
|
172
209
|
/**
|
|
173
210
|
* Static method that creates a new instance of the PineconeStore class
|
|
174
211
|
* from texts.
|