@ai.ntellect/core 0.6.0 → 0.6.2

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 (37) hide show
  1. package/create-llm-to-select-multiple-graph copy.ts +243 -0
  2. package/create-llm-to-select-multiple-graph.ts +148 -0
  3. package/dist/create-llm-to-select-multiple-graph copy.js +201 -0
  4. package/dist/create-llm-to-select-multiple-graph.js +142 -0
  5. package/dist/graph/controller.js +6 -6
  6. package/dist/graph/engine.js +198 -135
  7. package/dist/index copy.js +76 -0
  8. package/dist/utils/setup-graphs.js +28 -0
  9. package/dist/utils/stringifiy-zod-schema.js +41 -0
  10. package/graph/controller.ts +11 -9
  11. package/graph/engine.ts +244 -166
  12. package/index copy.ts +81 -0
  13. package/index.ts +1 -1
  14. package/package.json +1 -1
  15. package/test/graph/engine.test.ts +27 -44
  16. package/tsconfig.json +1 -1
  17. package/types/index.ts +11 -3
  18. package/utils/setup-graphs.ts +45 -0
  19. package/utils/stringifiy-zod-schema.ts +45 -0
  20. package/dist/test/graph/controller.test.js +0 -170
  21. package/dist/test/graph/engine.test.js +0 -465
  22. package/dist/test/memory/adapters/meilisearch.test.js +0 -250
  23. package/dist/test/memory/adapters/redis.test.js +0 -143
  24. package/dist/test/memory/base.test.js +0 -209
  25. package/dist/test/services/agenda.test.js +0 -230
  26. package/dist/test/services/queue.test.js +0 -258
  27. package/dist/utils/schema-generator.js +0 -46
  28. package/dist/utils/state-manager.js +0 -20
  29. package/utils/generate-object.js +0 -111
  30. package/utils/header-builder.js +0 -34
  31. package/utils/inject-actions.js +0 -16
  32. package/utils/queue-item-transformer.js +0 -24
  33. package/utils/sanitize-results.js +0 -60
  34. package/utils/schema-generator.js +0 -46
  35. package/utils/schema-generator.ts +0 -73
  36. package/utils/state-manager.js +0 -20
  37. package/utils/state-manager.ts +0 -30
@@ -0,0 +1,243 @@
1
+ import { openai } from "@ai-sdk/openai";
2
+ import { streamObject } from "ai";
3
+ import { parseEther } from "ethers";
4
+ import { z } from "zod";
5
+ import { GraphEngine } from "./graph/engine";
6
+ import { networkConfigs } from "./index copy";
7
+ import { Action, GraphDefinition, SharedState } from "./types";
8
+ import { setupGraphsWithActions } from "./utils/setup-graphs";
9
+ import { stringifyZodSchema } from "./utils/stringifiy-zod-schema";
10
+ // ---- I. Create a simple workflow ----
11
+ // 1. Define the context
12
+ type MainContext = {
13
+ messages: string;
14
+ reasoning?: boolean;
15
+ actions?: Action[];
16
+ };
17
+
18
+ type ContextA = {
19
+ to: string;
20
+ value: string;
21
+ chain: {
22
+ id: number;
23
+ rpc: string;
24
+ };
25
+ type: string;
26
+ };
27
+
28
+ type ContextB = {
29
+ messages: string;
30
+ };
31
+
32
+ // // 2. Define the graph
33
+
34
+ // ---- II. Create an LLM to select the
35
+
36
+ // 2. Define the graph with a name
37
+ const graphDefinitionA: GraphDefinition<ContextA> = {
38
+ name: "prepare-evm-transaction", // Assign a name to match the workflow
39
+ entryNode: "prepare-evm-transaction",
40
+ nodes: {
41
+ "prepare-evm-transaction": {
42
+ name: "prepare-evm-transaction",
43
+ description: "Prepare a transaction for the user to sign.",
44
+ schema: z.object({
45
+ to: z.string(),
46
+ value: z
47
+ .string()
48
+ .describe("Ask the user for the amount to send, if not specified"),
49
+ chain: z
50
+ .string()
51
+ .describe(
52
+ "Examples networks: ethereum, arbitrum, base. IMPORTANT: You must respect the network name."
53
+ ),
54
+ }),
55
+ execute: async (params, state) => {
56
+ console.log("💰 Prepare transaction", { params, state });
57
+ const networkConfig = networkConfigs[params.chain.toLowerCase()];
58
+
59
+ if (!networkConfig) {
60
+ throw new Error(`Network ${params.chain} not found`);
61
+ }
62
+
63
+ return {
64
+ to: params.to,
65
+ value: parseEther(params.value).toString(),
66
+ chain: {
67
+ id: networkConfig.id || 0,
68
+ rpc: networkConfig.rpc,
69
+ },
70
+ type: "transfer",
71
+ };
72
+ },
73
+ },
74
+ },
75
+ };
76
+
77
+ const graphDefinitionB: GraphDefinition<ContextB> = {
78
+ name: "security-analysis",
79
+ entryNode: "security-analysis",
80
+ nodes: {
81
+ "security-analysis": {
82
+ name: "security-analysis",
83
+ description: "Get news",
84
+ execute: async () => {
85
+ return { messages: "Hello, world!" };
86
+ },
87
+ relationships: [{ name: "end" }],
88
+ },
89
+ end: {
90
+ name: "end",
91
+ description: "End the graph",
92
+ execute: async () => {
93
+ return {
94
+ messages:
95
+ "Here the security analysis of Bitcoin: Bitcoin is a good investment",
96
+ };
97
+ },
98
+ },
99
+ },
100
+ };
101
+ // 3. Define the initial state
102
+ const initialState: SharedState<MainContext> = {
103
+ messages: "",
104
+ reasoning: true,
105
+ };
106
+ type CombinedContext = ContextA | ContextB;
107
+
108
+ const graphMaps: GraphDefinition<CombinedContext>[] = [
109
+ graphDefinitionA as GraphDefinition<CombinedContext>,
110
+ graphDefinitionB as GraphDefinition<CombinedContext>,
111
+ // Add other graphs
112
+ ];
113
+
114
+ // ---- II. Create a node with LLM
115
+ (async () => {
116
+ const prompt = "je veux envoyer 0.0001 eth à 0x123 sur ethereum";
117
+ // Dynamically extract start nodes from each graph definition in graphMaps
118
+
119
+ const reasoningGraphDefinition: GraphDefinition<MainContext> = {
120
+ name: "reasoning",
121
+ entryNode: "reasoning",
122
+ nodes: {
123
+ reasoning: {
124
+ name: "reasoning",
125
+ description: "Reasoning",
126
+ execute: async (params, state) => {
127
+ console.log("Reasoning", { params, state });
128
+ const startNodesSchema = graphMaps.map(
129
+ (graphDefinition) =>
130
+ graphDefinition.nodes[graphDefinition.entryNode]
131
+ );
132
+
133
+ // Pass the start nodes into stringifyZodSchema
134
+
135
+ const system = `You are a wallet assistant. Don't reuse the same workflow multiple times.
136
+ Here the available workflows and parameters:
137
+ workflows:${stringifyZodSchema(startNodesSchema)}`;
138
+ console.log(system);
139
+
140
+ const llm = await streamObject({
141
+ model: openai("gpt-4o"),
142
+ prompt,
143
+ schema: z.object({
144
+ actions: z.array(
145
+ z.object({
146
+ name: z.string(),
147
+ parameters: z.array(
148
+ z.object({
149
+ name: z.string(),
150
+ value: z.any(),
151
+ })
152
+ ),
153
+ })
154
+ ),
155
+ response: z.string(),
156
+ }),
157
+ system,
158
+ });
159
+ console.dir(llm.object, { depth: null });
160
+
161
+ for await (const chunk of llm.partialObjectStream) {
162
+ if (chunk.response) {
163
+ // console.log(chunk.response);
164
+ }
165
+ }
166
+
167
+ const actions = (await llm.object).actions;
168
+ console.log({ actions });
169
+
170
+ const selectedWorkflows = (await llm.object).actions as Action[];
171
+ return {
172
+ messages: "Hello, world!",
173
+ actions: selectedWorkflows,
174
+ };
175
+ },
176
+ condition: (state) => {
177
+ return state.reasoning === true;
178
+ },
179
+ relationships: [{ name: "actions" }],
180
+ },
181
+ actions: {
182
+ name: "actions",
183
+ description: "Actions",
184
+ execute: async (parameters, state) => {
185
+ if (!state.actions) {
186
+ throw new Error("No actions found");
187
+ }
188
+ const baseStateMapping: Record<
189
+ string,
190
+ SharedState<CombinedContext>
191
+ > = {
192
+ "prepare-evm-transaction": initialState,
193
+ // Add other workflows and their base states as needed
194
+ };
195
+
196
+ const {
197
+ initialStates,
198
+ graphs: selectedGraphs,
199
+ startNodes,
200
+ } = setupGraphsWithActions(
201
+ state.actions,
202
+ baseStateMapping,
203
+ graphMaps
204
+ );
205
+
206
+ // Execute graphs with dynamically determined initial states
207
+ const results =
208
+ await GraphEngine.executeGraphsInSequence<CombinedContext>(
209
+ selectedGraphs,
210
+ startNodes,
211
+ initialStates,
212
+ (graph) => {
213
+ console.log(`Graph ${graph.name} updated`, graph.getState());
214
+ },
215
+ (error, nodeName, state) => {
216
+ console.error(`Erreur dans ${nodeName}`, error, state);
217
+ }
218
+ );
219
+
220
+ console.log({ results });
221
+
222
+ return {
223
+ messages: "Hello, world!",
224
+ results,
225
+ };
226
+ },
227
+ condition: (state) => {
228
+ if (
229
+ state.reasoning === true &&
230
+ state.actions &&
231
+ state.actions.length > 0
232
+ ) {
233
+ return true;
234
+ }
235
+ return false;
236
+ },
237
+ },
238
+ },
239
+ };
240
+
241
+ const reasoningGraph = new GraphEngine(reasoningGraphDefinition);
242
+ await reasoningGraph.execute(initialState, "reasoning");
243
+ })();
@@ -0,0 +1,148 @@
1
+ import { openai } from "@ai-sdk/openai";
2
+ import { streamObject } from "ai";
3
+ import { z } from "zod";
4
+ import { GraphEngine } from "./graph/engine";
5
+ import { Action, GraphDefinition, Node, SharedState } from "./types";
6
+ import { setupGraphsWithActions } from "./utils/setup-graphs";
7
+ import { stringifyZodSchema } from "./utils/stringifiy-zod-schema";
8
+
9
+ // ---- I. Create a simple workflow ----
10
+ // 1. Define the context
11
+ type Context = {
12
+ messages: string;
13
+ };
14
+
15
+ // // 2. Define the graph
16
+
17
+ // ---- II. Create an LLM to select the
18
+
19
+ // 2. Define the graph with a name
20
+ const graphDefinitionA: GraphDefinition<Context> = {
21
+ name: "get-news", // Assign a name to match the workflow
22
+ entryNode: "get-news",
23
+ nodes: {
24
+ "get-news": {
25
+ name: "get-news",
26
+ description: "Get news",
27
+ schema: z.object({
28
+ query: z.string(),
29
+ }),
30
+ execute: async () => {
31
+ return { messages: "Hello, world!" };
32
+ },
33
+ relationships: [{ name: "end" }],
34
+ },
35
+ end: {
36
+ name: "end",
37
+ description: "End the graph",
38
+ execute: async () => {
39
+ return { messages: "Goodbye, world!" };
40
+ },
41
+ },
42
+ },
43
+ };
44
+
45
+ const graphDefinitionB: GraphDefinition<Context> = {
46
+ name: "security-analysis",
47
+ entryNode: "security-analysis",
48
+ nodes: {
49
+ "security-analysis": {
50
+ name: "security-analysis",
51
+ description: "Get news",
52
+ execute: async () => {
53
+ return { messages: "Hello, world!" };
54
+ },
55
+ relationships: [{ name: "end" }],
56
+ },
57
+ end: {
58
+ name: "end",
59
+ description: "End the graph",
60
+ execute: async () => {
61
+ return { messages: "Goodbye, world!" };
62
+ },
63
+ },
64
+ },
65
+ };
66
+ // 3. Define the initial state
67
+ const initialState: SharedState<Context> = {
68
+ messages: "",
69
+ };
70
+
71
+ // 3. Define the initial state
72
+ const initialStateB: SharedState<Context> = {
73
+ messages: "",
74
+ };
75
+ const graphMaps = [graphDefinitionA, graphDefinitionB];
76
+
77
+ // ---- II. Create a node with LLM
78
+ (async () => {
79
+ const prompt =
80
+ "Salut quelles sont les news sur bitcoin ? et fais une analyse de sécurité";
81
+ // Dynamically extract start nodes from each graph definition in graphMaps
82
+ const startNodesSchema = graphMaps.map(
83
+ (graphDefinition) => graphDefinition.nodes[graphDefinition.entryNode]
84
+ );
85
+
86
+ // Pass the start nodes into stringifyZodSchema
87
+ const system = `You can select multiple workflows.
88
+ Here the available workflows and parameters:
89
+ workflows:${stringifyZodSchema(startNodesSchema)}`;
90
+ console.log(system);
91
+
92
+ const llm = await streamObject({
93
+ model: openai("gpt-4o"),
94
+ prompt,
95
+ schema: z.object({
96
+ actions: z.array(
97
+ z.object({
98
+ name: z.string(),
99
+ parameters: z.array(
100
+ z.object({
101
+ name: z.string(),
102
+ value: z.any(),
103
+ })
104
+ ),
105
+ })
106
+ ),
107
+ response: z.string(),
108
+ }),
109
+ system,
110
+ });
111
+
112
+ for await (const chunk of llm.partialObjectStream) {
113
+ if (chunk.response) {
114
+ console.log(chunk.response);
115
+ }
116
+ }
117
+
118
+ const actions = (await llm.object).actions;
119
+ console.log(actions);
120
+
121
+ const selectedWorkflows = (await llm.object).actions as Action[];
122
+ console.dir(llm.object, { depth: null });
123
+ // Define the base states
124
+ const baseStateMapping: Record<string, SharedState<Context>> = {
125
+ "get-news": initialState,
126
+ "security-analysis": initialStateB,
127
+ // Add other workflows and their base states as needed
128
+ };
129
+
130
+ const {
131
+ initialStates,
132
+ graphs: selectedGraphs,
133
+ startNodes,
134
+ } = setupGraphsWithActions(selectedWorkflows, baseStateMapping, graphMaps);
135
+
136
+ // Execute graphs with dynamically determined initial states
137
+ GraphEngine.executeGraphsInParallel<Context>(
138
+ selectedGraphs,
139
+ startNodes,
140
+ initialStates,
141
+ (graph) => {
142
+ console.log(`Graph ${graph.name} updated`, graph.getState());
143
+ },
144
+ (error, nodeName, state) => {
145
+ console.error(`Erreur dans ${nodeName}`, error, state);
146
+ }
147
+ );
148
+ })();
@@ -0,0 +1,201 @@
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 __asyncValues = (this && this.__asyncValues) || function (o) {
12
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
13
+ var m = o[Symbol.asyncIterator], i;
14
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
15
+ function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
16
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
17
+ };
18
+ Object.defineProperty(exports, "__esModule", { value: true });
19
+ const openai_1 = require("@ai-sdk/openai");
20
+ const ai_1 = require("ai");
21
+ const ethers_1 = require("ethers");
22
+ const zod_1 = require("zod");
23
+ const engine_1 = require("./graph/engine");
24
+ const index_copy_1 = require("./index copy");
25
+ const setup_graphs_1 = require("./utils/setup-graphs");
26
+ const stringifiy_zod_schema_1 = require("./utils/stringifiy-zod-schema");
27
+ // // 2. Define the graph
28
+ // ---- II. Create an LLM to select the
29
+ // 2. Define the graph with a name
30
+ const graphDefinitionA = {
31
+ name: "prepare-evm-transaction", // Assign a name to match the workflow
32
+ entryNode: "prepare-evm-transaction",
33
+ nodes: {
34
+ "prepare-evm-transaction": {
35
+ name: "prepare-evm-transaction",
36
+ description: "Prepare a transaction for the user to sign.",
37
+ schema: zod_1.z.object({
38
+ to: zod_1.z.string(),
39
+ value: zod_1.z
40
+ .string()
41
+ .describe("Ask the user for the amount to send, if not specified"),
42
+ chain: zod_1.z
43
+ .string()
44
+ .describe("Examples networks: ethereum, arbitrum, base. IMPORTANT: You must respect the network name."),
45
+ }),
46
+ execute: (params, state) => __awaiter(void 0, void 0, void 0, function* () {
47
+ console.log("💰 Prepare transaction", { params, state });
48
+ const networkConfig = index_copy_1.networkConfigs[params.chain.toLowerCase()];
49
+ if (!networkConfig) {
50
+ throw new Error(`Network ${params.chain} not found`);
51
+ }
52
+ return {
53
+ to: params.to,
54
+ value: (0, ethers_1.parseEther)(params.value).toString(),
55
+ chain: {
56
+ id: networkConfig.id || 0,
57
+ rpc: networkConfig.rpc,
58
+ },
59
+ type: "transfer",
60
+ };
61
+ }),
62
+ },
63
+ },
64
+ };
65
+ const graphDefinitionB = {
66
+ name: "security-analysis",
67
+ entryNode: "security-analysis",
68
+ nodes: {
69
+ "security-analysis": {
70
+ name: "security-analysis",
71
+ description: "Get news",
72
+ execute: () => __awaiter(void 0, void 0, void 0, function* () {
73
+ return { messages: "Hello, world!" };
74
+ }),
75
+ relationships: [{ name: "end" }],
76
+ },
77
+ end: {
78
+ name: "end",
79
+ description: "End the graph",
80
+ execute: () => __awaiter(void 0, void 0, void 0, function* () {
81
+ return {
82
+ messages: "Here the security analysis of Bitcoin: Bitcoin is a good investment",
83
+ };
84
+ }),
85
+ },
86
+ },
87
+ };
88
+ // 3. Define the initial state
89
+ const initialState = {
90
+ messages: "",
91
+ reasoning: true,
92
+ };
93
+ const graphMaps = [
94
+ graphDefinitionA,
95
+ graphDefinitionB,
96
+ // Add other graphs
97
+ ];
98
+ // ---- II. Create a node with LLM
99
+ (() => __awaiter(void 0, void 0, void 0, function* () {
100
+ const prompt = "je veux envoyer 0.0001 eth à 0x123 sur ethereum";
101
+ // Dynamically extract start nodes from each graph definition in graphMaps
102
+ const reasoningGraphDefinition = {
103
+ name: "reasoning",
104
+ entryNode: "reasoning",
105
+ nodes: {
106
+ reasoning: {
107
+ name: "reasoning",
108
+ description: "Reasoning",
109
+ execute: (params, state) => __awaiter(void 0, void 0, void 0, function* () {
110
+ var _a, e_1, _b, _c;
111
+ console.log("Reasoning", { params, state });
112
+ const startNodesSchema = graphMaps.map((graphDefinition) => graphDefinition.nodes[graphDefinition.entryNode]);
113
+ // Pass the start nodes into stringifyZodSchema
114
+ const system = `You are a wallet assistant. Don't reuse the same workflow multiple times.
115
+ Here the available workflows and parameters:
116
+ workflows:${(0, stringifiy_zod_schema_1.stringifyZodSchema)(startNodesSchema)}`;
117
+ console.log(system);
118
+ const llm = yield (0, ai_1.streamObject)({
119
+ model: (0, openai_1.openai)("gpt-4o"),
120
+ prompt,
121
+ schema: zod_1.z.object({
122
+ actions: zod_1.z.array(zod_1.z.object({
123
+ name: zod_1.z.string(),
124
+ parameters: zod_1.z.array(zod_1.z.object({
125
+ name: zod_1.z.string(),
126
+ value: zod_1.z.any(),
127
+ })),
128
+ })),
129
+ response: zod_1.z.string(),
130
+ }),
131
+ system,
132
+ });
133
+ console.dir(llm.object, { depth: null });
134
+ try {
135
+ for (var _d = true, _e = __asyncValues(llm.partialObjectStream), _f; _f = yield _e.next(), _a = _f.done, !_a; _d = true) {
136
+ _c = _f.value;
137
+ _d = false;
138
+ const chunk = _c;
139
+ if (chunk.response) {
140
+ // console.log(chunk.response);
141
+ }
142
+ }
143
+ }
144
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
145
+ finally {
146
+ try {
147
+ if (!_d && !_a && (_b = _e.return)) yield _b.call(_e);
148
+ }
149
+ finally { if (e_1) throw e_1.error; }
150
+ }
151
+ const actions = (yield llm.object).actions;
152
+ console.log({ actions });
153
+ const selectedWorkflows = (yield llm.object).actions;
154
+ return {
155
+ messages: "Hello, world!",
156
+ actions: selectedWorkflows,
157
+ };
158
+ }),
159
+ condition: (state) => {
160
+ return state.reasoning === true;
161
+ },
162
+ relationships: [{ name: "actions" }],
163
+ },
164
+ actions: {
165
+ name: "actions",
166
+ description: "Actions",
167
+ execute: (parameters, state) => __awaiter(void 0, void 0, void 0, function* () {
168
+ if (!state.actions) {
169
+ throw new Error("No actions found");
170
+ }
171
+ const baseStateMapping = {
172
+ "prepare-evm-transaction": initialState,
173
+ // Add other workflows and their base states as needed
174
+ };
175
+ const { initialStates, graphs: selectedGraphs, startNodes, } = (0, setup_graphs_1.setupGraphsWithActions)(state.actions, baseStateMapping, graphMaps);
176
+ // Execute graphs with dynamically determined initial states
177
+ const results = yield engine_1.GraphEngine.executeGraphsInSequence(selectedGraphs, startNodes, initialStates, (graph) => {
178
+ console.log(`Graph ${graph.name} updated`, graph.getState());
179
+ }, (error, nodeName, state) => {
180
+ console.error(`Erreur dans ${nodeName}`, error, state);
181
+ });
182
+ console.log({ results });
183
+ return {
184
+ messages: "Hello, world!",
185
+ results,
186
+ };
187
+ }),
188
+ condition: (state) => {
189
+ if (state.reasoning === true &&
190
+ state.actions &&
191
+ state.actions.length > 0) {
192
+ return true;
193
+ }
194
+ return false;
195
+ },
196
+ },
197
+ },
198
+ };
199
+ const reasoningGraph = new engine_1.GraphEngine(reasoningGraphDefinition);
200
+ yield reasoningGraph.execute(initialState, "reasoning");
201
+ }))();