n8n-nodes-engram 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (154) hide show
  1. package/LICENSE +661 -0
  2. package/README.md +334 -0
  3. package/dist/community/CommunityDetector.d.ts +11 -0
  4. package/dist/community/CommunityDetector.js +126 -0
  5. package/dist/community/CommunityDetector.js.map +1 -0
  6. package/dist/community/CommunitySummarizer.d.ts +8 -0
  7. package/dist/community/CommunitySummarizer.js +56 -0
  8. package/dist/community/CommunitySummarizer.js.map +1 -0
  9. package/dist/community/index.d.ts +2 -0
  10. package/dist/community/index.js +8 -0
  11. package/dist/community/index.js.map +1 -0
  12. package/dist/credentials/EngramExtractionApi.credentials.d.ts +8 -0
  13. package/dist/credentials/EngramExtractionApi.credentials.js +41 -0
  14. package/dist/credentials/EngramExtractionApi.credentials.js.map +1 -0
  15. package/dist/credentials/EngramNeo4jApi.credentials.d.ts +8 -0
  16. package/dist/credentials/EngramNeo4jApi.credentials.js +59 -0
  17. package/dist/credentials/EngramNeo4jApi.credentials.js.map +1 -0
  18. package/dist/descriptions.d.ts +4 -0
  19. package/dist/descriptions.js +41 -0
  20. package/dist/descriptions.js.map +1 -0
  21. package/dist/embeddings/EmbeddingService.d.ts +24 -0
  22. package/dist/embeddings/EmbeddingService.js +64 -0
  23. package/dist/embeddings/EmbeddingService.js.map +1 -0
  24. package/dist/embeddings/cosine.d.ts +1 -0
  25. package/dist/embeddings/cosine.js +21 -0
  26. package/dist/embeddings/cosine.js.map +1 -0
  27. package/dist/embeddings/index.d.ts +2 -0
  28. package/dist/embeddings/index.js +8 -0
  29. package/dist/embeddings/index.js.map +1 -0
  30. package/dist/extraction/ContradictionDetector.d.ts +11 -0
  31. package/dist/extraction/ContradictionDetector.js +35 -0
  32. package/dist/extraction/ContradictionDetector.js.map +1 -0
  33. package/dist/extraction/EntityDeduplicator.d.ts +17 -0
  34. package/dist/extraction/EntityDeduplicator.js +39 -0
  35. package/dist/extraction/EntityDeduplicator.js.map +1 -0
  36. package/dist/extraction/EntityExtractor.d.ts +11 -0
  37. package/dist/extraction/EntityExtractor.js +33 -0
  38. package/dist/extraction/EntityExtractor.js.map +1 -0
  39. package/dist/extraction/ExtractionPipeline.d.ts +24 -0
  40. package/dist/extraction/ExtractionPipeline.js +126 -0
  41. package/dist/extraction/ExtractionPipeline.js.map +1 -0
  42. package/dist/extraction/LlmClient.d.ts +36 -0
  43. package/dist/extraction/LlmClient.js +73 -0
  44. package/dist/extraction/LlmClient.js.map +1 -0
  45. package/dist/extraction/RelationshipExtractor.d.ts +12 -0
  46. package/dist/extraction/RelationshipExtractor.js +38 -0
  47. package/dist/extraction/RelationshipExtractor.js.map +1 -0
  48. package/dist/extraction/index.d.ts +6 -0
  49. package/dist/extraction/index.js +16 -0
  50. package/dist/extraction/index.js.map +1 -0
  51. package/dist/extraction/prompts.d.ts +16 -0
  52. package/dist/extraction/prompts.js +101 -0
  53. package/dist/extraction/prompts.js.map +1 -0
  54. package/dist/memory/EngramChatMemory.d.ts +42 -0
  55. package/dist/memory/EngramChatMemory.js +162 -0
  56. package/dist/memory/EngramChatMemory.js.map +1 -0
  57. package/dist/memory/EngramChatMessageHistory.d.ts +22 -0
  58. package/dist/memory/EngramChatMessageHistory.js +72 -0
  59. package/dist/memory/EngramChatMessageHistory.js.map +1 -0
  60. package/dist/memory/index.d.ts +2 -0
  61. package/dist/memory/index.js +8 -0
  62. package/dist/memory/index.js.map +1 -0
  63. package/dist/nodes/EngramAdmin/EngramAdmin.node.d.ts +5 -0
  64. package/dist/nodes/EngramAdmin/EngramAdmin.node.js +798 -0
  65. package/dist/nodes/EngramAdmin/EngramAdmin.node.js.map +1 -0
  66. package/dist/nodes/EngramAdmin/engram-admin.png +0 -0
  67. package/dist/nodes/EngramExplorer/EngramExplorer.node.d.ts +5 -0
  68. package/dist/nodes/EngramExplorer/EngramExplorer.node.js +932 -0
  69. package/dist/nodes/EngramExplorer/EngramExplorer.node.js.map +1 -0
  70. package/dist/nodes/EngramExplorer/engram-explorer.png +0 -0
  71. package/dist/nodes/EngramMemory/EngramMemory.node.d.ts +10 -0
  72. package/dist/nodes/EngramMemory/EngramMemory.node.js +462 -0
  73. package/dist/nodes/EngramMemory/EngramMemory.node.js.map +1 -0
  74. package/dist/nodes/EngramMemory/engram.png +0 -0
  75. package/dist/nodes/EngramTrigger/EngramTrigger.node.d.ts +5 -0
  76. package/dist/nodes/EngramTrigger/EngramTrigger.node.js +146 -0
  77. package/dist/nodes/EngramTrigger/EngramTrigger.node.js.map +1 -0
  78. package/dist/nodes/EngramTrigger/engram-trigger.png +0 -0
  79. package/dist/schemas/Community.schema.d.ts +656 -0
  80. package/dist/schemas/Community.schema.js +26 -0
  81. package/dist/schemas/Community.schema.js.map +1 -0
  82. package/dist/schemas/EntityEdge.schema.d.ts +86 -0
  83. package/dist/schemas/EntityEdge.schema.js +34 -0
  84. package/dist/schemas/EntityEdge.schema.js.map +1 -0
  85. package/dist/schemas/EntityNode.schema.d.ts +56 -0
  86. package/dist/schemas/EntityNode.schema.js +24 -0
  87. package/dist/schemas/EntityNode.schema.js.map +1 -0
  88. package/dist/schemas/EpisodicNode.schema.d.ts +53 -0
  89. package/dist/schemas/EpisodicNode.schema.js +23 -0
  90. package/dist/schemas/EpisodicNode.schema.js.map +1 -0
  91. package/dist/schemas/GraphData.schema.d.ts +220 -0
  92. package/dist/schemas/GraphData.schema.js +25 -0
  93. package/dist/schemas/GraphData.schema.js.map +1 -0
  94. package/dist/schemas/index.d.ts +5 -0
  95. package/dist/schemas/index.js +20 -0
  96. package/dist/schemas/index.js.map +1 -0
  97. package/dist/search/HybridSearchEngine.d.ts +31 -0
  98. package/dist/search/HybridSearchEngine.js +140 -0
  99. package/dist/search/HybridSearchEngine.js.map +1 -0
  100. package/dist/search/MinisearchProvider.d.ts +20 -0
  101. package/dist/search/MinisearchProvider.js +77 -0
  102. package/dist/search/MinisearchProvider.js.map +1 -0
  103. package/dist/search/TextSearchProvider.d.ts +20 -0
  104. package/dist/search/TextSearchProvider.js +3 -0
  105. package/dist/search/TextSearchProvider.js.map +1 -0
  106. package/dist/search/index.d.ts +3 -0
  107. package/dist/search/index.js +8 -0
  108. package/dist/search/index.js.map +1 -0
  109. package/dist/storage/GraphologyStorage.d.ts +42 -0
  110. package/dist/storage/GraphologyStorage.js +665 -0
  111. package/dist/storage/GraphologyStorage.js.map +1 -0
  112. package/dist/storage/IGraphStorage.d.ts +64 -0
  113. package/dist/storage/IGraphStorage.js +3 -0
  114. package/dist/storage/IGraphStorage.js.map +1 -0
  115. package/dist/storage/Neo4jStorage.d.ts +45 -0
  116. package/dist/storage/Neo4jStorage.js +949 -0
  117. package/dist/storage/Neo4jStorage.js.map +1 -0
  118. package/dist/storage/StorageFactory.d.ts +14 -0
  119. package/dist/storage/StorageFactory.js +26 -0
  120. package/dist/storage/StorageFactory.js.map +1 -0
  121. package/dist/storage/index.d.ts +3 -0
  122. package/dist/storage/index.js +8 -0
  123. package/dist/storage/index.js.map +1 -0
  124. package/dist/traversal/EpisodeTraverser.d.ts +10 -0
  125. package/dist/traversal/EpisodeTraverser.js +46 -0
  126. package/dist/traversal/EpisodeTraverser.js.map +1 -0
  127. package/dist/traversal/GraphTraverser.d.ts +24 -0
  128. package/dist/traversal/GraphTraverser.js +89 -0
  129. package/dist/traversal/GraphTraverser.js.map +1 -0
  130. package/dist/traversal/index.d.ts +2 -0
  131. package/dist/traversal/index.js +8 -0
  132. package/dist/traversal/index.js.map +1 -0
  133. package/dist/utils/descriptions.d.ts +6 -0
  134. package/dist/utils/descriptions.js +95 -0
  135. package/dist/utils/descriptions.js.map +1 -0
  136. package/dist/utils/helpers.d.ts +23 -0
  137. package/dist/utils/helpers.js +146 -0
  138. package/dist/utils/helpers.js.map +1 -0
  139. package/dist/utils/logWrapper.d.ts +26 -0
  140. package/dist/utils/logWrapper.js +300 -0
  141. package/dist/utils/logWrapper.js.map +1 -0
  142. package/dist/utils/sharedFields.d.ts +6 -0
  143. package/dist/utils/sharedFields.js +121 -0
  144. package/dist/utils/sharedFields.js.map +1 -0
  145. package/dist/utils/temporal.d.ts +22 -0
  146. package/dist/utils/temporal.js +44 -0
  147. package/dist/utils/temporal.js.map +1 -0
  148. package/dist/utils/tracing.d.ts +7 -0
  149. package/dist/utils/tracing.js +20 -0
  150. package/dist/utils/tracing.js.map +1 -0
  151. package/dist/utils/uuid.d.ts +2 -0
  152. package/dist/utils/uuid.js +13 -0
  153. package/dist/utils/uuid.js.map +1 -0
  154. package/package.json +108 -0
@@ -0,0 +1,73 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.LlmClient = void 0;
4
+ class LlmClient {
5
+ constructor(config) {
6
+ var _a;
7
+ this.apiKey = config.apiKey;
8
+ this.baseUrl = config.baseUrl.replace(/\/$/, '');
9
+ this.model = config.model;
10
+ this.timeoutMs = (_a = config.timeoutMs) !== null && _a !== void 0 ? _a : 30000;
11
+ }
12
+ async chat(messages, options) {
13
+ var _a, _b, _c, _d;
14
+ const url = `${this.baseUrl}/chat/completions`;
15
+ const body = {
16
+ model: this.model,
17
+ messages,
18
+ temperature: (_a = options === null || options === void 0 ? void 0 : options.temperature) !== null && _a !== void 0 ? _a : 0.0,
19
+ };
20
+ if (options === null || options === void 0 ? void 0 : options.maxTokens) {
21
+ body.max_tokens = options.maxTokens;
22
+ }
23
+ if (options === null || options === void 0 ? void 0 : options.responseFormat) {
24
+ body.response_format = options.responseFormat;
25
+ }
26
+ const controller = new AbortController();
27
+ const timeout = setTimeout(() => controller.abort(), this.timeoutMs);
28
+ let response;
29
+ try {
30
+ response = await fetch(url, {
31
+ method: 'POST',
32
+ headers: {
33
+ 'Content-Type': 'application/json',
34
+ Authorization: `Bearer ${this.apiKey}`,
35
+ },
36
+ body: JSON.stringify(body),
37
+ signal: controller.signal,
38
+ });
39
+ }
40
+ catch (error) {
41
+ if (error instanceof Error && error.name === 'AbortError') {
42
+ throw new Error(`LLM API request timed out after ${this.timeoutMs}ms`);
43
+ }
44
+ throw error;
45
+ }
46
+ finally {
47
+ clearTimeout(timeout);
48
+ }
49
+ if (!response.ok) {
50
+ const errorText = await response.text();
51
+ throw new Error(`LLM API error (${response.status}): ${errorText}`);
52
+ }
53
+ const data = (await response.json());
54
+ return {
55
+ content: (_d = (_c = (_b = data.choices[0]) === null || _b === void 0 ? void 0 : _b.message) === null || _c === void 0 ? void 0 : _c.content) !== null && _d !== void 0 ? _d : '',
56
+ usage: data.usage,
57
+ };
58
+ }
59
+ async chatJson(messages, options) {
60
+ const response = await this.chat(messages, {
61
+ ...options,
62
+ responseFormat: { type: 'json_object' },
63
+ });
64
+ try {
65
+ return JSON.parse(response.content);
66
+ }
67
+ catch {
68
+ throw new Error(`Failed to parse LLM JSON response: ${response.content.slice(0, 200)}`);
69
+ }
70
+ }
71
+ }
72
+ exports.LlmClient = LlmClient;
73
+ //# sourceMappingURL=LlmClient.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"LlmClient.js","sourceRoot":"","sources":["../../src/extraction/LlmClient.ts"],"names":[],"mappings":";;;AA2BA,MAAa,SAAS;IAMpB,YAAY,MAAuB;;QACjC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC;QAC5B,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;QACjD,IAAI,CAAC,KAAK,GAAG,MAAM,CAAC,KAAK,CAAC;QAC1B,IAAI,CAAC,SAAS,GAAG,MAAA,MAAM,CAAC,SAAS,mCAAI,KAAM,CAAC;IAC9C,CAAC;IAED,KAAK,CAAC,IAAI,CACR,QAAsB,EACtB,OAIC;;QAED,MAAM,GAAG,GAAG,GAAG,IAAI,CAAC,OAAO,mBAAmB,CAAC;QAE/C,MAAM,IAAI,GAA4B;YACpC,KAAK,EAAE,IAAI,CAAC,KAAK;YACjB,QAAQ;YACR,WAAW,EAAE,MAAA,OAAO,aAAP,OAA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AM,IAAI,KAAK,CAAC,kBAAkB,QAAQ,CAAC,MAAM,MAAM,SAAS,EAAE,CAAC,CAAC;QACtE,CAAC;QAED,MAAM,IAAI,GAAG,CAAC,MAAM,QAAQ,CAAC,IAAI,EAAE,CAGlC,CAAC;QAEF,OAAO;YACL,OAAO,EAAE,MAAA,MAAA,MAAA,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,0CAAE,OAAO,0CAAE,OAAO,mCAAI,EAAE;YAChD,KAAK,EAAE,IAAI,CAAC,KAAK;SAClB,CAAC;IACJ,CAAC;IAED,KAAK,CAAC,QAAQ,CACZ,QAAsB,EACtB,OAAsD;QAEtD,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE;YACzC,GAAG,OAAO;YACV,cAAc,EAAE,EAAE,IAAI,EAAE,aAAa,EAAE;SACxC,CAAC,CAAC;QAEH,IAAI,CAAC;YACH,OAAO,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,OAAO,CAAM,CAAC;QAC3C,CAAC;QAAC,MAAM,CAAC;YACP,MAAM,IAAI,KAAK,CAAC,sCAAsC,QAAQ,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,EAAE,CAAC,CAAC;QAC1F,CAAC;IACH,CAAC;CACF;AA3FD,8BA2FC"}
@@ -0,0 +1,12 @@
1
+ import type { LlmClient } from './LlmClient';
2
+ export interface ExtractedRelationship {
3
+ source_entity: string;
4
+ target_entity: string;
5
+ name: string;
6
+ fact: string;
7
+ }
8
+ export declare class RelationshipExtractor {
9
+ private llm;
10
+ constructor(llm: LlmClient);
11
+ extract(humanMessage: string, aiMessage: string, entityNames: string[]): Promise<ExtractedRelationship[]>;
12
+ }
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RelationshipExtractor = void 0;
4
+ const prompts_1 = require("./prompts");
5
+ class RelationshipExtractor {
6
+ constructor(llm) {
7
+ this.llm = llm;
8
+ }
9
+ async extract(humanMessage, aiMessage, entityNames) {
10
+ if (entityNames.length < 2)
11
+ return [];
12
+ try {
13
+ const result = await this.llm.chatJson([
14
+ { role: 'system', content: prompts_1.RELATIONSHIP_EXTRACTION_SYSTEM },
15
+ {
16
+ role: 'user',
17
+ content: (0, prompts_1.relationshipExtractionUser)(humanMessage, aiMessage, entityNames),
18
+ },
19
+ ]);
20
+ if (!result.relationships || !Array.isArray(result.relationships)) {
21
+ return [];
22
+ }
23
+ const entitySet = new Set(entityNames.map((n) => n.toLowerCase()));
24
+ return result.relationships.filter((r) => typeof r.source_entity === 'string' &&
25
+ typeof r.target_entity === 'string' &&
26
+ typeof r.name === 'string' &&
27
+ typeof r.fact === 'string' &&
28
+ entitySet.has(r.source_entity.toLowerCase()) &&
29
+ entitySet.has(r.target_entity.toLowerCase()));
30
+ }
31
+ catch (error) {
32
+ console.warn('Engram: Relationship extraction failed:', error.message);
33
+ return [];
34
+ }
35
+ }
36
+ }
37
+ exports.RelationshipExtractor = RelationshipExtractor;
38
+ //# sourceMappingURL=RelationshipExtractor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"RelationshipExtractor.js","sourceRoot":"","sources":["../../src/extraction/RelationshipExtractor.ts"],"names":[],"mappings":";;;AACA,uCAAuF;AAavF,MAAa,qBAAqB;IAGhC,YAAY,GAAc;QACxB,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC;IACjB,CAAC;IAED,KAAK,CAAC,OAAO,CACX,YAAoB,EACpB,SAAiB,EACjB,WAAqB;QAErB,IAAI,WAAW,CAAC,MAAM,GAAG,CAAC;YAAE,OAAO,EAAE,CAAC;QAEtC,IAAI,CAAC;YACH,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,GAAG,CAAC,QAAQ,CAA+B;gBACnE,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,wCAA8B,EAAE;gBAC3D;oBACE,IAAI,EAAE,MAAM;oBACZ,OAAO,EAAE,IAAA,oCAA0B,EAAC,YAAY,EAAE,SAAS,EAAE,WAAW,CAAC;iBAC1E;aACF,CAAC,CAAC;YAEH,IAAI,CAAC,MAAM,CAAC,aAAa,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,aAAa,CAAC,EAAE,CAAC;gBAClE,OAAO,EAAE,CAAC;YACZ,CAAC;YAGD,MAAM,SAAS,GAAG,IAAI,GAAG,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC;YACnE,OAAO,MAAM,CAAC,aAAa,CAAC,MAAM,CAChC,CAAC,CAAC,EAAE,EAAE,CACJ,OAAO,CAAC,CAAC,aAAa,KAAK,QAAQ;gBACnC,OAAO,CAAC,CAAC,aAAa,KAAK,QAAQ;gBACnC,OAAO,CAAC,CAAC,IAAI,KAAK,QAAQ;gBAC1B,OAAO,CAAC,CAAC,IAAI,KAAK,QAAQ;gBAC1B,SAAS,CAAC,GAAG,CAAC,CAAC,CAAC,aAAa,CAAC,WAAW,EAAE,CAAC;gBAC5C,SAAS,CAAC,GAAG,CAAC,CAAC,CAAC,aAAa,CAAC,WAAW,EAAE,CAAC,CAC/C,CAAC;QACJ,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,IAAI,CAAC,yCAAyC,EAAG,KAAe,CAAC,OAAO,CAAC,CAAC;YAClF,OAAO,EAAE,CAAC;QACZ,CAAC;IACH,CAAC;CACF;AA3CD,sDA2CC"}
@@ -0,0 +1,6 @@
1
+ export { LlmClient, type LlmClientConfig } from './LlmClient';
2
+ export { EntityExtractor, type ExtractedEntity } from './EntityExtractor';
3
+ export { RelationshipExtractor, type ExtractedRelationship } from './RelationshipExtractor';
4
+ export { EntityDeduplicator } from './EntityDeduplicator';
5
+ export { ContradictionDetector, type ContradictionResolution } from './ContradictionDetector';
6
+ export { ExtractionPipeline, type ExtractionPipelineConfig } from './ExtractionPipeline';
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ExtractionPipeline = exports.ContradictionDetector = exports.EntityDeduplicator = exports.RelationshipExtractor = exports.EntityExtractor = exports.LlmClient = void 0;
4
+ var LlmClient_1 = require("./LlmClient");
5
+ Object.defineProperty(exports, "LlmClient", { enumerable: true, get: function () { return LlmClient_1.LlmClient; } });
6
+ var EntityExtractor_1 = require("./EntityExtractor");
7
+ Object.defineProperty(exports, "EntityExtractor", { enumerable: true, get: function () { return EntityExtractor_1.EntityExtractor; } });
8
+ var RelationshipExtractor_1 = require("./RelationshipExtractor");
9
+ Object.defineProperty(exports, "RelationshipExtractor", { enumerable: true, get: function () { return RelationshipExtractor_1.RelationshipExtractor; } });
10
+ var EntityDeduplicator_1 = require("./EntityDeduplicator");
11
+ Object.defineProperty(exports, "EntityDeduplicator", { enumerable: true, get: function () { return EntityDeduplicator_1.EntityDeduplicator; } });
12
+ var ContradictionDetector_1 = require("./ContradictionDetector");
13
+ Object.defineProperty(exports, "ContradictionDetector", { enumerable: true, get: function () { return ContradictionDetector_1.ContradictionDetector; } });
14
+ var ExtractionPipeline_1 = require("./ExtractionPipeline");
15
+ Object.defineProperty(exports, "ExtractionPipeline", { enumerable: true, get: function () { return ExtractionPipeline_1.ExtractionPipeline; } });
16
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/extraction/index.ts"],"names":[],"mappings":";;;AAAA,yCAA8D;AAArD,sGAAA,SAAS,OAAA;AAClB,qDAA0E;AAAjE,kHAAA,eAAe,OAAA;AACxB,iEAA4F;AAAnF,8HAAA,qBAAqB,OAAA;AAC9B,2DAA0D;AAAjD,wHAAA,kBAAkB,OAAA;AAC3B,iEAA8F;AAArF,8HAAA,qBAAqB,OAAA;AAC9B,2DAAyF;AAAhF,wHAAA,kBAAkB,OAAA"}
@@ -0,0 +1,16 @@
1
+ export declare const ENTITY_EXTRACTION_SYSTEM: string;
2
+ export declare function entityExtractionUser(humanMessage: string, aiMessage: string, entityTypes: string[], existingEntities: string[]): string;
3
+ export declare const RELATIONSHIP_EXTRACTION_SYSTEM: string;
4
+ export declare function relationshipExtractionUser(humanMessage: string, aiMessage: string, entities: string[]): string;
5
+ export declare const DEDUPLICATION_SYSTEM: string;
6
+ export declare function deduplicationUser(entity1: {
7
+ name: string;
8
+ summary: string;
9
+ entity_type: string;
10
+ }, entity2: {
11
+ name: string;
12
+ summary: string;
13
+ entity_type: string;
14
+ }): string;
15
+ export declare const CONTRADICTION_SYSTEM: string;
16
+ export declare function contradictionUser(existingFact: string, newFact: string, sourceEntity: string, targetEntity: string): string;
@@ -0,0 +1,101 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CONTRADICTION_SYSTEM = exports.DEDUPLICATION_SYSTEM = exports.RELATIONSHIP_EXTRACTION_SYSTEM = exports.ENTITY_EXTRACTION_SYSTEM = void 0;
4
+ exports.entityExtractionUser = entityExtractionUser;
5
+ exports.relationshipExtractionUser = relationshipExtractionUser;
6
+ exports.deduplicationUser = deduplicationUser;
7
+ exports.contradictionUser = contradictionUser;
8
+ exports.ENTITY_EXTRACTION_SYSTEM = [
9
+ 'You are an entity extraction system. Extract entities from the conversation.',
10
+ '',
11
+ 'Rules:',
12
+ '- Extract real-world entities mentioned: people, organizations, locations, concepts, events, products, etc.',
13
+ '- Each entity needs: name (string), entity_type (string), summary (one sentence description)',
14
+ '- Use consistent naming: proper nouns as-is, concepts in lowercase',
15
+ '- entity_type should be one of the allowed types provided',
16
+ '- Return ONLY valid JSON, no extra text',
17
+ '',
18
+ 'Output format:',
19
+ '{"entities": [{"name": "Alice", "entity_type": "person", "summary": "A software engineer"}]}',
20
+ ].join('\n');
21
+ function entityExtractionUser(humanMessage, aiMessage, entityTypes, existingEntities) {
22
+ const typesStr = entityTypes.join(', ');
23
+ const parts = [
24
+ 'Extract entities from this conversation turn.',
25
+ '',
26
+ 'Allowed entity types: ' + typesStr,
27
+ ];
28
+ if (existingEntities.length > 0) {
29
+ parts.push('Already known entities (avoid duplicates): ' + existingEntities.join(', '));
30
+ }
31
+ parts.push('', 'Human: ' + humanMessage, 'AI: ' + aiMessage);
32
+ return parts.join('\n');
33
+ }
34
+ exports.RELATIONSHIP_EXTRACTION_SYSTEM = [
35
+ 'You are a relationship extraction system. Extract facts and relationships between entities.',
36
+ '',
37
+ 'Rules:',
38
+ '- Extract relationships as factual statements connecting two entities',
39
+ '- source_entity and target_entity must be exact entity names from the provided list',
40
+ '- name should be SCREAMING_SNAKE_CASE (e.g., WORKS_AT, LIVES_IN, KNOWS)',
41
+ '- fact should be a natural language statement of the relationship',
42
+ '- Only extract relationships where both entities exist in the provided list',
43
+ '- Return ONLY valid JSON, no extra text',
44
+ '',
45
+ 'Output format:',
46
+ '{"relationships": [{"source_entity": "Alice", "target_entity": "Acme Corp", "name": "WORKS_AT", "fact": "Alice works at Acme Corp as a senior engineer"}]}',
47
+ ].join('\n');
48
+ function relationshipExtractionUser(humanMessage, aiMessage, entities) {
49
+ const parts = [
50
+ 'Extract relationships from this conversation turn.',
51
+ '',
52
+ 'Available entities: ' + entities.join(', '),
53
+ '',
54
+ 'Human: ' + humanMessage,
55
+ 'AI: ' + aiMessage,
56
+ ];
57
+ return parts.join('\n');
58
+ }
59
+ exports.DEDUPLICATION_SYSTEM = [
60
+ 'You are an entity deduplication system. Determine if two entities refer to the same real-world thing.',
61
+ '',
62
+ 'Rules:',
63
+ '- Consider name variations (Bob/Robert, NYC/New York City)',
64
+ '- Consider context clues from summaries',
65
+ '- Return ONLY valid JSON',
66
+ '',
67
+ 'Output format:',
68
+ '{"is_duplicate": true, "merged_summary": "Combined summary of both entities"}',
69
+ ].join('\n');
70
+ function deduplicationUser(entity1, entity2) {
71
+ const parts = [
72
+ 'Are these the same entity?',
73
+ '',
74
+ 'Entity 1: ' + entity1.name + ' (' + entity1.entity_type + ') - ' + entity1.summary,
75
+ 'Entity 2: ' + entity2.name + ' (' + entity2.entity_type + ') - ' + entity2.summary,
76
+ ];
77
+ return parts.join('\n');
78
+ }
79
+ exports.CONTRADICTION_SYSTEM = [
80
+ 'You are a contradiction detection system. Determine if a new fact contradicts an existing fact.',
81
+ '',
82
+ 'Rules:',
83
+ '- A contradiction means the new fact makes the old fact no longer true',
84
+ '- Example: "Alice lives in London" contradicts "Alice lives in Tokyo" (can only live in one place)',
85
+ '- Example: "Alice knows Python" does NOT contradict "Alice knows JavaScript" (can know both)',
86
+ '- Return ONLY valid JSON',
87
+ '',
88
+ 'Output format:',
89
+ '{"is_contradiction": true, "explanation": "The new fact about living location replaces the old one"}',
90
+ ].join('\n');
91
+ function contradictionUser(existingFact, newFact, sourceEntity, targetEntity) {
92
+ const parts = [
93
+ 'Does the new fact contradict the existing fact?',
94
+ '',
95
+ 'Entities: ' + sourceEntity + ' -> ' + targetEntity,
96
+ 'Existing fact: ' + existingFact,
97
+ 'New fact: ' + newFact,
98
+ ];
99
+ return parts.join('\n');
100
+ }
101
+ //# sourceMappingURL=prompts.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prompts.js","sourceRoot":"","sources":["../../src/extraction/prompts.ts"],"names":[],"mappings":";;;AAmBA,oDAmBC;AAiBD,gEAcC;AAcD,8CAWC;AAeD,8CAcC;AAtHY,QAAA,wBAAwB,GAAG;IACtC,8EAA8E;IAC9E,EAAE;IACF,QAAQ;IACR,6GAA6G;IAC7G,8FAA8F;IAC9F,oEAAoE;IACpE,2DAA2D;IAC3D,yCAAyC;IACzC,EAAE;IACF,gBAAgB;IAChB,8FAA8F;CAC/F,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAEb,SAAgB,oBAAoB,CAClC,YAAoB,EACpB,SAAiB,EACjB,WAAqB,EACrB,gBAA0B;IAE1B,MAAM,QAAQ,GAAG,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACxC,MAAM,KAAK,GAAG;QACZ,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YAAY,GAAG,OAAO,CAAC,IAAI,GAAG,IAAI,GAAG,OAAO,CAAC,WAAW,GAAG,MAAM,GAAG,OAAO,CAAC,OAAO;QACnF,YAAY,GAAG,OAAO,CAAC,IAAI,GAAG,IAAI,GAAG,OAAO,CAAC,WAAW,GAAG,MAAM,GAAG,OAAO,CAAC,OAAO;KACpF,CAAC;IACF,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAC1B,CAAC;AAEY,QAAA,oBAAoB,GAAG;IAClC,iGAAiG;IACjG,EAAE;IACF,QAAQ;IACR,wEAAwE;IACxE,oGAAoG;IACpG,8FAA8F;IAC9F,0BAA0B;IAC1B,EAAE;IACF,gBAAgB;IAChB,sGAAsG;CACvG,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAEb,SAAgB,iBAAiB,CAC/B,YAAoB,EACpB,OAAe,EACf,YAAoB,EACpB,YAAoB;IAEpB,MAAM,KAAK,GAAG;QACZ,iDAAiD;QACjD,EAAE;QACF,YAAY,GAAG,YAAY,GAAG,MAAM,GAAG,YAAY;QACnD,iBAAiB,GAAG,YAAY;QAChC,YAAY,GAAG,OAAO;KACvB,CAAC;IACF,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAC1B,CAAC"}
@@ -0,0 +1,42 @@
1
+ import { BaseChatMemory, type BaseChatMemoryInput } from 'langchain/memory';
2
+ import type { InputValues, MemoryVariables, OutputValues } from '@langchain/core/memory';
3
+ import type { IGraphStorage } from '../storage/IGraphStorage';
4
+ import { type EmbeddingConfig } from '../embeddings';
5
+ import type { LlmClientConfig } from '../extraction/LlmClient';
6
+ export interface EngramChatMemoryInput extends BaseChatMemoryInput {
7
+ storage: IGraphStorage;
8
+ groupId: string;
9
+ memoryKey?: string;
10
+ contextWindow?: number;
11
+ maxFactsPerQuery?: number;
12
+ minRelevanceScore?: number;
13
+ enableExtraction?: boolean;
14
+ llmConfig?: LlmClientConfig;
15
+ entityTypes?: string[];
16
+ embeddingConfig?: EmbeddingConfig;
17
+ enableTraversal?: boolean;
18
+ traversalHops?: number;
19
+ }
20
+ export declare class EngramChatMemory extends BaseChatMemory {
21
+ storage: IGraphStorage;
22
+ groupId: string;
23
+ memoryKey: string;
24
+ contextWindow: number;
25
+ maxFactsPerQuery: number;
26
+ minRelevanceScore: number;
27
+ enableExtraction: boolean;
28
+ private extractionPipeline;
29
+ private searchEngine;
30
+ private engramHistory;
31
+ private enableTraversal;
32
+ private traversalHops;
33
+ constructor(fields: EngramChatMemoryInput);
34
+ get memoryKeys(): string[];
35
+ loadMemoryVariables(values: InputValues): Promise<MemoryVariables>;
36
+ saveContext(inputValues: InputValues, outputValues: OutputValues): Promise<void>;
37
+ clear(): Promise<void>;
38
+ private getRelevantFacts;
39
+ private extractInputText;
40
+ private runExtraction;
41
+ private extractOutputText;
42
+ }
@@ -0,0 +1,162 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.EngramChatMemory = void 0;
4
+ const memory_1 = require("langchain/memory");
5
+ const messages_1 = require("@langchain/core/messages");
6
+ const EngramChatMessageHistory_1 = require("./EngramChatMessageHistory");
7
+ const ExtractionPipeline_1 = require("../extraction/ExtractionPipeline");
8
+ const HybridSearchEngine_1 = require("../search/HybridSearchEngine");
9
+ const embeddings_1 = require("../embeddings");
10
+ const GraphTraverser_1 = require("../traversal/GraphTraverser");
11
+ class EngramChatMemory extends memory_1.BaseChatMemory {
12
+ constructor(fields) {
13
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
14
+ const history = new EngramChatMessageHistory_1.EngramChatMessageHistory({
15
+ storage: fields.storage,
16
+ groupId: fields.groupId,
17
+ contextWindow: (_a = fields.contextWindow) !== null && _a !== void 0 ? _a : 10,
18
+ });
19
+ super({
20
+ chatHistory: history,
21
+ returnMessages: (_b = fields.returnMessages) !== null && _b !== void 0 ? _b : true,
22
+ inputKey: (_c = fields.inputKey) !== null && _c !== void 0 ? _c : 'input',
23
+ outputKey: (_d = fields.outputKey) !== null && _d !== void 0 ? _d : 'output',
24
+ });
25
+ this.extractionPipeline = null;
26
+ this.storage = fields.storage;
27
+ this.groupId = fields.groupId;
28
+ this.memoryKey = (_e = fields.memoryKey) !== null && _e !== void 0 ? _e : 'chat_history';
29
+ this.contextWindow = (_f = fields.contextWindow) !== null && _f !== void 0 ? _f : 10;
30
+ this.maxFactsPerQuery = (_g = fields.maxFactsPerQuery) !== null && _g !== void 0 ? _g : 10;
31
+ this.minRelevanceScore = (_h = fields.minRelevanceScore) !== null && _h !== void 0 ? _h : 0.5;
32
+ this.enableExtraction = (_j = fields.enableExtraction) !== null && _j !== void 0 ? _j : false;
33
+ this.engramHistory = history;
34
+ this.enableTraversal = (_k = fields.enableTraversal) !== null && _k !== void 0 ? _k : false;
35
+ this.traversalHops = (_l = fields.traversalHops) !== null && _l !== void 0 ? _l : 1;
36
+ const embeddingService = fields.embeddingConfig
37
+ ? new embeddings_1.EmbeddingService(fields.embeddingConfig)
38
+ : undefined;
39
+ this.searchEngine = new HybridSearchEngine_1.HybridSearchEngine(fields.storage, embeddingService);
40
+ if (this.enableExtraction && fields.llmConfig) {
41
+ this.extractionPipeline = new ExtractionPipeline_1.ExtractionPipeline(fields.storage, {
42
+ llmConfig: fields.llmConfig,
43
+ entityTypes: (_m = fields.entityTypes) !== null && _m !== void 0 ? _m : [
44
+ 'person',
45
+ 'organization',
46
+ 'location',
47
+ 'concept',
48
+ 'event',
49
+ ],
50
+ groupId: fields.groupId,
51
+ embeddingConfig: fields.embeddingConfig,
52
+ });
53
+ }
54
+ }
55
+ get memoryKeys() {
56
+ return [this.memoryKey];
57
+ }
58
+ async loadMemoryVariables(values) {
59
+ const messages = await this.chatHistory.getMessages();
60
+ const currentInput = this.extractInputText(values);
61
+ const factMessages = await this.getRelevantFacts(currentInput);
62
+ const allMessages = [...factMessages, ...messages];
63
+ if (this.returnMessages) {
64
+ return { [this.memoryKey]: allMessages };
65
+ }
66
+ const formatted = allMessages
67
+ .map((m) => {
68
+ const type = m._getType();
69
+ const prefix = type === 'human' ? 'Human' : type === 'ai' ? 'AI' : 'System';
70
+ return `${prefix}: ${m.content}`;
71
+ })
72
+ .join('\n');
73
+ return { [this.memoryKey]: formatted };
74
+ }
75
+ async saveContext(inputValues, outputValues) {
76
+ await super.saveContext(inputValues, outputValues);
77
+ if (this.enableExtraction) {
78
+ await this.runExtraction(inputValues, outputValues);
79
+ }
80
+ }
81
+ async clear() {
82
+ await this.engramHistory.clear();
83
+ }
84
+ async getRelevantFacts(query) {
85
+ if (!query.trim())
86
+ return [];
87
+ try {
88
+ const results = await this.searchEngine.search(query, this.groupId, {
89
+ limit: this.maxFactsPerQuery,
90
+ minScore: this.minRelevanceScore,
91
+ });
92
+ if (results.edges.length === 0 && results.entities.length === 0)
93
+ return [];
94
+ let contextText = this.searchEngine.formatAsContext(results);
95
+ if (this.enableTraversal && results.entities.length > 0) {
96
+ try {
97
+ const seedUuids = results.entities.map((r) => r.entity.uuid);
98
+ const traverser = new GraphTraverser_1.GraphTraverser();
99
+ const traversal = await traverser.traverse(this.storage, seedUuids, {
100
+ maxHops: this.traversalHops,
101
+ maxEntities: 20,
102
+ });
103
+ if (traversal.context) {
104
+ contextText += '\n\n' + traversal.context;
105
+ }
106
+ }
107
+ catch (err) {
108
+ console.warn('Engram: Traversal enrichment failed:', err.message);
109
+ }
110
+ }
111
+ if (!contextText)
112
+ return [];
113
+ return [new messages_1.SystemMessage(`Relevant knowledge from memory:\n${contextText}`)];
114
+ }
115
+ catch (error) {
116
+ console.warn('Engram: Failed to retrieve relevant facts:', error.message);
117
+ return [];
118
+ }
119
+ }
120
+ extractInputText(values) {
121
+ if (this.inputKey && values[this.inputKey]) {
122
+ const val = values[this.inputKey];
123
+ return typeof val === 'string' ? val : JSON.stringify(val);
124
+ }
125
+ for (const key of ['input', 'question', 'query', 'text']) {
126
+ if (values[key]) {
127
+ const val = values[key];
128
+ return typeof val === 'string' ? val : JSON.stringify(val);
129
+ }
130
+ }
131
+ return '';
132
+ }
133
+ async runExtraction(inputValues, outputValues) {
134
+ if (!this.extractionPipeline)
135
+ return;
136
+ const humanText = this.extractInputText(inputValues);
137
+ const aiText = this.extractOutputText(outputValues);
138
+ if (!humanText && !aiText)
139
+ return;
140
+ try {
141
+ await this.extractionPipeline.process(humanText, aiText);
142
+ }
143
+ catch (error) {
144
+ console.warn('Engram: Extraction pipeline failed:', error.message);
145
+ }
146
+ }
147
+ extractOutputText(values) {
148
+ if (this.outputKey && values[this.outputKey]) {
149
+ const val = values[this.outputKey];
150
+ return typeof val === 'string' ? val : JSON.stringify(val);
151
+ }
152
+ for (const key of ['output', 'response', 'text', 'answer']) {
153
+ if (values[key]) {
154
+ const val = values[key];
155
+ return typeof val === 'string' ? val : JSON.stringify(val);
156
+ }
157
+ }
158
+ return '';
159
+ }
160
+ }
161
+ exports.EngramChatMemory = EngramChatMemory;
162
+ //# sourceMappingURL=EngramChatMemory.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"EngramChatMemory.js","sourceRoot":"","sources":["../../src/memory/EngramChatMemory.ts"],"names":[],"mappings":";;;AAAA,6CAA4E;AAE5E,uDAAyD;AAEzD,yEAAsE;AACtE,yEAG0C;AAC1C,qEAAkE;AAClE,8CAAuE;AAEvE,gEAA6D;AA+B7D,MAAa,gBAAiB,SAAQ,uBAAc;IAelD,YAAY,MAA6B;;QACvC,MAAM,OAAO,GAAG,IAAI,mDAAwB,CAAC;YAC3C,OAAO,EAAE,MAAM,CAAC,OAAO;YACvB,OAAO,EAAE,MAAM,CAAC,OAAO;YACvB,aAAa,EAAE,MAAA,MAAM,CAAC,aAAa,mCAAI,EAAE;SAC1C,CAAC,CAAC;QAEH,KAAK,CAAC;YACJ,WAAW,EAAE,OAAO;YACpB,cAAc,EAAE,MAAA,MAAM,CAAC,cAAc,mCAAI,IAAI;YAC7C,QAAQ,EAAE,MAAA,MAAM,CAAC,QAAQ,mCAAI,OAAO;YACpC,SAAS,EAAE,MA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C,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC;YAC7D,CAAC;QACH,CAAC;QAED,OAAO,EAAE,CAAC;IACZ,CAAC;CACF;AA5MD,4CA4MC"}
@@ -0,0 +1,22 @@
1
+ import { BaseChatMessageHistory } from '@langchain/core/chat_history';
2
+ import { BaseMessage } from '@langchain/core/messages';
3
+ import type { IGraphStorage } from '../storage/IGraphStorage';
4
+ export declare class EngramChatMessageHistory extends BaseChatMessageHistory {
5
+ lc_namespace: string[];
6
+ private storage;
7
+ private groupId;
8
+ private lastEpisodeUuid;
9
+ private contextWindow;
10
+ constructor(params: {
11
+ storage: IGraphStorage;
12
+ groupId: string;
13
+ contextWindow?: number;
14
+ });
15
+ getMessages(): Promise<BaseMessage[]>;
16
+ addMessage(message: BaseMessage): Promise<void>;
17
+ addUserMessage(message: string): Promise<void>;
18
+ addAIChatMessage(message: string): Promise<void>;
19
+ clear(): Promise<void>;
20
+ private episodeToMessage;
21
+ private messageToRole;
22
+ }
@@ -0,0 +1,72 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.EngramChatMessageHistory = void 0;
4
+ const chat_history_1 = require("@langchain/core/chat_history");
5
+ const messages_1 = require("@langchain/core/messages");
6
+ class EngramChatMessageHistory extends chat_history_1.BaseChatMessageHistory {
7
+ constructor(params) {
8
+ var _a;
9
+ super();
10
+ this.lc_namespace = ['engram', 'memory'];
11
+ this.lastEpisodeUuid = null;
12
+ this.storage = params.storage;
13
+ this.groupId = params.groupId;
14
+ this.contextWindow = (_a = params.contextWindow) !== null && _a !== void 0 ? _a : 10;
15
+ }
16
+ async getMessages() {
17
+ const episodes = await this.storage.getRecentEpisodes(this.groupId, this.contextWindow);
18
+ if (episodes.length > 0) {
19
+ this.lastEpisodeUuid = episodes[episodes.length - 1].uuid;
20
+ }
21
+ return episodes.map((ep) => this.episodeToMessage(ep));
22
+ }
23
+ async addMessage(message) {
24
+ const role = this.messageToRole(message);
25
+ const content = typeof message.content === 'string' ? message.content : JSON.stringify(message.content);
26
+ const episode = await this.storage.addEpisode({
27
+ group_id: this.groupId,
28
+ content,
29
+ role,
30
+ reference_time: new Date().toISOString(),
31
+ previous_episode_uuid: this.lastEpisodeUuid,
32
+ });
33
+ this.lastEpisodeUuid = episode.uuid;
34
+ }
35
+ async addUserMessage(message) {
36
+ await this.addMessage(new messages_1.HumanMessage(message));
37
+ }
38
+ async addAIChatMessage(message) {
39
+ await this.addMessage(new messages_1.AIMessage(message));
40
+ }
41
+ async clear() {
42
+ await this.storage.clearGroup(this.groupId);
43
+ this.lastEpisodeUuid = null;
44
+ }
45
+ episodeToMessage(episode) {
46
+ switch (episode.role) {
47
+ case 'human':
48
+ return new messages_1.HumanMessage(episode.content);
49
+ case 'ai':
50
+ return new messages_1.AIMessage(episode.content);
51
+ case 'system':
52
+ return new messages_1.SystemMessage(episode.content);
53
+ default:
54
+ return new messages_1.HumanMessage(episode.content);
55
+ }
56
+ }
57
+ messageToRole(message) {
58
+ const type = message._getType();
59
+ switch (type) {
60
+ case 'human':
61
+ return 'human';
62
+ case 'ai':
63
+ return 'ai';
64
+ case 'system':
65
+ return 'system';
66
+ default:
67
+ return 'human';
68
+ }
69
+ }
70
+ }
71
+ exports.EngramChatMessageHistory = EngramChatMessageHistory;
72
+ //# sourceMappingURL=EngramChatMessageHistory.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"EngramChatMessageHistory.js","sourceRoot":"","sources":["../../src/memory/EngramChatMessageHistory.ts"],"names":[],"mappings":";;;AAAA,+DAAsE;AACtE,uDAA+F;AAQ/F,MAAa,wBAAyB,SAAQ,qCAAsB;IAQlE,YAAY,MAA2E;;QACrF,KAAK,EAAE,CAAC;QARV,iBAAY,GAAG,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC;QAI5B,oBAAe,GAAkB,IAAI,CAAC;QAK5C,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC;QAC9B,IAAI,C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CAAC,OAAO,CAAC,CAAC,CAAC;IACnD,CAAC;IAED,KAAK,CAAC,gBAAgB,CAAC,OAAe;QACpC,MAAM,IAAI,CAAC,UAAU,CAAC,IAAI,oBAAS,CAAC,OAAO,CAAC,CAAC,CAAC;IAChD,CAAC;IAED,KAAK,CAAC,KAAK;QACT,MAAM,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QAC5C,IAAI,CAAC,eAAe,GAAG,IAAI,CAAC;IAC9B,CAAC;IAEO,gBAAgB,CAAC,OAAqB;QAC5C,QAAQ,OAAO,CAAC,IAAI,EAAE,CAAC;YACrB,KAAK,OAAO;gBACV,OAAO,IAAI,uBAAY,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;YAC3C,KAAK,IAAI;gBACP,OAAO,IAAI,oBAAS,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;YACxC,KAAK,QAAQ;gBACX,OAAO,IAAI,wBAAa,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;YAC5C;gBACE,OAAO,IAAI,uBAAY,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;QAC7C,CAAC;IACH,CAAC;IAEO,aAAa,CAAC,OAAoB;QACxC,MAAM,IAAI,GAAG,OAAO,CAAC,QAAQ,EAAE,CAAC;QAChC,QAAQ,IAAI,EAAE,CAAC;YACb,KAAK,OAAO;gBACV,OAAO,OAAO,CAAC;YACjB,KAAK,IAAI;gBACP,OAAO,IAAI,CAAC;YACd,KAAK,QAAQ;gBACX,OAAO,QAAQ,CAAC;YAClB;gBACE,OAAO,OAAO,CAAC;QACnB,CAAC;IACH,CAAC;CACF;AAjFD,4DAiFC"}
@@ -0,0 +1,2 @@
1
+ export { EngramChatMessageHistory } from './EngramChatMessageHistory';
2
+ export { EngramChatMemory, type EngramChatMemoryInput } from './EngramChatMemory';
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.EngramChatMemory = exports.EngramChatMessageHistory = void 0;
4
+ var EngramChatMessageHistory_1 = require("./EngramChatMessageHistory");
5
+ Object.defineProperty(exports, "EngramChatMessageHistory", { enumerable: true, get: function () { return EngramChatMessageHistory_1.EngramChatMessageHistory; } });
6
+ var EngramChatMemory_1 = require("./EngramChatMemory");
7
+ Object.defineProperty(exports, "EngramChatMemory", { enumerable: true, get: function () { return EngramChatMemory_1.EngramChatMemory; } });
8
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/memory/index.ts"],"names":[],"mappings":";;;AAAA,uEAAsE;AAA7D,oIAAA,wBAAwB,OAAA;AACjC,uDAAkF;AAAzE,oHAAA,gBAAgB,OAAA"}
@@ -0,0 +1,5 @@
1
+ import { type IExecuteFunctions, type INodeExecutionData, type INodeType, type INodeTypeDescription } from 'n8n-workflow';
2
+ export declare class EngramAdmin implements INodeType {
3
+ description: INodeTypeDescription;
4
+ execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]>;
5
+ }