@ai.ntellect/core 0.6.17 → 0.6.20

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 (79) hide show
  1. package/.mocharc.json +1 -2
  2. package/README.md +123 -178
  3. package/dist/graph/controller.js +29 -6
  4. package/dist/graph/index.js +302 -62
  5. package/dist/index.js +21 -6
  6. package/dist/interfaces/index.js +15 -0
  7. package/dist/modules/agenda/adapters/node-cron/index.js +29 -0
  8. package/dist/modules/agenda/index.js +140 -0
  9. package/dist/{services/embedding.js → modules/embedding/adapters/ai/index.js} +24 -7
  10. package/dist/modules/embedding/index.js +59 -0
  11. package/dist/modules/memory/adapters/in-memory/index.js +210 -0
  12. package/dist/{memory → modules/memory}/adapters/meilisearch/index.js +97 -2
  13. package/dist/{memory → modules/memory}/adapters/redis/index.js +77 -15
  14. package/dist/modules/memory/index.js +103 -0
  15. package/dist/utils/{stringifiy-zod-schema.js → generate-action-schema.js} +5 -5
  16. package/graph/controller.ts +46 -35
  17. package/graph/index.ts +534 -102
  18. package/graph.ts +74 -0
  19. package/index.ts +25 -7
  20. package/interfaces/index.ts +353 -27
  21. package/modules/agenda/adapters/node-cron/index.ts +25 -0
  22. package/modules/agenda/index.ts +159 -0
  23. package/modules/embedding/adapters/ai/index.ts +42 -0
  24. package/modules/embedding/index.ts +45 -0
  25. package/modules/memory/adapters/in-memory/index.ts +203 -0
  26. package/{memory → modules/memory}/adapters/meilisearch/index.ts +114 -12
  27. package/modules/memory/adapters/redis/index.ts +164 -0
  28. package/modules/memory/index.ts +93 -0
  29. package/package.json +3 -1
  30. package/test/graph/index.test.ts +578 -0
  31. package/test/modules/agenda/node-cron.test.ts +286 -0
  32. package/test/modules/embedding/ai.test.ts +78 -0
  33. package/test/modules/memory/adapters/in-memory.test.ts +153 -0
  34. package/test/{memory → modules/memory}/adapters/meilisearch.test.ts +79 -75
  35. package/test/modules/memory/adapters/redis.test.ts +169 -0
  36. package/test/modules/memory/base.test.ts +230 -0
  37. package/test/services/agenda.test.ts +279 -280
  38. package/types/index.ts +93 -202
  39. package/utils/{stringifiy-zod-schema.ts → generate-action-schema.ts} +3 -3
  40. package/app/README.md +0 -36
  41. package/app/app/favicon.ico +0 -0
  42. package/app/app/globals.css +0 -21
  43. package/app/app/gun.ts +0 -0
  44. package/app/app/layout.tsx +0 -18
  45. package/app/app/page.tsx +0 -321
  46. package/app/eslint.config.mjs +0 -16
  47. package/app/next.config.ts +0 -7
  48. package/app/package-lock.json +0 -5912
  49. package/app/package.json +0 -31
  50. package/app/pnpm-lock.yaml +0 -4031
  51. package/app/postcss.config.mjs +0 -8
  52. package/app/public/file.svg +0 -1
  53. package/app/public/globe.svg +0 -1
  54. package/app/public/next.svg +0 -1
  55. package/app/public/vercel.svg +0 -1
  56. package/app/public/window.svg +0 -1
  57. package/app/tailwind.config.ts +0 -18
  58. package/app/tsconfig.json +0 -27
  59. package/dist/memory/index.js +0 -9
  60. package/dist/services/agenda.js +0 -115
  61. package/dist/services/queue.js +0 -142
  62. package/dist/utils/experimental-graph-rag.js +0 -152
  63. package/dist/utils/generate-object.js +0 -111
  64. package/dist/utils/inject-actions.js +0 -16
  65. package/dist/utils/queue-item-transformer.js +0 -24
  66. package/dist/utils/sanitize-results.js +0 -60
  67. package/memory/adapters/redis/index.ts +0 -103
  68. package/memory/index.ts +0 -22
  69. package/services/agenda.ts +0 -118
  70. package/services/embedding.ts +0 -26
  71. package/services/queue.ts +0 -145
  72. package/test/memory/adapters/redis.test.ts +0 -159
  73. package/test/memory/base.test.ts +0 -225
  74. package/test/services/queue.test.ts +0 -286
  75. package/utils/experimental-graph-rag.ts +0 -170
  76. package/utils/generate-object.ts +0 -117
  77. package/utils/inject-actions.ts +0 -19
  78. package/utils/queue-item-transformer.ts +0 -38
  79. package/utils/sanitize-results.ts +0 -66
@@ -1,8 +0,0 @@
1
- /** @type {import('postcss-load-config').Config} */
2
- const config = {
3
- plugins: {
4
- tailwindcss: {},
5
- },
6
- };
7
-
8
- export default config;
@@ -1 +0,0 @@
1
- <svg fill="none" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 13.5V5.41a1 1 0 0 0-.3-.7L9.8.29A1 1 0 0 0 9.08 0H1.5v13.5A2.5 2.5 0 0 0 4 16h8a2.5 2.5 0 0 0 2.5-2.5m-1.5 0v-7H8v-5H3v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1M9.5 5V2.12L12.38 5zM5.13 5h-.62v1.25h2.12V5zm-.62 3h7.12v1.25H4.5zm.62 3h-.62v1.25h7.12V11z" clip-rule="evenodd" fill="#666" fill-rule="evenodd"/></svg>
@@ -1 +0,0 @@
1
- <svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g clip-path="url(#a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M10.27 14.1a6.5 6.5 0 0 0 3.67-3.45q-1.24.21-2.7.34-.31 1.83-.97 3.1M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.48-1.52a7 7 0 0 1-.96 0H7.5a4 4 0 0 1-.84-1.32q-.38-.89-.63-2.08a40 40 0 0 0 3.92 0q-.25 1.2-.63 2.08a4 4 0 0 1-.84 1.31zm2.94-4.76q1.66-.15 2.95-.43a7 7 0 0 0 0-2.58q-1.3-.27-2.95-.43a18 18 0 0 1 0 3.44m-1.27-3.54a17 17 0 0 1 0 3.64 39 39 0 0 1-4.3 0 17 17 0 0 1 0-3.64 39 39 0 0 1 4.3 0m1.1-1.17q1.45.13 2.69.34a6.5 6.5 0 0 0-3.67-3.44q.65 1.26.98 3.1M8.48 1.5l.01.02q.41.37.84 1.31.38.89.63 2.08a40 40 0 0 0-3.92 0q.25-1.2.63-2.08a4 4 0 0 1 .85-1.32 7 7 0 0 1 .96 0m-2.75.4a6.5 6.5 0 0 0-3.67 3.44 29 29 0 0 1 2.7-.34q.31-1.83.97-3.1M4.58 6.28q-1.66.16-2.95.43a7 7 0 0 0 0 2.58q1.3.27 2.95.43a18 18 0 0 1 0-3.44m.17 4.71q-1.45-.12-2.69-.34a6.5 6.5 0 0 0 3.67 3.44q-.65-1.27-.98-3.1" fill="#666"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h16v16H0z"/></clipPath></defs></svg>
@@ -1 +0,0 @@
1
- <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>
@@ -1 +0,0 @@
1
- <svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1155 1000"><path d="m577.3 0 577.4 1000H0z" fill="#fff"/></svg>
@@ -1 +0,0 @@
1
- <svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5h13v10a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1zM0 1h16v11.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12.5zm3.75 4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5M7 4.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0m1.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5" fill="#666"/></svg>
@@ -1,18 +0,0 @@
1
- import type { Config } from "tailwindcss";
2
-
3
- export default {
4
- content: [
5
- "./pages/**/*.{js,ts,jsx,tsx,mdx}",
6
- "./components/**/*.{js,ts,jsx,tsx,mdx}",
7
- "./app/**/*.{js,ts,jsx,tsx,mdx}",
8
- ],
9
- theme: {
10
- extend: {
11
- colors: {
12
- background: "var(--background)",
13
- foreground: "var(--foreground)",
14
- },
15
- },
16
- },
17
- plugins: [require("daisyui")],
18
- } satisfies Config;
package/app/tsconfig.json DELETED
@@ -1,27 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "target": "ES2017",
4
- "lib": ["dom", "dom.iterable", "esnext"],
5
- "allowJs": true,
6
- "skipLibCheck": true,
7
- "strict": true,
8
- "noEmit": true,
9
- "esModuleInterop": true,
10
- "module": "esnext",
11
- "moduleResolution": "bundler",
12
- "resolveJsonModule": true,
13
- "isolatedModules": true,
14
- "jsx": "preserve",
15
- "incremental": true,
16
- "plugins": [
17
- {
18
- "name": "next"
19
- }
20
- ],
21
- "paths": {
22
- "@/*": ["./*"]
23
- }
24
- },
25
- "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
26
- "exclude": ["node_modules"]
27
- }
@@ -1,9 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.BaseMemory = void 0;
4
- class BaseMemory {
5
- constructor(cacheService) {
6
- this.cacheService = cacheService;
7
- }
8
- }
9
- exports.BaseMemory = BaseMemory;
@@ -1,115 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __importDefault = (this && this.__importDefault) || function (mod) {
12
- return (mod && mod.__esModule) ? mod : { "default": mod };
13
- };
14
- Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.Agenda = void 0;
16
- const node_cron_1 = __importDefault(require("node-cron"));
17
- class Agenda {
18
- constructor() {
19
- this.scheduledRequests = new Map();
20
- this.cronJobs = new Map();
21
- }
22
- /**
23
- * Schedule a new request to be processed later
24
- */
25
- scheduleRequest(request, callbacks) {
26
- return __awaiter(this, void 0, void 0, function* () {
27
- const id = crypto.randomUUID();
28
- const scheduledRequest = {
29
- id,
30
- originalRequest: request.originalRequest,
31
- cronExpression: request.cronExpression,
32
- isRecurring: false,
33
- createdAt: new Date(),
34
- };
35
- // Create cron job
36
- const cronJob = node_cron_1.default.schedule(request.cronExpression, () => {
37
- console.log(`🔄 Executing scheduled request: ${id}`);
38
- if (callbacks === null || callbacks === void 0 ? void 0 : callbacks.onExecuted) {
39
- callbacks.onExecuted(id, scheduledRequest.originalRequest);
40
- }
41
- console.log(`✅ Scheduled request executed successfully: ${id}`);
42
- // Auto-stop pour les tâches non récurrentes
43
- if (!scheduledRequest.isRecurring) {
44
- this.cancelScheduledRequest(id);
45
- }
46
- });
47
- // Démarrer le job en mode non-running
48
- cronJob.stop();
49
- // Store request and job
50
- this.scheduledRequests.set(id, scheduledRequest);
51
- this.cronJobs.set(id, cronJob);
52
- if (callbacks === null || callbacks === void 0 ? void 0 : callbacks.onScheduled)
53
- callbacks.onScheduled(id);
54
- // Démarrer le job après l'avoir stocké
55
- cronJob.start();
56
- return id;
57
- });
58
- }
59
- /**
60
- * Cancel a scheduled request
61
- */
62
- cancelScheduledRequest(requestId) {
63
- const cronJob = this.cronJobs.get(requestId);
64
- if (cronJob) {
65
- try {
66
- cronJob.stop();
67
- this.cronJobs.delete(requestId);
68
- this.scheduledRequests.delete(requestId);
69
- return true;
70
- }
71
- catch (error) {
72
- console.error(`Failed to stop cron job ${requestId}:`, error);
73
- return false;
74
- }
75
- }
76
- return false;
77
- }
78
- /**
79
- * Get all scheduled requests
80
- */
81
- getScheduledRequests() {
82
- return Array.from(this.scheduledRequests.values());
83
- }
84
- /**
85
- * Stop all cron jobs
86
- */
87
- stopAll() {
88
- const ids = Array.from(this.cronJobs.keys());
89
- // Arrêter tous les jobs de manière synchrone
90
- for (const id of ids) {
91
- const job = this.cronJobs.get(id);
92
- if (job) {
93
- job.stop();
94
- this.cronJobs.delete(id);
95
- this.scheduledRequests.delete(id);
96
- }
97
- }
98
- // Double vérification
99
- this.cronJobs.clear();
100
- this.scheduledRequests.clear();
101
- }
102
- stop() {
103
- return __awaiter(this, void 0, void 0, function* () {
104
- this.stopAll();
105
- yield new Promise((resolve) => setTimeout(resolve, 100));
106
- });
107
- }
108
- cancel(query) {
109
- return __awaiter(this, void 0, void 0, function* () {
110
- this.stopAll();
111
- yield new Promise((resolve) => setTimeout(resolve, 100));
112
- });
113
- }
114
- }
115
- exports.Agenda = Agenda;
@@ -1,142 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.Queue = void 0;
13
- class Queue {
14
- constructor(actions, callbacks = {}) {
15
- this.queue = [];
16
- this.results = [];
17
- this.isProcessing = false;
18
- this.actions = actions;
19
- this.callbacks = callbacks;
20
- }
21
- add(actions) {
22
- if (Array.isArray(actions)) {
23
- this.queue.push(...actions);
24
- }
25
- else {
26
- this.queue.push(actions);
27
- }
28
- }
29
- execute() {
30
- return __awaiter(this, void 0, void 0, function* () {
31
- var _a, _b, _c, _d, _e;
32
- if (this.isProcessing) {
33
- return;
34
- }
35
- this.isProcessing = true;
36
- const actionPromises = [];
37
- for (const action of this.queue) {
38
- const actionConfig = this.actions.find((a) => a.name === action.name);
39
- if ((_a = actionConfig === null || actionConfig === void 0 ? void 0 : actionConfig.confirmation) === null || _a === void 0 ? void 0 : _a.requireConfirmation) {
40
- const shouldProceed = yield ((_c = (_b = this.callbacks).onConfirmationRequired) === null || _c === void 0 ? void 0 : _c.call(_b, actionConfig.confirmation.message ||
41
- `Do you want to proceed with action: ${action.name}?`));
42
- if (!shouldProceed) {
43
- this.results.push({
44
- name: action.name,
45
- parameters: this.formatArguments(action.parameters),
46
- result: null,
47
- error: "Action cancelled by user",
48
- cancelled: true,
49
- });
50
- continue;
51
- }
52
- }
53
- const parameters = this.formatArguments(action.parameters);
54
- actionPromises.push(this.executeAction(action)
55
- .then((result) => {
56
- var _a, _b;
57
- (_b = (_a = this.callbacks).onActionComplete) === null || _b === void 0 ? void 0 : _b.call(_a, result);
58
- return result;
59
- })
60
- .catch((error) => {
61
- var _a, _b;
62
- const result = {
63
- name: action.name,
64
- parameters,
65
- result: null,
66
- error: error.message || "Unknown error occurred",
67
- };
68
- (_b = (_a = this.callbacks).onActionComplete) === null || _b === void 0 ? void 0 : _b.call(_a, result);
69
- return result;
70
- }));
71
- }
72
- try {
73
- const results = yield Promise.all(actionPromises);
74
- this.results.push(...results);
75
- this.queue = [];
76
- (_e = (_d = this.callbacks).onQueueComplete) === null || _e === void 0 ? void 0 : _e.call(_d, this.results);
77
- this.isProcessing = false;
78
- return this.results;
79
- }
80
- catch (error) {
81
- this.isProcessing = false;
82
- throw error;
83
- }
84
- });
85
- }
86
- formatArguments(args) {
87
- return args.reduce((acc, arg) => {
88
- try {
89
- // Parse the JSON string if the value is a stringified JSON object
90
- const parsedValue = JSON.parse(arg.value);
91
- if (parsedValue &&
92
- typeof parsedValue === "object" &&
93
- "value" in parsedValue) {
94
- acc[parsedValue.name] = parsedValue.value;
95
- }
96
- else {
97
- // Fallback to original value if not in expected format
98
- acc[arg.name] = arg.value;
99
- }
100
- }
101
- catch (_a) {
102
- // If JSON parsing fails, use the original value
103
- acc[arg.name] = arg.value;
104
- }
105
- return acc;
106
- }, {});
107
- }
108
- executeAction(action) {
109
- return __awaiter(this, void 0, void 0, function* () {
110
- var _a, _b;
111
- (_b = (_a = this.callbacks).onActionStart) === null || _b === void 0 ? void 0 : _b.call(_a, action);
112
- const actionConfig = this.actions.find((a) => a.name === action.name);
113
- if (!actionConfig) {
114
- return {
115
- name: action.name,
116
- parameters: {},
117
- result: null,
118
- error: `Action '${action.name}' not found in actions list`,
119
- };
120
- }
121
- const actionArgs = this.formatArguments(action.parameters);
122
- try {
123
- const result = yield actionConfig.execute(actionArgs);
124
- return {
125
- name: action.name,
126
- parameters: actionArgs,
127
- result,
128
- error: null,
129
- };
130
- }
131
- catch (error) {
132
- return {
133
- name: action.name,
134
- parameters: actionArgs,
135
- result: null,
136
- error: error.message || "Unknown error occurred",
137
- };
138
- }
139
- });
140
- }
141
- }
142
- exports.Queue = Queue;
@@ -1,152 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.experimentalGraphRag = void 0;
13
- const meilisearch_1 = require("../memory/adapters/meilisearch");
14
- const embedding_1 = require("../services/embedding");
15
- const openai_1 = require("@ai-sdk/openai");
16
- const ai_1 = require("ai");
17
- const zod_1 = require("zod");
18
- const experimentalGraphRag = (context) => __awaiter(void 0, void 0, void 0, function* () {
19
- if (!process.env.MEILISEARCH_API_KEY)
20
- throw new Error("MEILISEARCH_API_KEY is not set");
21
- if (!process.env.MEILISEARCH_HOST)
22
- throw new Error("MEILISEARCH_HOST is not set");
23
- const memoryManager = new meilisearch_1.MeilisearchAdapter({
24
- apiKey: process.env.MEILISEARCH_API_KEY,
25
- host: process.env.MEILISEARCH_HOST,
26
- });
27
- yield memoryManager.init("nodes");
28
- yield memoryManager.init("edges");
29
- const { existingNodes } = yield retrieveExistingRelations(memoryManager, "nodes");
30
- const prompt = `
31
- User asked: ${context.prompt}
32
- Results: ${JSON.stringify(context.results, null, 2)}
33
- Existing nodes: ${JSON.stringify(existingNodes, null, 2)}
34
- `;
35
- console.log("🔍 Prompt:", prompt);
36
- const llmMemory = yield (0, ai_1.generateObject)({
37
- model: (0, openai_1.openai)("gpt-4o"),
38
- prompt,
39
- schema: zod_1.z.object({
40
- nodes: zod_1.z.array(zod_1.z.object({
41
- name: zod_1.z.string(), // Nom de l'entité (ex: Adresse, ETH, Transaction ID)
42
- metadata: zod_1.z.record(zod_1.z.string(), zod_1.z.any()), // Métadonnées associées
43
- })),
44
- edges: zod_1.z.array(zod_1.z.object({
45
- source: zod_1.z.string(), // ID de l'entité source
46
- target: zod_1.z.string(), // ID de l'entité cible
47
- relation: zod_1.z.string(), // Type de relation (ex: "sent", "received", "on_chain")
48
- })),
49
- }),
50
- system: `
51
- You are an **AI memory manager** for a crypto wallet assistant.
52
-
53
- ## Rules:
54
- - Nodes are entities like user, networks, tokens...etc
55
- - Relations are edges like sent, uses, supported_on, loves, has_website...etc
56
- - Ensure NO DUPLICATE RELATIONS.
57
- - Standardize all relations using Cypher language.
58
-
59
- Return the structured memory in JSON format, ensuring it follows the schema.
60
-
61
- Generate structured graph data accordingly.
62
-
63
- Format the output as a JSON object :
64
- {
65
- nodes: [
66
- {
67
- name: string,
68
- metadata: Record<string, any>,
69
- },
70
- ],
71
- edges: [
72
- {
73
- source: string,
74
- target: string,
75
- relation: string,
76
- },
77
- ],
78
- }
79
- `,
80
- });
81
- console.log("🔍 LLM memory (graph-based):");
82
- console.log("Nodes:");
83
- console.dir(llmMemory.object.nodes, { depth: null, colors: true });
84
- console.log("Edges:");
85
- console.dir(llmMemory.object.edges, { depth: null, colors: true });
86
- const embeddingManager = new embedding_1.AIEmbeddingService(openai_1.openai.embedding("text-embedding-3-small"));
87
- const embedding = yield embeddingManager.embedText(context.prompt);
88
- let nodesNameToId = {};
89
- for (const node of llmMemory.object.nodes) {
90
- // Search for existing memory with same data and query
91
- const searchResults = yield memoryManager.search(node.name, "nodes", {
92
- limit: 1,
93
- });
94
- const existingMemory = searchResults.find((result) => result.document.data.name === node.name &&
95
- result.document.roomId === "nodes");
96
- // If found, return existing memory
97
- if (existingMemory) {
98
- nodesNameToId[node.name] = existingMemory.document.id;
99
- }
100
- else {
101
- const nodesMemory = yield memoryManager.createMemory({
102
- data: node,
103
- embedding,
104
- roomId: "nodes",
105
- });
106
- nodesNameToId[node.name] = (nodesMemory === null || nodesMemory === void 0 ? void 0 : nodesMemory.id) || "";
107
- }
108
- }
109
- for (const edge of llmMemory.object.edges) {
110
- // Verify if source and target already exist in memory
111
- const searchResults = yield memoryManager.search(nodesNameToId[edge.source], "edges", {
112
- limit: 100,
113
- });
114
- const existingEdge = searchResults.find((result) => result.document.data.source === nodesNameToId[edge.source] &&
115
- result.document.data.target === nodesNameToId[edge.target] &&
116
- result.document.data.relation === edge.relation);
117
- if (existingEdge) {
118
- }
119
- else {
120
- yield memoryManager.createMemory({
121
- data: {
122
- source: nodesNameToId[edge.source],
123
- target: nodesNameToId[edge.target],
124
- relation: edge.relation,
125
- },
126
- embedding,
127
- roomId: "edges",
128
- });
129
- }
130
- }
131
- });
132
- exports.experimentalGraphRag = experimentalGraphRag;
133
- function retrieveExistingRelations(memoryManager, roomId) {
134
- return __awaiter(this, void 0, void 0, function* () {
135
- const existingNodesMemories = yield memoryManager.getAllMemories("nodes");
136
- const existingEdgesMemories = yield memoryManager.getAllMemories("edges");
137
- let existingNodes = [];
138
- let existingEdges = [];
139
- if (existingNodesMemories.length > 0) {
140
- existingNodes = existingNodesMemories.flatMap((memory) => {
141
- return {
142
- id: memory.id,
143
- data: memory.data,
144
- };
145
- });
146
- }
147
- if (existingEdgesMemories.length > 0) {
148
- existingEdges = existingEdgesMemories.flatMap((memory) => memory.data || []);
149
- }
150
- return { existingNodes, existingEdges };
151
- });
152
- }
@@ -1,111 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.generateObject = exports.describeZodSchema = void 0;
13
- const ai_1 = require("ai");
14
- const zod_1 = require("zod");
15
- const describeZodSchema = (schema) => {
16
- if (schema instanceof zod_1.z.ZodObject) {
17
- const entries = Object.entries(schema.shape);
18
- const fields = entries.map(([key, value]) => {
19
- const description = value._def.description || "";
20
- const fieldSchema = (0, exports.describeZodSchema)(value);
21
- return description
22
- ? `${key}: ${fieldSchema} // ${description}`
23
- : `${key}: ${fieldSchema}`;
24
- });
25
- return `z.object({${fields.join(", ")}})`;
26
- }
27
- if (schema instanceof zod_1.z.ZodArray) {
28
- return `z.array(${(0, exports.describeZodSchema)(schema.element)})`;
29
- }
30
- if (schema instanceof zod_1.z.ZodString) {
31
- return "z.string()";
32
- }
33
- if (schema instanceof zod_1.z.ZodNumber) {
34
- return "z.number()";
35
- }
36
- if (schema instanceof zod_1.z.ZodBoolean) {
37
- return "z.boolean()";
38
- }
39
- if (schema instanceof zod_1.z.ZodOptional) {
40
- return `z.optional(${(0, exports.describeZodSchema)(schema._def.innerType)})`;
41
- }
42
- if (schema instanceof zod_1.z.ZodUnion) {
43
- return `z.union([${schema._def.options
44
- .map((option) => (0, exports.describeZodSchema)(option))
45
- .join(", ")}])`;
46
- }
47
- if (schema instanceof zod_1.z.ZodEnum) {
48
- return `z.enum(${JSON.stringify(schema._def.values)})`;
49
- }
50
- if (schema instanceof zod_1.z.ZodLiteral) {
51
- return `z.literal(${JSON.stringify(schema._def.value)})`;
52
- }
53
- return "z.unknown()"; // Fallback for unknown types
54
- };
55
- exports.describeZodSchema = describeZodSchema;
56
- const generateObject = (config) => __awaiter(void 0, void 0, void 0, function* () {
57
- var _a;
58
- // Generate a detailed description of the schema
59
- const schemaDescription = (0, exports.describeZodSchema)(config.schema);
60
- const baseContext = `
61
- ${config.system}
62
- EXPECTED SCHEMA:
63
- ${schemaDescription}
64
-
65
- BAD EXAMPLE:
66
- \`\`\`json
67
- {
68
- "key": "value"
69
- }
70
- \`\`\`
71
-
72
- GOOD EXAMPLE:
73
- {
74
- "key": "value"
75
- }
76
-
77
- OUTPUT ONLY THE JSON SCHEMA, NO 'TRIPLE QUOTES'JSON OR ANY OTHER TEXT. ONLY THE JSON SCHEMA.
78
- `;
79
- console.log("🔍 Generating object with context:");
80
- console.log(`${config.prompt}\n${baseContext}\n`);
81
- const response = yield (0, ai_1.generateText)({
82
- model: config.model,
83
- messages: !config.prompt
84
- ? [
85
- {
86
- role: "system",
87
- content: baseContext,
88
- },
89
- ...((_a = config.messages) !== null && _a !== void 0 ? _a : []),
90
- ]
91
- : undefined,
92
- system: config.system,
93
- temperature: config.temperature,
94
- prompt: !config.prompt ? undefined : `${config.prompt}\n\n${baseContext}`,
95
- });
96
- try {
97
- // Clean the response text from any markdown or code block markers
98
- const cleanText = response.text
99
- .replace(/```json\s*/g, "")
100
- .replace(/```\s*$/g, "")
101
- .trim();
102
- const parsedResponse = JSON.parse(cleanText);
103
- const validatedResponse = config.schema.parse(parsedResponse);
104
- return { object: validatedResponse };
105
- }
106
- catch (error) {
107
- console.error("Error parsing or validating JSON response:", error);
108
- throw new Error("Failed to generate valid JSON response");
109
- }
110
- });
111
- exports.generateObject = generateObject;
@@ -1,16 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.injectActions = void 0;
4
- const injectActions = (actions) => {
5
- return actions.map((action) => {
6
- const parameters = action.parameters;
7
- const schemaShape = Object.keys(parameters._def.shape()).join(", ");
8
- const actionString = `* ${action.name}( { ${schemaShape} }) (${action.description}) ${action.examples
9
- ? `Eg: ${action.examples.map((example) => {
10
- return JSON.stringify(example);
11
- })}`
12
- : ""}`;
13
- return actionString;
14
- });
15
- };
16
- exports.injectActions = injectActions;
@@ -1,24 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.QueueItemTransformer = void 0;
4
- class QueueItemTransformer {
5
- static transformActionToQueueItem(action) {
6
- return {
7
- name: action.name || "",
8
- parameters: QueueItemTransformer.transformParameters(action.parameters || {}),
9
- };
10
- }
11
- static transformFromSimilarActions(similarActions) {
12
- return similarActions === null || similarActions === void 0 ? void 0 : similarActions.map((action) => QueueItemTransformer.transformActionToQueueItem(action));
13
- }
14
- static transformParameters(parameters) {
15
- return Object.entries(parameters).map(([name, value]) => ({
16
- name,
17
- value: typeof value === "object" ? JSON.stringify(value) : String(value),
18
- }));
19
- }
20
- static transformActionsToQueueItems(actions) {
21
- return actions === null || actions === void 0 ? void 0 : actions.map((action) => this.transformActionToQueueItem(action));
22
- }
23
- }
24
- exports.QueueItemTransformer = QueueItemTransformer;