@ai.ntellect/core 0.6.7 → 0.6.8

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.
@@ -1,5 +1,5 @@
1
1
  import { openai } from "@ai-sdk/openai";
2
- import { streamObject } from "ai";
2
+ import { generateObject } from "ai";
3
3
  import { parseEther } from "ethers";
4
4
  import { z } from "zod";
5
5
  import { GraphEngine } from "./graph/engine";
@@ -10,8 +10,7 @@ import { stringifyZodSchema } from "./utils/stringifiy-zod-schema";
10
10
  // ---- I. Create a simple workflow ----
11
11
  // 1. Define the context
12
12
  type MainContext = {
13
- messages: string;
14
- reasoning?: boolean;
13
+ results?: Record<string, CombinedContext>[];
15
14
  actions?: Action[];
16
15
  };
17
16
 
@@ -25,9 +24,7 @@ type ContextA = {
25
24
  type: string;
26
25
  };
27
26
 
28
- type ContextB = {
29
- messages: string;
30
- };
27
+ type ContextB = {};
31
28
 
32
29
  // // 2. Define the graph
33
30
 
@@ -52,17 +49,18 @@ const graphDefinitionA: GraphDefinition<ContextA> = {
52
49
  "Examples networks: ethereum, arbitrum, base. IMPORTANT: You must respect the network name."
53
50
  ),
54
51
  }),
55
- execute: async (params, state) => {
56
- console.log("💰 Prepare transaction", { params, state });
57
- const networkConfig = networkConfigs[params.chain.toLowerCase()];
52
+ execute: async (state) => {
53
+ console.log("💰 Prepare transaction", { state });
54
+ const networkConfig =
55
+ networkConfigs[(state.chain as any).toLowerCase()];
58
56
 
59
57
  if (!networkConfig) {
60
- throw new Error(`Network ${params.chain} not found`);
58
+ throw new Error(`Network ${state.chain} not found`);
61
59
  }
62
60
 
63
61
  return {
64
- to: params.to,
65
- value: parseEther(params.value).toString(),
62
+ to: state.to,
63
+ value: parseEther(state.value).toString(),
66
64
  chain: {
67
65
  id: networkConfig.id || 0,
68
66
  rpc: networkConfig.rpc,
@@ -99,10 +97,7 @@ const graphDefinitionB: GraphDefinition<ContextB> = {
99
97
  },
100
98
  };
101
99
  // 3. Define the initial state
102
- const initialState: SharedState<MainContext> = {
103
- messages: "",
104
- reasoning: true,
105
- };
100
+ const initialState: SharedState<MainContext> = {};
106
101
  type CombinedContext = ContextA | ContextB;
107
102
 
108
103
  const graphMaps: GraphDefinition<CombinedContext>[] = [
@@ -123,8 +118,8 @@ const graphMaps: GraphDefinition<CombinedContext>[] = [
123
118
  reasoning: {
124
119
  name: "reasoning",
125
120
  description: "Reasoning",
126
- execute: async (params, state) => {
127
- console.log("Reasoning", { params, state });
121
+ execute: async (state) => {
122
+ console.log("Reasoning", { state });
128
123
  const startNodesSchema = graphMaps.map(
129
124
  (graphDefinition) =>
130
125
  graphDefinition.nodes[graphDefinition.entryNode]
@@ -137,7 +132,7 @@ const graphMaps: GraphDefinition<CombinedContext>[] = [
137
132
  workflows:${stringifyZodSchema(startNodesSchema)}`;
138
133
  console.log(system);
139
134
 
140
- const llm = await streamObject({
135
+ const llm = await generateObject({
141
136
  model: openai("gpt-4o"),
142
137
  prompt,
143
138
  schema: z.object({
@@ -158,12 +153,6 @@ const graphMaps: GraphDefinition<CombinedContext>[] = [
158
153
  });
159
154
  console.dir(llm.object, { depth: null });
160
155
 
161
- for await (const chunk of llm.partialObjectStream) {
162
- if (chunk.response) {
163
- // console.log(chunk.response);
164
- }
165
- }
166
-
167
156
  const actions = (await llm.object).actions;
168
157
  console.log({ actions });
169
158
 
@@ -173,15 +162,12 @@ const graphMaps: GraphDefinition<CombinedContext>[] = [
173
162
  actions: selectedWorkflows,
174
163
  };
175
164
  },
176
- condition: (state) => {
177
- return state.reasoning === true;
178
- },
179
165
  relationships: [{ name: "actions" }],
180
166
  },
181
167
  actions: {
182
168
  name: "actions",
183
169
  description: "Actions",
184
- execute: async (parameters, state) => {
170
+ execute: async (state) => {
185
171
  if (!state.actions) {
186
172
  throw new Error("No actions found");
187
173
  }
@@ -209,27 +195,25 @@ const graphMaps: GraphDefinition<CombinedContext>[] = [
209
195
  selectedGraphs,
210
196
  startNodes,
211
197
  initialStates,
198
+ state.actions,
212
199
  (graph) => {
213
200
  console.log(`Graph ${graph.name} updated`, graph.getState());
214
201
  },
215
- (error, nodeName, state) => {
202
+ (
203
+ error: Error,
204
+ nodeName: string,
205
+ state: SharedState<CombinedContext>
206
+ ) => {
216
207
  console.error(`Erreur dans ${nodeName}`, error, state);
217
208
  }
218
209
  );
219
210
 
220
- console.log({ results });
221
-
222
211
  return {
223
- messages: "Hello, world!",
224
- results,
212
+ actions: results,
225
213
  };
226
214
  },
227
215
  condition: (state) => {
228
- if (
229
- state.reasoning === true &&
230
- state.actions &&
231
- state.actions.length > 0
232
- ) {
216
+ if (state.actions && state.actions.length > 0) {
233
217
  return true;
234
218
  }
235
219
  return false;
@@ -239,5 +223,15 @@ const graphMaps: GraphDefinition<CombinedContext>[] = [
239
223
  };
240
224
 
241
225
  const reasoningGraph = new GraphEngine(reasoningGraphDefinition);
242
- await reasoningGraph.execute(initialState, "reasoning");
226
+ await reasoningGraph.execute(
227
+ initialState,
228
+ "reasoning",
229
+ (graph) => {
230
+ console.log("Main graph updated", graph.name);
231
+ console.dir(graph.getState(), { depth: null });
232
+ },
233
+ (error, nodeName, state) => {
234
+ console.error(`Erreur dans ${nodeName}`, error, state);
235
+ }
236
+ );
243
237
  })();
@@ -8,13 +8,6 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
8
8
  step((generator = generator.apply(thisArg, _arguments || [])).next());
9
9
  });
10
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
11
  Object.defineProperty(exports, "__esModule", { value: true });
19
12
  const openai_1 = require("@ai-sdk/openai");
20
13
  const ai_1 = require("ai");
@@ -43,15 +36,15 @@ const graphDefinitionA = {
43
36
  .string()
44
37
  .describe("Examples networks: ethereum, arbitrum, base. IMPORTANT: You must respect the network name."),
45
38
  }),
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()];
39
+ execute: (state) => __awaiter(void 0, void 0, void 0, function* () {
40
+ console.log("💰 Prepare transaction", { state });
41
+ const networkConfig = index_copy_1.networkConfigs[state.chain.toLowerCase()];
49
42
  if (!networkConfig) {
50
- throw new Error(`Network ${params.chain} not found`);
43
+ throw new Error(`Network ${state.chain} not found`);
51
44
  }
52
45
  return {
53
- to: params.to,
54
- value: (0, ethers_1.parseEther)(params.value).toString(),
46
+ to: state.to,
47
+ value: (0, ethers_1.parseEther)(state.value).toString(),
55
48
  chain: {
56
49
  id: networkConfig.id || 0,
57
50
  rpc: networkConfig.rpc,
@@ -86,10 +79,7 @@ const graphDefinitionB = {
86
79
  },
87
80
  };
88
81
  // 3. Define the initial state
89
- const initialState = {
90
- messages: "",
91
- reasoning: true,
92
- };
82
+ const initialState = {};
93
83
  const graphMaps = [
94
84
  graphDefinitionA,
95
85
  graphDefinitionB,
@@ -106,16 +96,15 @@ const graphMaps = [
106
96
  reasoning: {
107
97
  name: "reasoning",
108
98
  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 });
99
+ execute: (state) => __awaiter(void 0, void 0, void 0, function* () {
100
+ console.log("Reasoning", { state });
112
101
  const startNodesSchema = graphMaps.map((graphDefinition) => graphDefinition.nodes[graphDefinition.entryNode]);
113
102
  // Pass the start nodes into stringifyZodSchema
114
103
  const system = `You are a wallet assistant. Don't reuse the same workflow multiple times.
115
104
  Here the available workflows and parameters:
116
105
  workflows:${(0, stringifiy_zod_schema_1.stringifyZodSchema)(startNodesSchema)}`;
117
106
  console.log(system);
118
- const llm = yield (0, ai_1.streamObject)({
107
+ const llm = yield (0, ai_1.generateObject)({
119
108
  model: (0, openai_1.openai)("gpt-4o"),
120
109
  prompt,
121
110
  schema: zod_1.z.object({
@@ -131,23 +120,6 @@ const graphMaps = [
131
120
  system,
132
121
  });
133
122
  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
123
  const actions = (yield llm.object).actions;
152
124
  console.log({ actions });
153
125
  const selectedWorkflows = (yield llm.object).actions;
@@ -156,15 +128,12 @@ const graphMaps = [
156
128
  actions: selectedWorkflows,
157
129
  };
158
130
  }),
159
- condition: (state) => {
160
- return state.reasoning === true;
161
- },
162
131
  relationships: [{ name: "actions" }],
163
132
  },
164
133
  actions: {
165
134
  name: "actions",
166
135
  description: "Actions",
167
- execute: (parameters, state) => __awaiter(void 0, void 0, void 0, function* () {
136
+ execute: (state) => __awaiter(void 0, void 0, void 0, function* () {
168
137
  if (!state.actions) {
169
138
  throw new Error("No actions found");
170
139
  }
@@ -174,21 +143,17 @@ const graphMaps = [
174
143
  };
175
144
  const { initialStates, graphs: selectedGraphs, startNodes, } = (0, setup_graphs_1.setupGraphsWithActions)(state.actions, baseStateMapping, graphMaps);
176
145
  // Execute graphs with dynamically determined initial states
177
- const results = yield engine_1.GraphEngine.executeGraphsInSequence(selectedGraphs, startNodes, initialStates, (graph) => {
146
+ const results = yield engine_1.GraphEngine.executeGraphsInSequence(selectedGraphs, startNodes, initialStates, state.actions, (graph) => {
178
147
  console.log(`Graph ${graph.name} updated`, graph.getState());
179
148
  }, (error, nodeName, state) => {
180
149
  console.error(`Erreur dans ${nodeName}`, error, state);
181
150
  });
182
- console.log({ results });
183
151
  return {
184
- messages: "Hello, world!",
185
- results,
152
+ actions: results,
186
153
  };
187
154
  }),
188
155
  condition: (state) => {
189
- if (state.reasoning === true &&
190
- state.actions &&
191
- state.actions.length > 0) {
156
+ if (state.actions && state.actions.length > 0) {
192
157
  return true;
193
158
  }
194
159
  return false;
@@ -197,5 +162,10 @@ const graphMaps = [
197
162
  },
198
163
  };
199
164
  const reasoningGraph = new engine_1.GraphEngine(reasoningGraphDefinition);
200
- yield reasoningGraph.execute(initialState, "reasoning");
165
+ yield reasoningGraph.execute(initialState, "reasoning", (graph) => {
166
+ console.log("Main graph updated", graph.name);
167
+ console.dir(graph.getState(), { depth: null });
168
+ }, (error, nodeName, state) => {
169
+ console.error(`Erreur dans ${nodeName}`, error, state);
170
+ });
201
171
  }))();
@@ -44,7 +44,7 @@ class GraphEngine {
44
44
  throw new Error("Cycle détecté dans le workflow");
45
45
  }
46
46
  if (options === null || options === void 0 ? void 0 : options.initialState) {
47
- this.setState(options.initialState);
47
+ // this.setState(options.initialState);
48
48
  }
49
49
  }
50
50
  /**
@@ -189,7 +189,7 @@ class GraphEngine {
189
189
  */
190
190
  execute(state, startNode, onStream, onError) {
191
191
  return __awaiter(this, void 0, void 0, function* () {
192
- var _a, _b;
192
+ var _a;
193
193
  try {
194
194
  // Valide l'état initial via le schéma global (si défini)
195
195
  if (this.schema) {
@@ -209,7 +209,7 @@ class GraphEngine {
209
209
  this.executedNodes.add(currentNodeName);
210
210
  const currentNode = this.nodes.get(currentNodeName);
211
211
  if (!currentNode) {
212
- throw new Error(`Nœud ${currentNodeName} introuvable.`);
212
+ throw new Error(`Node ${currentNodeName} introuvable.`);
213
213
  }
214
214
  // Vérification de condition (si présente)
215
215
  if (currentNode.condition &&
@@ -224,8 +224,7 @@ class GraphEngine {
224
224
  node: currentNodeName,
225
225
  });
226
226
  }
227
- const params = (_a = currentNode.schema) === null || _a === void 0 ? void 0 : _a.parse(this.currentState);
228
- const newState = yield currentNode.execute(params || {}, this.currentState);
227
+ const newState = yield currentNode.execute(this.currentState);
229
228
  if (newState) {
230
229
  this.setState(newState);
231
230
  if (onStream)
@@ -268,7 +267,7 @@ class GraphEngine {
268
267
  }
269
268
  else {
270
269
  // Cas normal : un seul chemin
271
- currentNodeName = ((_b = relationsNodes[0]) === null || _b === void 0 ? void 0 : _b.name) || "";
270
+ currentNodeName = ((_a = relationsNodes[0]) === null || _a === void 0 ? void 0 : _a.name) || "";
272
271
  }
273
272
  }
274
273
  return this.getState();
@@ -568,17 +567,26 @@ class GraphEngine {
568
567
  * @param onError Callback d'erreur
569
568
  * @returns Tableau des états finaux de chaque graphe
570
569
  */
571
- static executeGraphsInSequence(graphs, startNodes, initialStates, onStream, onError) {
570
+ static executeGraphsInSequence(graphs, startNodes, initialStates, actions, // Pass actions here
571
+ onStream, onError) {
572
572
  return __awaiter(this, void 0, void 0, function* () {
573
+ // Return updated actions directly
573
574
  const finalStates = [];
574
575
  for (let i = 0; i < graphs.length; i++) {
575
576
  const graph = graphs[i];
576
577
  const startNode = startNodes[i];
577
578
  const initialState = initialStates[i];
578
579
  const result = yield graph.execute(initialState, startNode, onStream, onError);
579
- finalStates.push(result);
580
+ finalStates.push({
581
+ name: graph.name,
582
+ result,
583
+ });
580
584
  }
581
- return finalStates;
585
+ // Map results to actions
586
+ return actions.map((action) => {
587
+ const result = finalStates.find((state) => state.name === action.name);
588
+ return Object.assign(Object.assign({}, action), { result: result ? result.result : null });
589
+ });
582
590
  });
583
591
  }
584
592
  /**
package/graph/engine.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { Persistence, RealTimeNotifier } from "@/interfaces";
2
- import { GraphDefinition, Node, SharedState } from "@/types";
2
+ import { Action, GraphDefinition, Node, SharedState } from "@/types";
3
3
  import EventEmitter from "events";
4
4
  import { z } from "zod";
5
5
 
@@ -68,7 +68,7 @@ export class GraphEngine<T> {
68
68
  }
69
69
 
70
70
  if (options?.initialState) {
71
- this.setState(options.initialState);
71
+ // this.setState(options.initialState);
72
72
  }
73
73
  }
74
74
 
@@ -112,7 +112,6 @@ export class GraphEngine<T> {
112
112
  setNotifier(notifier: RealTimeNotifier): void {
113
113
  this.notifier = notifier;
114
114
  }
115
-
116
115
  /**
117
116
  * Charge un workflow à partir d'une définition.
118
117
  * @private
@@ -260,7 +259,7 @@ export class GraphEngine<T> {
260
259
  this.executedNodes.add(currentNodeName);
261
260
  const currentNode = this.nodes.get(currentNodeName);
262
261
  if (!currentNode) {
263
- throw new Error(`Nœud ${currentNodeName} introuvable.`);
262
+ throw new Error(`Node ${currentNodeName} introuvable.`);
264
263
  }
265
264
 
266
265
  // Vérification de condition (si présente)
@@ -280,12 +279,7 @@ export class GraphEngine<T> {
280
279
  });
281
280
  }
282
281
 
283
- const params = currentNode.schema?.parse(this.currentState);
284
- const newState = await currentNode.execute(
285
- params || {},
286
- this.currentState
287
- );
288
-
282
+ const newState = await currentNode.execute(this.currentState);
289
283
  if (newState) {
290
284
  this.setState(newState);
291
285
  if (onStream) onStream(this);
@@ -702,10 +696,12 @@ export class GraphEngine<T> {
702
696
  graphs: GraphEngine<U>[],
703
697
  startNodes: string[],
704
698
  initialStates: SharedState<U>[],
699
+ actions: Action[], // Pass actions here
705
700
  onStream?: (graph: GraphEngine<U>) => void,
706
701
  onError?: (error: Error, nodeName: string, state: SharedState<U>) => void
707
- ): Promise<SharedState<U>[]> {
708
- const finalStates: SharedState<U>[] = [];
702
+ ): Promise<Action[]> {
703
+ // Return updated actions directly
704
+ const finalStates: { name: string; result: SharedState<U> }[] = [];
709
705
 
710
706
  for (let i = 0; i < graphs.length; i++) {
711
707
  const graph = graphs[i];
@@ -717,10 +713,20 @@ export class GraphEngine<T> {
717
713
  onStream,
718
714
  onError
719
715
  );
720
- finalStates.push(result);
716
+ finalStates.push({
717
+ name: graph.name,
718
+ result,
719
+ });
721
720
  }
722
721
 
723
- return finalStates;
722
+ // Map results to actions
723
+ return actions.map((action) => {
724
+ const result = finalStates.find((state) => state.name === action.name);
725
+ return {
726
+ ...action,
727
+ result: result ? result.result : null,
728
+ };
729
+ });
724
730
  }
725
731
 
726
732
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ai.ntellect/core",
3
- "version": "0.6.7",
3
+ "version": "0.6.8",
4
4
  "description": "",
5
5
  "main": "dist/index.js",
6
6
  "scripts": {
package/types/index.ts CHANGED
@@ -209,7 +209,7 @@ export type SharedState<T> = T;
209
209
  export type Node<T, P = any> = {
210
210
  name: string;
211
211
  description?: string;
212
- execute: (params: P, state: SharedState<T>) => Promise<SharedState<T> | void>;
212
+ execute: (state: SharedState<T>) => Promise<SharedState<T> | void>;
213
213
  condition?: (state: SharedState<T>) => boolean;
214
214
  relationships?: NodeRelationship[];
215
215
  schema?: z.ZodSchema<P>;