langchain 0.0.150 → 0.0.152
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/cache/cloudflare_kv.cjs +1 -0
- package/cache/cloudflare_kv.d.ts +1 -0
- package/cache/cloudflare_kv.js +1 -0
- package/dist/agents/chat/index.cjs +1 -1
- package/dist/agents/chat/index.js +1 -1
- package/dist/agents/chat_convo/index.cjs +1 -1
- package/dist/agents/chat_convo/index.js +1 -1
- package/dist/agents/openai/index.cjs +1 -1
- package/dist/agents/openai/index.js +1 -1
- package/dist/agents/structured_chat/index.cjs +1 -1
- package/dist/agents/structured_chat/index.js +1 -1
- package/dist/agents/xml/index.cjs +1 -1
- package/dist/agents/xml/index.js +1 -1
- package/dist/base_language/count_tokens.cjs +1 -0
- package/dist/base_language/count_tokens.js +1 -0
- package/dist/base_language/index.cjs +5 -3
- package/dist/base_language/index.d.ts +1 -1
- package/dist/base_language/index.js +4 -3
- package/dist/cache/cloudflare_kv.cjs +61 -0
- package/dist/cache/cloudflare_kv.d.ts +29 -0
- package/dist/cache/cloudflare_kv.js +57 -0
- package/dist/chains/openai_functions/openapi.cjs +1 -1
- package/dist/chains/openai_functions/openapi.js +1 -1
- package/dist/chains/question_answering/map_reduce_prompts.cjs +2 -3
- package/dist/chains/question_answering/map_reduce_prompts.js +2 -3
- package/dist/chains/question_answering/refine_prompts.cjs +2 -2
- package/dist/chains/question_answering/refine_prompts.js +2 -2
- package/dist/chains/question_answering/stuff_prompts.cjs +1 -2
- package/dist/chains/question_answering/stuff_prompts.js +1 -2
- package/dist/chat_models/ollama.cjs +3 -7
- package/dist/chat_models/ollama.d.ts +1 -1
- package/dist/chat_models/ollama.js +3 -7
- package/dist/document_loaders/web/pdf.cjs +87 -0
- package/dist/document_loaders/web/pdf.d.ts +17 -0
- package/dist/document_loaders/web/pdf.js +83 -0
- package/dist/evaluation/agents/prompt.cjs +2 -3
- package/dist/evaluation/agents/prompt.js +2 -3
- package/dist/experimental/chat_models/bittensor.cjs +141 -0
- package/dist/experimental/chat_models/bittensor.d.ts +36 -0
- package/dist/experimental/chat_models/bittensor.js +137 -0
- package/dist/experimental/plan_and_execute/prompt.cjs +1 -1
- package/dist/experimental/plan_and_execute/prompt.js +1 -1
- package/dist/llms/llama_cpp.cjs +10 -4
- package/dist/llms/llama_cpp.d.ts +2 -1
- package/dist/llms/llama_cpp.js +10 -4
- package/dist/llms/ollama.cjs +5 -6
- package/dist/llms/ollama.d.ts +2 -2
- package/dist/llms/ollama.js +5 -6
- package/dist/llms/openai.cjs +3 -3
- package/dist/llms/openai.js +3 -3
- package/dist/load/import_constants.cjs +4 -0
- package/dist/load/import_constants.js +4 -0
- package/dist/load/import_map.cjs +2 -1
- package/dist/load/import_map.d.ts +1 -0
- package/dist/load/import_map.js +1 -0
- package/dist/prompts/chat.cjs +12 -1
- package/dist/prompts/chat.d.ts +8 -0
- package/dist/prompts/chat.js +12 -1
- package/dist/schema/runnable/base.cjs +10 -2
- package/dist/schema/runnable/base.d.ts +2 -0
- package/dist/schema/runnable/base.js +9 -2
- package/dist/schema/runnable/branch.cjs +106 -0
- package/dist/schema/runnable/branch.d.ts +66 -0
- package/dist/schema/runnable/branch.js +102 -0
- package/dist/schema/runnable/index.cjs +12 -16
- package/dist/schema/runnable/index.d.ts +2 -1
- package/dist/schema/runnable/index.js +2 -1
- package/dist/stores/message/cloudflare_d1.cjs +134 -0
- package/dist/stores/message/cloudflare_d1.d.ts +49 -0
- package/dist/stores/message/cloudflare_d1.js +130 -0
- package/dist/types/openai-types.d.ts +2 -0
- package/dist/vectorstores/pgvector.cjs +277 -0
- package/dist/vectorstores/pgvector.d.ts +132 -0
- package/dist/vectorstores/pgvector.js +270 -0
- package/document_loaders/web/pdf.cjs +1 -0
- package/document_loaders/web/pdf.d.ts +1 -0
- package/document_loaders/web/pdf.js +1 -0
- package/experimental/chat_models/bittensor.cjs +1 -0
- package/experimental/chat_models/bittensor.d.ts +1 -0
- package/experimental/chat_models/bittensor.js +1 -0
- package/package.json +46 -1
- package/stores/message/cloudflare_d1.cjs +1 -0
- package/stores/message/cloudflare_d1.d.ts +1 -0
- package/stores/message/cloudflare_d1.js +1 -0
- package/vectorstores/pgvector.cjs +1 -0
- package/vectorstores/pgvector.d.ts +1 -0
- package/vectorstores/pgvector.js +1 -0
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.CloudflareD1MessageHistory = void 0;
|
|
4
|
+
const uuid_1 = require("uuid");
|
|
5
|
+
const index_js_1 = require("../../schema/index.cjs");
|
|
6
|
+
const utils_js_1 = require("./utils.cjs");
|
|
7
|
+
/**
|
|
8
|
+
* Class for storing and retrieving chat message history from a
|
|
9
|
+
* Cloudflare D1 database. Extends the BaseListChatMessageHistory class.
|
|
10
|
+
*/
|
|
11
|
+
class CloudflareD1MessageHistory extends index_js_1.BaseListChatMessageHistory {
|
|
12
|
+
constructor(fields) {
|
|
13
|
+
super(fields);
|
|
14
|
+
Object.defineProperty(this, "lc_namespace", {
|
|
15
|
+
enumerable: true,
|
|
16
|
+
configurable: true,
|
|
17
|
+
writable: true,
|
|
18
|
+
value: ["langchain", "stores", "message", "cloudflare_d1"]
|
|
19
|
+
});
|
|
20
|
+
Object.defineProperty(this, "database", {
|
|
21
|
+
enumerable: true,
|
|
22
|
+
configurable: true,
|
|
23
|
+
writable: true,
|
|
24
|
+
value: void 0
|
|
25
|
+
});
|
|
26
|
+
Object.defineProperty(this, "tableName", {
|
|
27
|
+
enumerable: true,
|
|
28
|
+
configurable: true,
|
|
29
|
+
writable: true,
|
|
30
|
+
value: void 0
|
|
31
|
+
});
|
|
32
|
+
Object.defineProperty(this, "sessionId", {
|
|
33
|
+
enumerable: true,
|
|
34
|
+
configurable: true,
|
|
35
|
+
writable: true,
|
|
36
|
+
value: void 0
|
|
37
|
+
});
|
|
38
|
+
Object.defineProperty(this, "tableInitialized", {
|
|
39
|
+
enumerable: true,
|
|
40
|
+
configurable: true,
|
|
41
|
+
writable: true,
|
|
42
|
+
value: void 0
|
|
43
|
+
});
|
|
44
|
+
const { sessionId, database, tableName } = fields;
|
|
45
|
+
if (database) {
|
|
46
|
+
this.database = database;
|
|
47
|
+
}
|
|
48
|
+
else {
|
|
49
|
+
throw new Error("Either a client or config must be provided to CloudflareD1MessageHistory");
|
|
50
|
+
}
|
|
51
|
+
this.tableName = tableName || "langchain_chat_histories";
|
|
52
|
+
this.tableInitialized = false;
|
|
53
|
+
this.sessionId = sessionId;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Private method to ensure that the necessary table exists in the
|
|
57
|
+
* Cloudflare D1 database before performing any operations. If the table
|
|
58
|
+
* does not exist, it is created.
|
|
59
|
+
* @returns Promise that resolves to void.
|
|
60
|
+
*/
|
|
61
|
+
async ensureTable() {
|
|
62
|
+
if (this.tableInitialized) {
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
const query = `CREATE TABLE IF NOT EXISTS ${this.tableName} (id TEXT PRIMARY KEY, session_id TEXT, type TEXT, content TEXT, role TEXT, name TEXT, additional_kwargs TEXT);`;
|
|
66
|
+
await this.database.prepare(query).bind().all();
|
|
67
|
+
const idIndexQuery = `CREATE INDEX IF NOT EXISTS id_index ON ${this.tableName} (id);`;
|
|
68
|
+
await this.database.prepare(idIndexQuery).bind().all();
|
|
69
|
+
const sessionIdIndexQuery = `CREATE INDEX IF NOT EXISTS session_id_index ON ${this.tableName} (session_id);`;
|
|
70
|
+
await this.database.prepare(sessionIdIndexQuery).bind().all();
|
|
71
|
+
this.tableInitialized = true;
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Method to retrieve all messages from the Cloudflare D1 database for the
|
|
75
|
+
* current session.
|
|
76
|
+
* @returns Promise that resolves to an array of BaseMessage objects.
|
|
77
|
+
*/
|
|
78
|
+
async getMessages() {
|
|
79
|
+
await this.ensureTable();
|
|
80
|
+
const query = `SELECT * FROM ${this.tableName} WHERE session_id = ?`;
|
|
81
|
+
const rawStoredMessages = await this.database
|
|
82
|
+
.prepare(query)
|
|
83
|
+
.bind(this.sessionId)
|
|
84
|
+
.all();
|
|
85
|
+
const storedMessagesObject = rawStoredMessages.results;
|
|
86
|
+
const orderedMessages = storedMessagesObject.map((message) => {
|
|
87
|
+
const data = {
|
|
88
|
+
content: message.content,
|
|
89
|
+
additional_kwargs: JSON.parse(message.additional_kwargs),
|
|
90
|
+
};
|
|
91
|
+
if (message.role) {
|
|
92
|
+
data.role = message.role;
|
|
93
|
+
}
|
|
94
|
+
if (message.name) {
|
|
95
|
+
data.name = message.name;
|
|
96
|
+
}
|
|
97
|
+
return {
|
|
98
|
+
type: message.type,
|
|
99
|
+
data,
|
|
100
|
+
};
|
|
101
|
+
});
|
|
102
|
+
return (0, utils_js_1.mapStoredMessagesToChatMessages)(orderedMessages);
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Method to add a new message to the Cloudflare D1 database for the current
|
|
106
|
+
* session.
|
|
107
|
+
* @param message The BaseMessage object to be added to the database.
|
|
108
|
+
* @returns Promise that resolves to void.
|
|
109
|
+
*/
|
|
110
|
+
async addMessage(message) {
|
|
111
|
+
await this.ensureTable();
|
|
112
|
+
const messageToAdd = (0, utils_js_1.mapChatMessagesToStoredMessages)([message]);
|
|
113
|
+
const query = `INSERT INTO ${this.tableName} (id, session_id, type, content, role, name, additional_kwargs) VALUES(?, ?, ?, ?, ?, ?, ?)`;
|
|
114
|
+
const id = (0, uuid_1.v4)();
|
|
115
|
+
await this.database
|
|
116
|
+
.prepare(query)
|
|
117
|
+
.bind(id, this.sessionId, messageToAdd[0].type || null, messageToAdd[0].data.content || null, messageToAdd[0].data.role || null, messageToAdd[0].data.name || null, JSON.stringify(messageToAdd[0].data.additional_kwargs))
|
|
118
|
+
.all();
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Method to delete all messages from the Cloudflare D1 database for the
|
|
122
|
+
* current session.
|
|
123
|
+
* @returns Promise that resolves to void.
|
|
124
|
+
*/
|
|
125
|
+
async clear() {
|
|
126
|
+
await this.ensureTable();
|
|
127
|
+
const query = `DELETE FROM ? WHERE session_id = ? `;
|
|
128
|
+
await this.database
|
|
129
|
+
.prepare(query)
|
|
130
|
+
.bind(this.tableName, this.sessionId)
|
|
131
|
+
.all();
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
exports.CloudflareD1MessageHistory = CloudflareD1MessageHistory;
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import type { D1Database } from "@cloudflare/workers-types";
|
|
2
|
+
import { BaseMessage, BaseListChatMessageHistory } from "../../schema/index.js";
|
|
3
|
+
/**
|
|
4
|
+
* Type definition for the input parameters required when instantiating a
|
|
5
|
+
* CloudflareD1MessageHistory object.
|
|
6
|
+
*/
|
|
7
|
+
export type CloudflareD1MessageHistoryInput = {
|
|
8
|
+
tableName?: string;
|
|
9
|
+
sessionId: string;
|
|
10
|
+
database?: D1Database;
|
|
11
|
+
};
|
|
12
|
+
/**
|
|
13
|
+
* Class for storing and retrieving chat message history from a
|
|
14
|
+
* Cloudflare D1 database. Extends the BaseListChatMessageHistory class.
|
|
15
|
+
*/
|
|
16
|
+
export declare class CloudflareD1MessageHistory extends BaseListChatMessageHistory {
|
|
17
|
+
lc_namespace: string[];
|
|
18
|
+
database: D1Database;
|
|
19
|
+
private tableName;
|
|
20
|
+
private sessionId;
|
|
21
|
+
private tableInitialized;
|
|
22
|
+
constructor(fields: CloudflareD1MessageHistoryInput);
|
|
23
|
+
/**
|
|
24
|
+
* Private method to ensure that the necessary table exists in the
|
|
25
|
+
* Cloudflare D1 database before performing any operations. If the table
|
|
26
|
+
* does not exist, it is created.
|
|
27
|
+
* @returns Promise that resolves to void.
|
|
28
|
+
*/
|
|
29
|
+
private ensureTable;
|
|
30
|
+
/**
|
|
31
|
+
* Method to retrieve all messages from the Cloudflare D1 database for the
|
|
32
|
+
* current session.
|
|
33
|
+
* @returns Promise that resolves to an array of BaseMessage objects.
|
|
34
|
+
*/
|
|
35
|
+
getMessages(): Promise<BaseMessage[]>;
|
|
36
|
+
/**
|
|
37
|
+
* Method to add a new message to the Cloudflare D1 database for the current
|
|
38
|
+
* session.
|
|
39
|
+
* @param message The BaseMessage object to be added to the database.
|
|
40
|
+
* @returns Promise that resolves to void.
|
|
41
|
+
*/
|
|
42
|
+
addMessage(message: BaseMessage): Promise<void>;
|
|
43
|
+
/**
|
|
44
|
+
* Method to delete all messages from the Cloudflare D1 database for the
|
|
45
|
+
* current session.
|
|
46
|
+
* @returns Promise that resolves to void.
|
|
47
|
+
*/
|
|
48
|
+
clear(): Promise<void>;
|
|
49
|
+
}
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import { v4 } from "uuid";
|
|
2
|
+
import { BaseListChatMessageHistory, } from "../../schema/index.js";
|
|
3
|
+
import { mapChatMessagesToStoredMessages, mapStoredMessagesToChatMessages, } from "./utils.js";
|
|
4
|
+
/**
|
|
5
|
+
* Class for storing and retrieving chat message history from a
|
|
6
|
+
* Cloudflare D1 database. Extends the BaseListChatMessageHistory class.
|
|
7
|
+
*/
|
|
8
|
+
export class CloudflareD1MessageHistory extends BaseListChatMessageHistory {
|
|
9
|
+
constructor(fields) {
|
|
10
|
+
super(fields);
|
|
11
|
+
Object.defineProperty(this, "lc_namespace", {
|
|
12
|
+
enumerable: true,
|
|
13
|
+
configurable: true,
|
|
14
|
+
writable: true,
|
|
15
|
+
value: ["langchain", "stores", "message", "cloudflare_d1"]
|
|
16
|
+
});
|
|
17
|
+
Object.defineProperty(this, "database", {
|
|
18
|
+
enumerable: true,
|
|
19
|
+
configurable: true,
|
|
20
|
+
writable: true,
|
|
21
|
+
value: void 0
|
|
22
|
+
});
|
|
23
|
+
Object.defineProperty(this, "tableName", {
|
|
24
|
+
enumerable: true,
|
|
25
|
+
configurable: true,
|
|
26
|
+
writable: true,
|
|
27
|
+
value: void 0
|
|
28
|
+
});
|
|
29
|
+
Object.defineProperty(this, "sessionId", {
|
|
30
|
+
enumerable: true,
|
|
31
|
+
configurable: true,
|
|
32
|
+
writable: true,
|
|
33
|
+
value: void 0
|
|
34
|
+
});
|
|
35
|
+
Object.defineProperty(this, "tableInitialized", {
|
|
36
|
+
enumerable: true,
|
|
37
|
+
configurable: true,
|
|
38
|
+
writable: true,
|
|
39
|
+
value: void 0
|
|
40
|
+
});
|
|
41
|
+
const { sessionId, database, tableName } = fields;
|
|
42
|
+
if (database) {
|
|
43
|
+
this.database = database;
|
|
44
|
+
}
|
|
45
|
+
else {
|
|
46
|
+
throw new Error("Either a client or config must be provided to CloudflareD1MessageHistory");
|
|
47
|
+
}
|
|
48
|
+
this.tableName = tableName || "langchain_chat_histories";
|
|
49
|
+
this.tableInitialized = false;
|
|
50
|
+
this.sessionId = sessionId;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Private method to ensure that the necessary table exists in the
|
|
54
|
+
* Cloudflare D1 database before performing any operations. If the table
|
|
55
|
+
* does not exist, it is created.
|
|
56
|
+
* @returns Promise that resolves to void.
|
|
57
|
+
*/
|
|
58
|
+
async ensureTable() {
|
|
59
|
+
if (this.tableInitialized) {
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
const query = `CREATE TABLE IF NOT EXISTS ${this.tableName} (id TEXT PRIMARY KEY, session_id TEXT, type TEXT, content TEXT, role TEXT, name TEXT, additional_kwargs TEXT);`;
|
|
63
|
+
await this.database.prepare(query).bind().all();
|
|
64
|
+
const idIndexQuery = `CREATE INDEX IF NOT EXISTS id_index ON ${this.tableName} (id);`;
|
|
65
|
+
await this.database.prepare(idIndexQuery).bind().all();
|
|
66
|
+
const sessionIdIndexQuery = `CREATE INDEX IF NOT EXISTS session_id_index ON ${this.tableName} (session_id);`;
|
|
67
|
+
await this.database.prepare(sessionIdIndexQuery).bind().all();
|
|
68
|
+
this.tableInitialized = true;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Method to retrieve all messages from the Cloudflare D1 database for the
|
|
72
|
+
* current session.
|
|
73
|
+
* @returns Promise that resolves to an array of BaseMessage objects.
|
|
74
|
+
*/
|
|
75
|
+
async getMessages() {
|
|
76
|
+
await this.ensureTable();
|
|
77
|
+
const query = `SELECT * FROM ${this.tableName} WHERE session_id = ?`;
|
|
78
|
+
const rawStoredMessages = await this.database
|
|
79
|
+
.prepare(query)
|
|
80
|
+
.bind(this.sessionId)
|
|
81
|
+
.all();
|
|
82
|
+
const storedMessagesObject = rawStoredMessages.results;
|
|
83
|
+
const orderedMessages = storedMessagesObject.map((message) => {
|
|
84
|
+
const data = {
|
|
85
|
+
content: message.content,
|
|
86
|
+
additional_kwargs: JSON.parse(message.additional_kwargs),
|
|
87
|
+
};
|
|
88
|
+
if (message.role) {
|
|
89
|
+
data.role = message.role;
|
|
90
|
+
}
|
|
91
|
+
if (message.name) {
|
|
92
|
+
data.name = message.name;
|
|
93
|
+
}
|
|
94
|
+
return {
|
|
95
|
+
type: message.type,
|
|
96
|
+
data,
|
|
97
|
+
};
|
|
98
|
+
});
|
|
99
|
+
return mapStoredMessagesToChatMessages(orderedMessages);
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Method to add a new message to the Cloudflare D1 database for the current
|
|
103
|
+
* session.
|
|
104
|
+
* @param message The BaseMessage object to be added to the database.
|
|
105
|
+
* @returns Promise that resolves to void.
|
|
106
|
+
*/
|
|
107
|
+
async addMessage(message) {
|
|
108
|
+
await this.ensureTable();
|
|
109
|
+
const messageToAdd = mapChatMessagesToStoredMessages([message]);
|
|
110
|
+
const query = `INSERT INTO ${this.tableName} (id, session_id, type, content, role, name, additional_kwargs) VALUES(?, ?, ?, ?, ?, ?, ?)`;
|
|
111
|
+
const id = v4();
|
|
112
|
+
await this.database
|
|
113
|
+
.prepare(query)
|
|
114
|
+
.bind(id, this.sessionId, messageToAdd[0].type || null, messageToAdd[0].data.content || null, messageToAdd[0].data.role || null, messageToAdd[0].data.name || null, JSON.stringify(messageToAdd[0].data.additional_kwargs))
|
|
115
|
+
.all();
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Method to delete all messages from the Cloudflare D1 database for the
|
|
119
|
+
* current session.
|
|
120
|
+
* @returns Promise that resolves to void.
|
|
121
|
+
*/
|
|
122
|
+
async clear() {
|
|
123
|
+
await this.ensureTable();
|
|
124
|
+
const query = `DELETE FROM ? WHERE session_id = ? `;
|
|
125
|
+
await this.database
|
|
126
|
+
.prepare(query)
|
|
127
|
+
.bind(this.tableName, this.sessionId)
|
|
128
|
+
.all();
|
|
129
|
+
}
|
|
130
|
+
}
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import type { OpenAI as OpenAIClient } from "openai";
|
|
2
|
+
import { TiktokenModel } from "js-tiktoken/lite";
|
|
2
3
|
import { BaseLanguageModelCallOptions } from "../base_language/index.js";
|
|
4
|
+
export type { TiktokenModel };
|
|
3
5
|
export declare interface OpenAIBaseInput {
|
|
4
6
|
/** Sampling temperature to use */
|
|
5
7
|
temperature: number;
|
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.PGVectorStore = void 0;
|
|
7
|
+
const pg_1 = __importDefault(require("pg"));
|
|
8
|
+
const base_js_1 = require("./base.cjs");
|
|
9
|
+
const document_js_1 = require("../document.cjs");
|
|
10
|
+
const env_js_1 = require("../util/env.cjs");
|
|
11
|
+
/**
|
|
12
|
+
* Class that provides an interface to a Postgres vector database. It
|
|
13
|
+
* extends the `VectorStore` base class and implements methods for adding
|
|
14
|
+
* documents and vectors, performing similarity searches, and ensuring the
|
|
15
|
+
* existence of a table in the database.
|
|
16
|
+
*/
|
|
17
|
+
class PGVectorStore extends base_js_1.VectorStore {
|
|
18
|
+
_vectorstoreType() {
|
|
19
|
+
return "pgvector";
|
|
20
|
+
}
|
|
21
|
+
constructor(embeddings, config) {
|
|
22
|
+
super(embeddings, config);
|
|
23
|
+
Object.defineProperty(this, "tableName", {
|
|
24
|
+
enumerable: true,
|
|
25
|
+
configurable: true,
|
|
26
|
+
writable: true,
|
|
27
|
+
value: void 0
|
|
28
|
+
});
|
|
29
|
+
Object.defineProperty(this, "idColumnName", {
|
|
30
|
+
enumerable: true,
|
|
31
|
+
configurable: true,
|
|
32
|
+
writable: true,
|
|
33
|
+
value: void 0
|
|
34
|
+
});
|
|
35
|
+
Object.defineProperty(this, "vectorColumnName", {
|
|
36
|
+
enumerable: true,
|
|
37
|
+
configurable: true,
|
|
38
|
+
writable: true,
|
|
39
|
+
value: void 0
|
|
40
|
+
});
|
|
41
|
+
Object.defineProperty(this, "contentColumnName", {
|
|
42
|
+
enumerable: true,
|
|
43
|
+
configurable: true,
|
|
44
|
+
writable: true,
|
|
45
|
+
value: void 0
|
|
46
|
+
});
|
|
47
|
+
Object.defineProperty(this, "metadataColumnName", {
|
|
48
|
+
enumerable: true,
|
|
49
|
+
configurable: true,
|
|
50
|
+
writable: true,
|
|
51
|
+
value: void 0
|
|
52
|
+
});
|
|
53
|
+
Object.defineProperty(this, "filter", {
|
|
54
|
+
enumerable: true,
|
|
55
|
+
configurable: true,
|
|
56
|
+
writable: true,
|
|
57
|
+
value: void 0
|
|
58
|
+
});
|
|
59
|
+
Object.defineProperty(this, "_verbose", {
|
|
60
|
+
enumerable: true,
|
|
61
|
+
configurable: true,
|
|
62
|
+
writable: true,
|
|
63
|
+
value: void 0
|
|
64
|
+
});
|
|
65
|
+
Object.defineProperty(this, "pool", {
|
|
66
|
+
enumerable: true,
|
|
67
|
+
configurable: true,
|
|
68
|
+
writable: true,
|
|
69
|
+
value: void 0
|
|
70
|
+
});
|
|
71
|
+
Object.defineProperty(this, "client", {
|
|
72
|
+
enumerable: true,
|
|
73
|
+
configurable: true,
|
|
74
|
+
writable: true,
|
|
75
|
+
value: void 0
|
|
76
|
+
});
|
|
77
|
+
this.tableName = config.tableName;
|
|
78
|
+
this.filter = config.filter;
|
|
79
|
+
this.vectorColumnName = config.columns?.vectorColumnName ?? "embedding";
|
|
80
|
+
this.contentColumnName = config.columns?.contentColumnName ?? "text";
|
|
81
|
+
this.idColumnName = config.columns?.idColumnName ?? "id";
|
|
82
|
+
this.metadataColumnName = config.columns?.metadataColumnName ?? "metadata";
|
|
83
|
+
const pool = new pg_1.default.Pool(config.postgresConnectionOptions);
|
|
84
|
+
this.pool = pool;
|
|
85
|
+
this._verbose =
|
|
86
|
+
(0, env_js_1.getEnvironmentVariable)("LANGCHAIN_VERBOSE") === "true" ??
|
|
87
|
+
!!config.verbose;
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Static method to create a new `PGVectorStore` instance from a
|
|
91
|
+
* connection. It creates a table if one does not exist, and calls
|
|
92
|
+
* `connect` to return a new instance of `PGVectorStore`.
|
|
93
|
+
*
|
|
94
|
+
* @param embeddings - Embeddings instance.
|
|
95
|
+
* @param fields - `PGVectorStoreArgs` instance.
|
|
96
|
+
* @returns A new instance of `PGVectorStore`.
|
|
97
|
+
*/
|
|
98
|
+
static async initialize(embeddings, config) {
|
|
99
|
+
const postgresqlVectorStore = new PGVectorStore(embeddings, config);
|
|
100
|
+
await postgresqlVectorStore._initializeClient();
|
|
101
|
+
await postgresqlVectorStore.ensureTableInDatabase();
|
|
102
|
+
return postgresqlVectorStore;
|
|
103
|
+
}
|
|
104
|
+
async _initializeClient() {
|
|
105
|
+
this.client = await this.pool.connect();
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Method to add documents to the vector store. It converts the documents into
|
|
109
|
+
* vectors, and adds them to the store.
|
|
110
|
+
*
|
|
111
|
+
* @param documents - Array of `Document` instances.
|
|
112
|
+
* @returns Promise that resolves when the documents have been added.
|
|
113
|
+
*/
|
|
114
|
+
async addDocuments(documents) {
|
|
115
|
+
const texts = documents.map(({ pageContent }) => pageContent);
|
|
116
|
+
return this.addVectors(await this.embeddings.embedDocuments(texts), documents);
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Generates the SQL placeholders for a specific row at the provided index.
|
|
120
|
+
*
|
|
121
|
+
* @param index - The index of the row for which placeholders need to be generated.
|
|
122
|
+
* @returns The SQL placeholders for the row values.
|
|
123
|
+
*/
|
|
124
|
+
generatePlaceholderForRowAt(index) {
|
|
125
|
+
const base = index * 3;
|
|
126
|
+
return `($${base + 1}, $${base + 2}, $${base + 3})`;
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Constructs the SQL query for inserting rows into the specified table.
|
|
130
|
+
*
|
|
131
|
+
* @param rows - The rows of data to be inserted, consisting of values and records.
|
|
132
|
+
* @param chunkIndex - The starting index for generating query placeholders based on chunk positioning.
|
|
133
|
+
* @returns The complete SQL INSERT INTO query string.
|
|
134
|
+
*/
|
|
135
|
+
buildInsertQuery(rows, chunkIndex) {
|
|
136
|
+
const valuesPlaceholders = rows
|
|
137
|
+
.map((_, j) => this.generatePlaceholderForRowAt(chunkIndex + j))
|
|
138
|
+
.join(", ");
|
|
139
|
+
const text = `
|
|
140
|
+
INSERT INTO ${this.tableName}(
|
|
141
|
+
${this.contentColumnName},
|
|
142
|
+
${this.vectorColumnName},
|
|
143
|
+
${this.metadataColumnName}
|
|
144
|
+
)
|
|
145
|
+
VALUES ${valuesPlaceholders}
|
|
146
|
+
`;
|
|
147
|
+
return text;
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* Method to add vectors to the vector store. It converts the vectors into
|
|
151
|
+
* rows and inserts them into the database.
|
|
152
|
+
*
|
|
153
|
+
* @param vectors - Array of vectors.
|
|
154
|
+
* @param documents - Array of `Document` instances.
|
|
155
|
+
* @returns Promise that resolves when the vectors have been added.
|
|
156
|
+
*/
|
|
157
|
+
async addVectors(vectors, documents) {
|
|
158
|
+
const rows = vectors.map((embedding, idx) => {
|
|
159
|
+
const embeddingString = `[${embedding.join(",")}]`;
|
|
160
|
+
return [
|
|
161
|
+
documents[idx].pageContent,
|
|
162
|
+
embeddingString,
|
|
163
|
+
documents[idx].metadata,
|
|
164
|
+
];
|
|
165
|
+
});
|
|
166
|
+
const chunkSize = 500;
|
|
167
|
+
for (let i = 0; i < rows.length; i += chunkSize) {
|
|
168
|
+
const chunk = rows.slice(i, i + chunkSize);
|
|
169
|
+
const insertQuery = this.buildInsertQuery(chunk, i);
|
|
170
|
+
const flatValues = chunk.flat();
|
|
171
|
+
try {
|
|
172
|
+
await this.pool.query(insertQuery, flatValues);
|
|
173
|
+
}
|
|
174
|
+
catch (e) {
|
|
175
|
+
console.error(e);
|
|
176
|
+
throw new Error(`Error inserting: ${chunk[1]}`);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* Method to perform a similarity search in the vector store. It returns
|
|
182
|
+
* the `k` most similar documents to the query vector, along with their
|
|
183
|
+
* similarity scores.
|
|
184
|
+
*
|
|
185
|
+
* @param query - Query vector.
|
|
186
|
+
* @param k - Number of most similar documents to return.
|
|
187
|
+
* @param filter - Optional filter to apply to the search.
|
|
188
|
+
* @returns Promise that resolves with an array of tuples, each containing a `Document` and its similarity score.
|
|
189
|
+
*/
|
|
190
|
+
async similaritySearchVectorWithScore(query, k, filter) {
|
|
191
|
+
const embeddingString = `[${query.join(",")}]`;
|
|
192
|
+
const _filter = filter ?? "{}";
|
|
193
|
+
const queryString = `
|
|
194
|
+
SELECT *, ${this.vectorColumnName} <=> $1 as "_distance"
|
|
195
|
+
FROM ${this.tableName}
|
|
196
|
+
WHERE ${this.metadataColumnName} @> $2
|
|
197
|
+
ORDER BY "_distance" ASC
|
|
198
|
+
LIMIT $3;`;
|
|
199
|
+
const documents = (await this.pool.query(queryString, [embeddingString, _filter, k])).rows;
|
|
200
|
+
const results = [];
|
|
201
|
+
for (const doc of documents) {
|
|
202
|
+
if (doc._distance != null && doc[this.contentColumnName] != null) {
|
|
203
|
+
const document = new document_js_1.Document({
|
|
204
|
+
pageContent: doc[this.contentColumnName],
|
|
205
|
+
metadata: doc[this.metadataColumnName],
|
|
206
|
+
});
|
|
207
|
+
results.push([document, doc._distance]);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
return results;
|
|
211
|
+
}
|
|
212
|
+
/**
|
|
213
|
+
* Method to ensure the existence of the table in the database. It creates
|
|
214
|
+
* the table if it does not already exist.
|
|
215
|
+
*
|
|
216
|
+
* @returns Promise that resolves when the table has been ensured.
|
|
217
|
+
*/
|
|
218
|
+
async ensureTableInDatabase() {
|
|
219
|
+
await this.pool.query("CREATE EXTENSION IF NOT EXISTS vector;");
|
|
220
|
+
await this.pool.query('CREATE EXTENSION IF NOT EXISTS "uuid-ossp";');
|
|
221
|
+
await this.pool.query(`
|
|
222
|
+
CREATE TABLE IF NOT EXISTS ${this.tableName} (
|
|
223
|
+
"${this.idColumnName}" uuid NOT NULL DEFAULT uuid_generate_v4() PRIMARY KEY,
|
|
224
|
+
"${this.contentColumnName}" text,
|
|
225
|
+
"${this.metadataColumnName}" jsonb,
|
|
226
|
+
"${this.vectorColumnName}" vector
|
|
227
|
+
);
|
|
228
|
+
`);
|
|
229
|
+
}
|
|
230
|
+
/**
|
|
231
|
+
* Static method to create a new `PGVectorStore` instance from an
|
|
232
|
+
* array of texts and their metadata. It converts the texts into
|
|
233
|
+
* `Document` instances and adds them to the store.
|
|
234
|
+
*
|
|
235
|
+
* @param texts - Array of texts.
|
|
236
|
+
* @param metadatas - Array of metadata objects or a single metadata object.
|
|
237
|
+
* @param embeddings - Embeddings instance.
|
|
238
|
+
* @param dbConfig - `PGVectorStoreArgs` instance.
|
|
239
|
+
* @returns Promise that resolves with a new instance of `PGVectorStore`.
|
|
240
|
+
*/
|
|
241
|
+
static async fromTexts(texts, metadatas, embeddings, dbConfig) {
|
|
242
|
+
const docs = [];
|
|
243
|
+
for (let i = 0; i < texts.length; i += 1) {
|
|
244
|
+
const metadata = Array.isArray(metadatas) ? metadatas[i] : metadatas;
|
|
245
|
+
const newDoc = new document_js_1.Document({
|
|
246
|
+
pageContent: texts[i],
|
|
247
|
+
metadata,
|
|
248
|
+
});
|
|
249
|
+
docs.push(newDoc);
|
|
250
|
+
}
|
|
251
|
+
return PGVectorStore.fromDocuments(docs, embeddings, dbConfig);
|
|
252
|
+
}
|
|
253
|
+
/**
|
|
254
|
+
* Static method to create a new `PGVectorStore` instance from an
|
|
255
|
+
* array of `Document` instances. It adds the documents to the store.
|
|
256
|
+
*
|
|
257
|
+
* @param docs - Array of `Document` instances.
|
|
258
|
+
* @param embeddings - Embeddings instance.
|
|
259
|
+
* @param dbConfig - `PGVectorStoreArgs` instance.
|
|
260
|
+
* @returns Promise that resolves with a new instance of `PGVectorStore`.
|
|
261
|
+
*/
|
|
262
|
+
static async fromDocuments(docs, embeddings, dbConfig) {
|
|
263
|
+
const instance = await PGVectorStore.initialize(embeddings, dbConfig);
|
|
264
|
+
await instance.addDocuments(docs);
|
|
265
|
+
return instance;
|
|
266
|
+
}
|
|
267
|
+
/**
|
|
268
|
+
* Closes all the clients in the pool and terminates the pool.
|
|
269
|
+
*
|
|
270
|
+
* @returns Promise that resolves when all clients are closed and the pool is terminated.
|
|
271
|
+
*/
|
|
272
|
+
async end() {
|
|
273
|
+
await this.client?.release();
|
|
274
|
+
return this.pool.end();
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
exports.PGVectorStore = PGVectorStore;
|