@lapage/ai-agent 1.0.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.
- package/README.md +487 -0
- package/dist/index.d.ts +119 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +349 -0
- package/dist/index.js.map +1 -0
- package/dist/memory/index.d.ts +2 -0
- package/dist/memory/index.d.ts.map +1 -0
- package/dist/memory/index.js +6 -0
- package/dist/memory/index.js.map +1 -0
- package/dist/memory/memory-manager.d.ts +27 -0
- package/dist/memory/memory-manager.d.ts.map +1 -0
- package/dist/memory/memory-manager.js +175 -0
- package/dist/memory/memory-manager.js.map +1 -0
- package/dist/models/embeddings-factory.d.ts +6 -0
- package/dist/models/embeddings-factory.d.ts.map +1 -0
- package/dist/models/embeddings-factory.js +84 -0
- package/dist/models/embeddings-factory.js.map +1 -0
- package/dist/models/index.d.ts +3 -0
- package/dist/models/index.d.ts.map +1 -0
- package/dist/models/index.js +8 -0
- package/dist/models/index.js.map +1 -0
- package/dist/models/model-factory.d.ts +6 -0
- package/dist/models/model-factory.d.ts.map +1 -0
- package/dist/models/model-factory.js +75 -0
- package/dist/models/model-factory.js.map +1 -0
- package/dist/tools/index.d.ts +34 -0
- package/dist/tools/index.d.ts.map +1 -0
- package/dist/tools/index.js +106 -0
- package/dist/tools/index.js.map +1 -0
- package/dist/tools/json-schema-to-zod.d.ts +8 -0
- package/dist/tools/json-schema-to-zod.d.ts.map +1 -0
- package/dist/tools/json-schema-to-zod.js +191 -0
- package/dist/tools/json-schema-to-zod.js.map +1 -0
- package/dist/tools/mcp-client.d.ts +8 -0
- package/dist/tools/mcp-client.d.ts.map +1 -0
- package/dist/tools/mcp-client.js +125 -0
- package/dist/tools/mcp-client.js.map +1 -0
- package/dist/tools/vector-tools.d.ts +44 -0
- package/dist/tools/vector-tools.d.ts.map +1 -0
- package/dist/tools/vector-tools.js +174 -0
- package/dist/tools/vector-tools.js.map +1 -0
- package/dist/types/index.d.ts +158 -0
- package/dist/types/index.d.ts.map +1 -0
- package/dist/types/index.js +3 -0
- package/dist/types/index.js.map +1 -0
- package/package.json +76 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,349 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
14
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
|
+
};
|
|
16
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
exports.convertJsonSchemaToZod = exports.getMcpServerTools = exports.EmbeddingsFactory = exports.ModelFactory = exports.ToolManager = exports.MemoryManager = exports.AIAgent = void 0;
|
|
18
|
+
const prompts_1 = require("@langchain/core/prompts");
|
|
19
|
+
const agents_1 = require("langchain/agents");
|
|
20
|
+
const lodash_1 = require("lodash");
|
|
21
|
+
const index_1 = require("./tools/index");
|
|
22
|
+
const memory_manager_1 = require("./memory/memory-manager");
|
|
23
|
+
const model_factory_1 = require("./models/model-factory");
|
|
24
|
+
const embeddings_factory_1 = require("./models/embeddings-factory");
|
|
25
|
+
const vector_tools_1 = require("./tools/vector-tools");
|
|
26
|
+
const mcp_client_1 = require("./tools/mcp-client");
|
|
27
|
+
class AIAgent {
|
|
28
|
+
model;
|
|
29
|
+
systemMessage;
|
|
30
|
+
maxIterations;
|
|
31
|
+
returnIntermediateSteps;
|
|
32
|
+
passthroughBinaryImages;
|
|
33
|
+
memory;
|
|
34
|
+
toolManager;
|
|
35
|
+
sessionId = Math.random().toString(36).substring(7); // Default sessionId
|
|
36
|
+
pendingMemoryConfig;
|
|
37
|
+
memorySetupPromise;
|
|
38
|
+
modelInitPromise;
|
|
39
|
+
knowledgeBaseInitPromise;
|
|
40
|
+
mcpServersInitPromise;
|
|
41
|
+
constructor(options) {
|
|
42
|
+
this.model = null;
|
|
43
|
+
this.systemMessage = options.systemMessage || 'You are a helpful assistant';
|
|
44
|
+
this.maxIterations = options.maxIterations || 10;
|
|
45
|
+
this.returnIntermediateSteps = options.returnIntermediateSteps || true;
|
|
46
|
+
this.passthroughBinaryImages = options.passthroughBinaryImages || false;
|
|
47
|
+
this.toolManager = new index_1.ToolManager();
|
|
48
|
+
this.modelInitPromise = this.initializeModel(options.model);
|
|
49
|
+
if (options.tools) {
|
|
50
|
+
if (Array.isArray(options.tools)) {
|
|
51
|
+
this.toolManager.addTools(options.tools);
|
|
52
|
+
}
|
|
53
|
+
else {
|
|
54
|
+
throw new Error('Tools must be an array of ToolOptions');
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
// Auto-create vector search tools from knowledge bases
|
|
58
|
+
if (options.knowledgeBases) {
|
|
59
|
+
this.knowledgeBaseInitPromise = this.addKnowledgeBaseTools(options.knowledgeBases).catch((error) => {
|
|
60
|
+
console.error('Failed to initialize knowledge base tools:', error);
|
|
61
|
+
throw error;
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
// Auto-register tools from MCP servers
|
|
65
|
+
if (options.mcpServers) {
|
|
66
|
+
this.mcpServersInitPromise = this.addMcpServerTools(options.mcpServers).catch((error) => {
|
|
67
|
+
console.error('Failed to initialize MCP server tools:', error);
|
|
68
|
+
throw error;
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
if (options.memory) {
|
|
72
|
+
if (options.memory.sessionId) {
|
|
73
|
+
this.sessionId = options.memory.sessionId;
|
|
74
|
+
}
|
|
75
|
+
this.pendingMemoryConfig = options.memory;
|
|
76
|
+
this.memorySetupPromise = this.setupMemory(options.memory);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Initialize the model asynchronously
|
|
81
|
+
*/
|
|
82
|
+
async initializeModel(modelConfig) {
|
|
83
|
+
try {
|
|
84
|
+
this.model = await model_factory_1.ModelFactory.createModel(modelConfig);
|
|
85
|
+
if (!this.model.bindTools) {
|
|
86
|
+
throw new Error('AI Agent requires a Chat Model which supports Tools calling');
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
catch (error) {
|
|
90
|
+
throw new Error(`Failed to initialize model: ${error instanceof Error ? error.message : String(error)}`);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Ensure model is initialized before operations
|
|
95
|
+
*/
|
|
96
|
+
async ensureModelReady() {
|
|
97
|
+
await this.modelInitPromise;
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Ensure memory is set up before operations
|
|
101
|
+
*/
|
|
102
|
+
async ensureMemoryReady() {
|
|
103
|
+
if (this.memorySetupPromise) {
|
|
104
|
+
await this.memorySetupPromise;
|
|
105
|
+
this.memorySetupPromise = undefined;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Ensure knowledge base tools are initialized before operations
|
|
110
|
+
*/
|
|
111
|
+
async ensureKnowledgeBaseReady() {
|
|
112
|
+
if (this.knowledgeBaseInitPromise) {
|
|
113
|
+
await this.knowledgeBaseInitPromise;
|
|
114
|
+
this.knowledgeBaseInitPromise = undefined;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Ensure MCP server tools are initialized before operations
|
|
119
|
+
*/
|
|
120
|
+
async ensureMcpServersReady() {
|
|
121
|
+
if (this.mcpServersInitPromise) {
|
|
122
|
+
await this.mcpServersInitPromise;
|
|
123
|
+
this.mcpServersInitPromise = undefined;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Set up memory for the agent with specific options
|
|
128
|
+
*/
|
|
129
|
+
async setupMemory(options) {
|
|
130
|
+
if (!options) {
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
this.memory = await memory_manager_1.MemoryManager.getMemory(this.sessionId, options, this.model);
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* Connect to MCP servers and register all their tools with the agent.
|
|
137
|
+
*/
|
|
138
|
+
async addMcpServerTools(mcpServers) {
|
|
139
|
+
for (const serverConfig of mcpServers) {
|
|
140
|
+
try {
|
|
141
|
+
const tools = await (0, mcp_client_1.getMcpServerTools)(serverConfig);
|
|
142
|
+
for (const tool of tools) {
|
|
143
|
+
this.toolManager.addLangChainTool(tool);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
catch (error) {
|
|
147
|
+
console.error(`Failed to connect to MCP server '${serverConfig.url}':`, error);
|
|
148
|
+
throw new Error(`Failed to connect to MCP server '${serverConfig.url}': ${error instanceof Error ? error.message : String(error)}`);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Create and add vector search tools from knowledge base configurations
|
|
154
|
+
*/
|
|
155
|
+
async addKnowledgeBaseTools(knowledgeBases) {
|
|
156
|
+
for (const kb of knowledgeBases) {
|
|
157
|
+
try {
|
|
158
|
+
// Create embeddings instance from config
|
|
159
|
+
const embeddings = await embeddings_factory_1.EmbeddingsFactory.createEmbeddings(kb.embeddings);
|
|
160
|
+
const vectorSearchTool = (0, vector_tools_1.createVectorSearchTool)({
|
|
161
|
+
toolName: `query_kb_${kb.name}`,
|
|
162
|
+
toolDescription: kb.description,
|
|
163
|
+
pgConfig: kb.pgConfig,
|
|
164
|
+
embeddings: embeddings,
|
|
165
|
+
topK: kb.topK || 4,
|
|
166
|
+
includeMetadata: kb.includeMetadata !== false,
|
|
167
|
+
metadataFilter: kb.metadataFilter,
|
|
168
|
+
outputFormat: 'simple',
|
|
169
|
+
allowDynamicTopK: true,
|
|
170
|
+
});
|
|
171
|
+
this.toolManager.addTool(vectorSearchTool);
|
|
172
|
+
}
|
|
173
|
+
catch (error) {
|
|
174
|
+
console.error(`Failed to create vector search tool for knowledge base '${kb.name}':`, error);
|
|
175
|
+
throw new Error(`Failed to create vector search tool for knowledge base '${kb.name}': ${error instanceof Error ? error.message : String(error)}`);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* Add a custom tool to the agent
|
|
181
|
+
*/
|
|
182
|
+
addTool(toolOptions) {
|
|
183
|
+
this.toolManager.addTool(toolOptions);
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* Add multiple tools at once
|
|
187
|
+
*/
|
|
188
|
+
addTools(toolOptions) {
|
|
189
|
+
this.toolManager.addTools(toolOptions);
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* Add an existing LangChain tool
|
|
193
|
+
*/
|
|
194
|
+
addLangChainTool(tool) {
|
|
195
|
+
this.toolManager.addLangChainTool(tool);
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* Get all available tools
|
|
199
|
+
*/
|
|
200
|
+
getTools() {
|
|
201
|
+
return this.toolManager.getTools();
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Get all available tools (async version that waits for initialization)
|
|
205
|
+
*/
|
|
206
|
+
async getToolsAsync() {
|
|
207
|
+
await this.ensureKnowledgeBaseReady();
|
|
208
|
+
await this.ensureMcpServersReady();
|
|
209
|
+
return this.toolManager.getTools();
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* Clear all tools
|
|
213
|
+
*/
|
|
214
|
+
clearTools() {
|
|
215
|
+
this.toolManager.clearTools();
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
218
|
+
* Clear memory for the current session
|
|
219
|
+
*/
|
|
220
|
+
async clearMemory() {
|
|
221
|
+
await this.ensureMemoryReady();
|
|
222
|
+
if (this.memory) {
|
|
223
|
+
await this.memory.clear();
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* Update the system message
|
|
228
|
+
*/
|
|
229
|
+
setSystemMessage(message) {
|
|
230
|
+
this.systemMessage = message;
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* Update max iterations
|
|
234
|
+
*/
|
|
235
|
+
setMaxIterations(iterations) {
|
|
236
|
+
this.maxIterations = iterations;
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* Prepare the prompt messages for the agent
|
|
240
|
+
*/
|
|
241
|
+
prepareMessages() {
|
|
242
|
+
const messages = [];
|
|
243
|
+
if (this.systemMessage) {
|
|
244
|
+
messages.push(['system', this.systemMessage]);
|
|
245
|
+
}
|
|
246
|
+
messages.push(['placeholder', '{chat_history}'], ['human', '{input}'], ['placeholder', '{agent_scratchpad}']);
|
|
247
|
+
return messages;
|
|
248
|
+
}
|
|
249
|
+
/**
|
|
250
|
+
* Create the chat prompt from messages
|
|
251
|
+
*/
|
|
252
|
+
preparePrompt(messages) {
|
|
253
|
+
return prompts_1.ChatPromptTemplate.fromMessages(messages);
|
|
254
|
+
}
|
|
255
|
+
/**
|
|
256
|
+
* Execute the agent with the given input
|
|
257
|
+
*/
|
|
258
|
+
async invoke(input) {
|
|
259
|
+
try {
|
|
260
|
+
await this.ensureModelReady();
|
|
261
|
+
await this.ensureMemoryReady();
|
|
262
|
+
await this.ensureKnowledgeBaseReady();
|
|
263
|
+
await this.ensureMcpServersReady();
|
|
264
|
+
const messages = this.prepareMessages();
|
|
265
|
+
const prompt = this.preparePrompt(messages);
|
|
266
|
+
const tools = this.toolManager.getTools();
|
|
267
|
+
// Create the base agent that calls tools
|
|
268
|
+
const agent = (0, agents_1.createToolCallingAgent)({
|
|
269
|
+
llm: this.model,
|
|
270
|
+
tools,
|
|
271
|
+
prompt,
|
|
272
|
+
streamRunnable: false,
|
|
273
|
+
});
|
|
274
|
+
// Disable streaming
|
|
275
|
+
agent.streamRunnable = false;
|
|
276
|
+
// Create the agent executor
|
|
277
|
+
const executor = agents_1.AgentExecutor.fromAgentAndTools({
|
|
278
|
+
agent,
|
|
279
|
+
memory: this.memory,
|
|
280
|
+
tools,
|
|
281
|
+
returnIntermediateSteps: this.returnIntermediateSteps,
|
|
282
|
+
maxIterations: this.maxIterations,
|
|
283
|
+
});
|
|
284
|
+
// Invoke the executor with the given input
|
|
285
|
+
const response = await executor.invoke({
|
|
286
|
+
input,
|
|
287
|
+
});
|
|
288
|
+
// Clean up the response by removing internal keys
|
|
289
|
+
const cleanedResponse = (0, lodash_1.omit)(response, 'system_message', 'formatting_instructions', 'input', 'chat_history', 'agent_scratchpad');
|
|
290
|
+
return {
|
|
291
|
+
output: cleanedResponse.output || '',
|
|
292
|
+
intermediateSteps: this.returnIntermediateSteps
|
|
293
|
+
? cleanedResponse.intermediateSteps
|
|
294
|
+
: undefined,
|
|
295
|
+
};
|
|
296
|
+
}
|
|
297
|
+
catch (error) {
|
|
298
|
+
return {
|
|
299
|
+
output: '',
|
|
300
|
+
error: error instanceof Error ? error.message : String(error),
|
|
301
|
+
};
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
/**
|
|
305
|
+
* Execute the agent with streaming support (if available)
|
|
306
|
+
*/
|
|
307
|
+
async stream(input, onToken) {
|
|
308
|
+
// Ensure model is ready before streaming
|
|
309
|
+
await this.ensureModelReady();
|
|
310
|
+
// For now, just call invoke - streaming can be added later if the model supports it
|
|
311
|
+
// This is a placeholder for future streaming functionality
|
|
312
|
+
return this.invoke(input);
|
|
313
|
+
}
|
|
314
|
+
/**
|
|
315
|
+
* Get conversation history from memory
|
|
316
|
+
*/
|
|
317
|
+
async getConversationHistory() {
|
|
318
|
+
await this.ensureMemoryReady();
|
|
319
|
+
if (!this.memory || !this.memory.chatHistory) {
|
|
320
|
+
return [];
|
|
321
|
+
}
|
|
322
|
+
return this.memory.chatHistory.getMessages();
|
|
323
|
+
}
|
|
324
|
+
/**
|
|
325
|
+
* Add a message to the conversation history
|
|
326
|
+
*/
|
|
327
|
+
async addToHistory(input, output) {
|
|
328
|
+
await this.ensureMemoryReady();
|
|
329
|
+
if (this.memory) {
|
|
330
|
+
await this.memory.saveContext({ input }, { output });
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
exports.AIAgent = AIAgent;
|
|
335
|
+
// Export all types and classes
|
|
336
|
+
__exportStar(require("./types/index"), exports);
|
|
337
|
+
var index_2 = require("./memory/index");
|
|
338
|
+
Object.defineProperty(exports, "MemoryManager", { enumerable: true, get: function () { return index_2.MemoryManager; } });
|
|
339
|
+
var index_3 = require("./tools/index");
|
|
340
|
+
Object.defineProperty(exports, "ToolManager", { enumerable: true, get: function () { return index_3.ToolManager; } });
|
|
341
|
+
var model_factory_2 = require("./models/model-factory");
|
|
342
|
+
Object.defineProperty(exports, "ModelFactory", { enumerable: true, get: function () { return model_factory_2.ModelFactory; } });
|
|
343
|
+
var embeddings_factory_2 = require("./models/embeddings-factory");
|
|
344
|
+
Object.defineProperty(exports, "EmbeddingsFactory", { enumerable: true, get: function () { return embeddings_factory_2.EmbeddingsFactory; } });
|
|
345
|
+
var mcp_client_2 = require("./tools/mcp-client");
|
|
346
|
+
Object.defineProperty(exports, "getMcpServerTools", { enumerable: true, get: function () { return mcp_client_2.getMcpServerTools; } });
|
|
347
|
+
var json_schema_to_zod_1 = require("./tools/json-schema-to-zod");
|
|
348
|
+
Object.defineProperty(exports, "convertJsonSchemaToZod", { enumerable: true, get: function () { return json_schema_to_zod_1.convertJsonSchemaToZod; } });
|
|
349
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAGA,q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5B,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,sBAAsB;QAC1B,MAAM,IAAI,CAAC,iBAAiB,EAAE,CAAC;QAE/B,IAAI,CAAC,IAAI,CAAC,MAAM,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,WAAW,EAAE,CAAC;YAC7C,OAAO,EAAE,CAAC;QACZ,CAAC;QACD,OAAO,IAAI,CAAC,MAAM,CAAC,WAAW,CAAC,WAAW,EAAE,CAAC;IAC/C,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,YAAY,CAAC,KAAa,EAAE,MAAc;QAC9C,MAAM,IAAI,CAAC,iBAAiB,EAAE,CAAC;QAE/B,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC;YAChB,MAAM,IAAI,CAAC,MAAM,CAAC,WAAW,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,MAAM,EAAE,CAAC,CAAC;QACvD,CAAC;IACH,CAAC;CACF;AA/YD,0BA+YC;AAED,+BAA+B;AAC/B,gDAA8B;AAC9B,wCAA+C;AAAtC,sGAAA,aAAa,OAAA;AACtB,uCAA4C;AAAnC,oGAAA,WAAW,OAAA;AACpB,wDAAsD;AAA7C,6GAAA,YAAY,OAAA;AACrB,kEAAgE;AAAvD,uHAAA,iBAAiB,OAAA;AAC1B,iDAAuD;AAA9C,+GAAA,iBAAiB,OAAA;AAC1B,iEAAoE;AAA3D,4HAAA,sBAAsB,OAAA"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/memory/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC"}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.MemoryManager = void 0;
|
|
4
|
+
var memory_manager_1 = require("./memory-manager");
|
|
5
|
+
Object.defineProperty(exports, "MemoryManager", { enumerable: true, get: function () { return memory_manager_1.MemoryManager; } });
|
|
6
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/memory/index.ts"],"names":[],"mappings":";;;AAAA,mDAAiD;AAAxC,+GAAA,aAAa,OAAA"}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { BaseChatModel } from '@langchain/core/language_models/chat_models';
|
|
2
|
+
import { BaseChatMemory, BufferWindowMemory, BufferMemory } from 'langchain/memory';
|
|
3
|
+
import { MemoryConfig } from '../types';
|
|
4
|
+
export declare class MemoryManager {
|
|
5
|
+
private static memories;
|
|
6
|
+
/**
|
|
7
|
+
* Create or retrieve a memory instance
|
|
8
|
+
*/
|
|
9
|
+
static getMemory(sessionId: string, options?: MemoryConfig, model?: BaseChatModel): Promise<BaseChatMemory>;
|
|
10
|
+
/**
|
|
11
|
+
* Clear memory for a specific session
|
|
12
|
+
*/
|
|
13
|
+
static clearMemory(sessionId: string, type?: string): Promise<void>;
|
|
14
|
+
/**
|
|
15
|
+
* Clean up memories that haven't been accessed in the last hour
|
|
16
|
+
*/
|
|
17
|
+
private static cleanupStaleMemories;
|
|
18
|
+
/**
|
|
19
|
+
* Create a simple buffer window memory with context length
|
|
20
|
+
*/
|
|
21
|
+
static createBufferWindowMemory(contextWindowLength?: number): BufferWindowMemory | BufferMemory;
|
|
22
|
+
/**
|
|
23
|
+
* Create PostgreSQL memory with configuration
|
|
24
|
+
*/
|
|
25
|
+
static createPostgresMemory(sessionId: string, postgresConfig: any, contextWindowLength?: number): Promise<BaseChatMemory>;
|
|
26
|
+
}
|
|
27
|
+
//# sourceMappingURL=memory-manager.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"memory-manager.d.ts","sourceRoot":"","sources":["../../src/memory/memory-manager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,6CAA6C,CAAC;AAC5E,OAAO,EACL,cAAc,EACd,kBAAkB,EAElB,YAAY,EACb,MAAM,kBAAkB,CAAC;AAG1B,OAAO,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AAExC,qBAAa,aAAa;IACxB,OAAO,CAAC,MAAM,CAAC,QAAQ,CAGT;IAEd;;OAEG;WACU,SAAS,CACpB,SAAS,EAAE,MAAM,EACjB,OAAO,GAAE,YAAiB,EAC1B,KAAK,CAAC,EAAE,aAAa,GACpB,OAAO,CAAC,cAAc,CAAC;IA8F1B;;OAEG;WACU,WAAW,CAAC,SAAS,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAqBzE;;OAEG;IACH,OAAO,CAAC,MAAM,CAAC,oBAAoB;IAWnC;;OAEG;IACH,MAAM,CAAC,wBAAwB,CAC7B,mBAAmB,GAAE,MAAW,GAC/B,kBAAkB,GAAG,YAAY;IAmBpC;;OAEG;WACU,oBAAoB,CAC/B,SAAS,EAAE,MAAM,EACjB,cAAc,EAAE,GAAG,EACnB,mBAAmB,GAAE,MAAW,GAC/B,OAAO,CAAC,cAAc,CAAC;CAyB3B"}
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.MemoryManager = void 0;
|
|
4
|
+
const memory_1 = require("langchain/memory");
|
|
5
|
+
const postgres_1 = require("@langchain/community/stores/message/postgres");
|
|
6
|
+
const pg_1 = require("pg");
|
|
7
|
+
class MemoryManager {
|
|
8
|
+
static memories = new Map();
|
|
9
|
+
/**
|
|
10
|
+
* Create or retrieve a memory instance
|
|
11
|
+
*/
|
|
12
|
+
static async getMemory(sessionId, options = {}, model) {
|
|
13
|
+
// Clean up old memories (older than 1 hour)
|
|
14
|
+
this.cleanupStaleMemories();
|
|
15
|
+
const key = `${sessionId}_${options.type}`;
|
|
16
|
+
let memoryInstance = this.memories.get(key);
|
|
17
|
+
if (memoryInstance) {
|
|
18
|
+
memoryInstance.lastAccessed = new Date();
|
|
19
|
+
return memoryInstance.memory;
|
|
20
|
+
}
|
|
21
|
+
// Create new memory based on type
|
|
22
|
+
let memory;
|
|
23
|
+
switch (options.type) {
|
|
24
|
+
case 'buffer-window':
|
|
25
|
+
memory = new memory_1.BufferWindowMemory({
|
|
26
|
+
k: options.contextWindowLength || 10,
|
|
27
|
+
inputKey: 'input',
|
|
28
|
+
memoryKey: 'chat_history',
|
|
29
|
+
outputKey: 'output',
|
|
30
|
+
returnMessages: true,
|
|
31
|
+
});
|
|
32
|
+
break;
|
|
33
|
+
case 'summary':
|
|
34
|
+
if (!model) {
|
|
35
|
+
throw new Error('Model is required for summary memory');
|
|
36
|
+
}
|
|
37
|
+
memory = new memory_1.ConversationSummaryMemory({
|
|
38
|
+
llm: model,
|
|
39
|
+
inputKey: 'input',
|
|
40
|
+
memoryKey: 'chat_history',
|
|
41
|
+
outputKey: 'output',
|
|
42
|
+
returnMessages: true,
|
|
43
|
+
});
|
|
44
|
+
break;
|
|
45
|
+
case 'postgres':
|
|
46
|
+
if (!options.postgresConfig) {
|
|
47
|
+
throw new Error('PostgreSQL configuration is required for postgres memory');
|
|
48
|
+
}
|
|
49
|
+
// Create PostgreSQL connection pool
|
|
50
|
+
const pool = new pg_1.Pool({
|
|
51
|
+
host: options.postgresConfig.host,
|
|
52
|
+
port: options.postgresConfig.port || 5432,
|
|
53
|
+
database: options.postgresConfig.database,
|
|
54
|
+
user: options.postgresConfig.user,
|
|
55
|
+
password: options.postgresConfig.password,
|
|
56
|
+
ssl: false, // Configure SSL as needed
|
|
57
|
+
});
|
|
58
|
+
// Create PostgreSQL chat message history
|
|
59
|
+
const pgChatHistory = new postgres_1.PostgresChatMessageHistory({
|
|
60
|
+
pool,
|
|
61
|
+
sessionId,
|
|
62
|
+
tableName: options.postgresConfig.tableName || 'chat_messages',
|
|
63
|
+
});
|
|
64
|
+
// Create memory with PostgreSQL history
|
|
65
|
+
memory = new memory_1.BufferWindowMemory({
|
|
66
|
+
k: options.contextWindowLength || 10,
|
|
67
|
+
chatHistory: pgChatHistory,
|
|
68
|
+
inputKey: 'input',
|
|
69
|
+
memoryKey: 'chat_history',
|
|
70
|
+
outputKey: 'output',
|
|
71
|
+
returnMessages: true,
|
|
72
|
+
});
|
|
73
|
+
break;
|
|
74
|
+
default:
|
|
75
|
+
// Default to buffer window memory
|
|
76
|
+
memory = new memory_1.BufferWindowMemory({
|
|
77
|
+
k: options.contextWindowLength || 10,
|
|
78
|
+
inputKey: 'input',
|
|
79
|
+
memoryKey: 'chat_history',
|
|
80
|
+
outputKey: 'output',
|
|
81
|
+
returnMessages: true,
|
|
82
|
+
});
|
|
83
|
+
break;
|
|
84
|
+
}
|
|
85
|
+
this.memories.set(key, {
|
|
86
|
+
memory,
|
|
87
|
+
lastAccessed: new Date(),
|
|
88
|
+
});
|
|
89
|
+
return memory;
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Clear memory for a specific session
|
|
93
|
+
*/
|
|
94
|
+
static async clearMemory(sessionId, type) {
|
|
95
|
+
if (type) {
|
|
96
|
+
const key = `${sessionId}_${type}`;
|
|
97
|
+
const memoryInstance = this.memories.get(key);
|
|
98
|
+
if (memoryInstance) {
|
|
99
|
+
await memoryInstance.memory.clear();
|
|
100
|
+
this.memories.delete(key);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
else {
|
|
104
|
+
// Clear all memories for this session
|
|
105
|
+
const keysToDelete = [];
|
|
106
|
+
for (const [key, memoryInstance] of this.memories.entries()) {
|
|
107
|
+
if (key.startsWith(`${sessionId}_`)) {
|
|
108
|
+
await memoryInstance.memory.clear();
|
|
109
|
+
keysToDelete.push(key);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
keysToDelete.forEach((key) => this.memories.delete(key));
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Clean up memories that haven't been accessed in the last hour
|
|
117
|
+
*/
|
|
118
|
+
static cleanupStaleMemories() {
|
|
119
|
+
const oneHourAgo = new Date(Date.now() - 60 * 60 * 1000);
|
|
120
|
+
for (const [key, memoryInstance] of this.memories.entries()) {
|
|
121
|
+
if (memoryInstance.lastAccessed < oneHourAgo) {
|
|
122
|
+
memoryInstance.memory.clear().catch(console.error);
|
|
123
|
+
this.memories.delete(key);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Create a simple buffer window memory with context length
|
|
129
|
+
*/
|
|
130
|
+
static createBufferWindowMemory(contextWindowLength = 10) {
|
|
131
|
+
if (contextWindowLength === 0) {
|
|
132
|
+
return new memory_1.BufferMemory({
|
|
133
|
+
inputKey: 'input',
|
|
134
|
+
memoryKey: 'chat_history',
|
|
135
|
+
outputKey: 'output',
|
|
136
|
+
returnMessages: true,
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
return new memory_1.BufferWindowMemory({
|
|
140
|
+
k: contextWindowLength,
|
|
141
|
+
inputKey: 'input',
|
|
142
|
+
memoryKey: 'chat_history',
|
|
143
|
+
outputKey: 'output',
|
|
144
|
+
returnMessages: true,
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* Create PostgreSQL memory with configuration
|
|
149
|
+
*/
|
|
150
|
+
static async createPostgresMemory(sessionId, postgresConfig, contextWindowLength = 10) {
|
|
151
|
+
const pool = new pg_1.Pool({
|
|
152
|
+
host: postgresConfig.host,
|
|
153
|
+
port: postgresConfig.port || 5432,
|
|
154
|
+
database: postgresConfig.database,
|
|
155
|
+
user: postgresConfig.user,
|
|
156
|
+
password: postgresConfig.password,
|
|
157
|
+
ssl: false, // Configure SSL as needed
|
|
158
|
+
});
|
|
159
|
+
const pgChatHistory = new postgres_1.PostgresChatMessageHistory({
|
|
160
|
+
pool,
|
|
161
|
+
sessionId,
|
|
162
|
+
tableName: postgresConfig.tableName || 'chat_messages',
|
|
163
|
+
});
|
|
164
|
+
return new memory_1.BufferWindowMemory({
|
|
165
|
+
k: contextWindowLength,
|
|
166
|
+
chatHistory: pgChatHistory,
|
|
167
|
+
inputKey: 'input',
|
|
168
|
+
memoryKey: 'chat_history',
|
|
169
|
+
outputKey: 'output',
|
|
170
|
+
returnMessages: true,
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
exports.MemoryManager = MemoryManager;
|
|
175
|
+
//# sourceMappingURL=memory-manager.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"memory-manager.js","sourceRoot":"","sources":["../../src/memory/memory-manager.ts"],"names":[],"mappings":";;;AACA,6CAK0B;AAC1B,2EAA0F;AAC1F,2BAA0B;AAG1B,MAAa,aAAa;IAChB,MAAM,CAAC,QAAQ,GAGnB,IAAI,GAAG,EAAE,CAAC;IAEd;;OAEG;IACH,MAAM,CAAC,KAAK,CAAC,SAAS,CACpB,SAAiB,EACjB,UAAwB,EAAE,EAC1B,KAAqB;QAErB,4CAA4C;QAC5C,IAAI,CAAC,oBAAoB,EAAE,CAAC;QAE5B,MAAM,GAAG,GAAG,GAAG,SAAS,IAAI,OAAO,CAAC,IAAI,EAAE,CAAC;QAC3C,IAAI,cAAc,GAAG,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QAE5C,IAAI,cAAc,EAAE,CAAC;YACnB,cAAc,CAAC,YAAY,GAAG,IAAI,IAAI,EAAE,CAAC;YACzC,OAAO,cAAc,CAAC,MAAM,CAAC;QAC/B,CAAC;QAED,kCAAkC;QAClC,IAAI,MAAsB,CAAC;QAE3B,QAAQ,OAAO,CAAC,IAAI,EAAE,CAAC;YACrB,KAAK,eAAe;gBAClB,MAAM,GAAG,IAAI,2BAAkB,CAAC;oBAC9B,CAAC,EAAE,OAAO,CAAC,mBAAmB,IAAI,EAAE;oBACpC,QAAQ,EAAE,OAAO;oBACjB,SAAS,EAAE,cAAc;oBACzB,SAAS,EAAE,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cAAmB,EACnB,sBAA8B,EAAE;QAEhC,MAAM,IAAI,GAAG,IAAI,SAAI,CAAC;YACpB,IAAI,EAAE,cAAc,CAAC,IAAI;YACzB,IAAI,EAAE,cAAc,CAAC,IAAI,IAAI,IAAI;YACjC,QAAQ,EAAE,cAAc,CAAC,QAAQ;YACjC,IAAI,EAAE,cAAc,CAAC,IAAI;YACzB,QAAQ,EAAE,cAAc,CAAC,QAAQ;YACjC,GAAG,EAAE,KAAK,EAAE,0BAA0B;SACvC,CAAC,CAAC;QAEH,MAAM,aAAa,GAAG,IAAI,qCAA0B,CAAC;YACnD,IAAI;YACJ,SAAS;YACT,SAAS,EAAE,cAAc,CAAC,SAAS,IAAI,eAAe;SACvD,CAAC,CAAC;QAEH,OAAO,IAAI,2BAAkB,CAAC;YAC5B,CAAC,EAAE,mBAAmB;YACtB,WAAW,EAAE,aAAa;YAC1B,QAAQ,EAAE,OAAO;YACjB,SAAS,EAAE,cAAc;YACzB,SAAS,EAAE,QAAQ;YACnB,cAAc,EAAE,IAAI;SACrB,CAAC,CAAC;IACL,CAAC;;AAxMH,sCAyMC"}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { Embeddings } from '@langchain/core/embeddings';
|
|
2
|
+
import { EmbeddingsConfig } from '../types';
|
|
3
|
+
export declare class EmbeddingsFactory {
|
|
4
|
+
static createEmbeddings(config: EmbeddingsConfig): Promise<Embeddings>;
|
|
5
|
+
}
|
|
6
|
+
//# sourceMappingURL=embeddings-factory.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"embeddings-factory.d.ts","sourceRoot":"","sources":["../../src/models/embeddings-factory.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,4BAA4B,CAAC;AAC7D,OAAO,EAAE,gBAAgB,EAAE,MAAM,UAAU,CAAC;AAE5C,qBAAa,iBAAiB;WACf,gBAAgB,CAAC,MAAM,EAAE,gBAAgB,GAAG,OAAO,CAAC,UAAU,CAAC;CAqD7E"}
|