@ai.ntellect/core 0.4.0 → 0.5.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 (39) hide show
  1. package/README.FR.md +624 -18
  2. package/README.md +127 -72
  3. package/agent/index.ts +57 -149
  4. package/agent/workflow/conditions.ts +16 -0
  5. package/agent/workflow/handlers/interpreter.handler.ts +48 -0
  6. package/agent/workflow/handlers/memory.handler.ts +106 -0
  7. package/agent/workflow/handlers/orchestrator.handler.ts +23 -0
  8. package/agent/workflow/handlers/queue.handler.ts +34 -0
  9. package/agent/workflow/handlers/scheduler.handler.ts +61 -0
  10. package/agent/workflow/index.ts +62 -0
  11. package/dist/agent/index.d.ts +1 -1
  12. package/dist/agent/index.js +3 -3
  13. package/{agent/tools → examples/actions}/get-rss.ts +8 -1
  14. package/examples/index.ts +10 -15
  15. package/index.html +42 -0
  16. package/llm/dynamic-condition/example.ts +36 -0
  17. package/llm/dynamic-condition/index.ts +108 -0
  18. package/llm/interpreter/context.ts +5 -12
  19. package/llm/interpreter/index.ts +20 -16
  20. package/llm/memory-manager/context.ts +4 -6
  21. package/llm/memory-manager/index.ts +32 -80
  22. package/llm/orchestrator/context.ts +5 -8
  23. package/llm/orchestrator/index.ts +62 -102
  24. package/llm/orchestrator/types.ts +2 -2
  25. package/package.json +3 -1
  26. package/script.js +167 -0
  27. package/services/{scheduler.ts → agenda.ts} +20 -35
  28. package/services/cache.ts +298 -0
  29. package/services/queue.ts +3 -3
  30. package/services/workflow.ts +491 -0
  31. package/t.ts +21 -129
  32. package/tsconfig.json +2 -1
  33. package/types.ts +91 -12
  34. package/utils/generate-object.ts +24 -12
  35. package/utils/inject-actions.ts +3 -3
  36. package/utils/state-manager.ts +25 -0
  37. package/bull.ts +0 -5
  38. package/services/redis-cache.ts +0 -128
  39. package/t.spec +0 -38
package/types.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { Embedding, EmbeddingModel, StreamTextResult } from "ai";
1
+ import { CoreMessage, Embedding, EmbeddingModel, StreamTextResult } from "ai";
2
2
  import { z } from "zod";
3
3
 
4
4
  export interface BaseLLM {
@@ -70,11 +70,6 @@ export type Behavior = {
70
70
  }[];
71
71
  };
72
72
 
73
- export type State = {
74
- userRequest: string;
75
- results: string;
76
- };
77
-
78
73
  export interface ActionSchema {
79
74
  name: string;
80
75
  description: string;
@@ -153,7 +148,10 @@ export interface CacheMemoryOptions {
153
148
  }
154
149
 
155
150
  export type GenerateObjectResponse = {
156
- shouldContinue: boolean;
151
+ processing: {
152
+ stop: boolean;
153
+ stopReason?: string;
154
+ };
157
155
  actions: Array<{
158
156
  name: string;
159
157
  parameters: Array<{
@@ -166,11 +164,7 @@ export type GenerateObjectResponse = {
166
164
  reason?: string;
167
165
  };
168
166
  }>;
169
- socialResponse?: {
170
- shouldRespond: boolean;
171
- response?: string;
172
- isPartialResponse?: boolean;
173
- };
167
+ response: string;
174
168
  interpreter?: string;
175
169
  };
176
170
 
@@ -286,3 +280,88 @@ export interface WorkflowPattern {
286
280
  }>;
287
281
  success: boolean;
288
282
  }
283
+
284
+ // État partagé
285
+ export type MyContext = {
286
+ prompt?: string;
287
+ processing: {
288
+ stop: boolean;
289
+ reason?: string;
290
+ };
291
+ actions?: {
292
+ name: string;
293
+ parameters: Record<string, any>;
294
+ result?: any;
295
+ error?: any;
296
+ scheduler?: {
297
+ isScheduled: boolean;
298
+ cronExpression?: string;
299
+ reason?: string;
300
+ };
301
+ }[];
302
+ interpreter?: string | null;
303
+ results?: any;
304
+ };
305
+
306
+ export interface SharedState<T> {
307
+ messages?: CoreMessage[]; // Historique des interactions
308
+ context: T;
309
+ }
310
+
311
+ export function mergeState<T>(
312
+ current: SharedState<T>,
313
+ updates: Partial<SharedState<T>>
314
+ ): SharedState<T> {
315
+ const uniqueMessages = new Map(
316
+ [...(current.messages || []), ...(updates.messages || [])].map((msg) => [
317
+ JSON.stringify(msg),
318
+ msg,
319
+ ])
320
+ );
321
+ return {
322
+ ...current,
323
+ context: { ...current.context, ...updates.context },
324
+ messages: Array.from(uniqueMessages.values()), // Messages uniques
325
+ };
326
+ }
327
+ export interface RetryConfig {
328
+ maxRetries: number;
329
+ retryDelay: number;
330
+ shouldRetry?: (error: Error) => boolean;
331
+ }
332
+
333
+ export interface Node<T> {
334
+ name: string;
335
+ description?: string;
336
+ execute: (state: SharedState<T>) => Promise<Partial<SharedState<T>>>;
337
+ condition?: (state: SharedState<T>) => boolean;
338
+ next?: string[];
339
+ events?: string[];
340
+ retry?: RetryConfig;
341
+ }
342
+
343
+ export interface Persistence<T> {
344
+ saveState(
345
+ graphName: string,
346
+ state: SharedState<T>,
347
+ currentNode: string
348
+ ): Promise<void>;
349
+ loadState(
350
+ graphName: string
351
+ ): Promise<{ state: SharedState<T>; currentNode: string } | null>;
352
+ }
353
+
354
+ export interface RealTimeNotifier {
355
+ notify(event: string, data: any): void;
356
+ }
357
+
358
+ export interface WorkflowDefinition<T> {
359
+ name: string;
360
+ nodes: {
361
+ [key: string]: Node<T> & {
362
+ condition?: (state: SharedState<T>) => boolean;
363
+ next?: string[];
364
+ };
365
+ };
366
+ entryNode: string;
367
+ }
@@ -1,4 +1,4 @@
1
- import { LanguageModelV1, generateText } from "ai";
1
+ import { CoreMessage, LanguageModelV1, generateText } from "ai";
2
2
  import { z } from "zod";
3
3
 
4
4
  export const describeZodSchema = (schema: z.ZodType): string => {
@@ -54,19 +54,16 @@ export const describeZodSchema = (schema: z.ZodType): string => {
54
54
  export const generateObject = async <T>(config: {
55
55
  model: LanguageModelV1;
56
56
  schema: z.ZodSchema;
57
- prompt: string;
58
57
  system: string;
59
58
  temperature: number;
59
+ prompt?: string;
60
+ messages?: CoreMessage[];
60
61
  }): Promise<{ object: T }> => {
61
62
  // Generate a detailed description of the schema
62
63
  const schemaDescription = describeZodSchema(config.schema);
63
64
 
64
- console.log("🔍 Schema Description:\n", schemaDescription);
65
-
66
- const response = await generateText({
67
- model: config.model,
68
- prompt: `${config.prompt}
69
-
65
+ const baseContext = `
66
+ ${config.system}
70
67
  EXPECTED SCHEMA:
71
68
  ${schemaDescription}
72
69
 
@@ -76,16 +73,31 @@ export const generateObject = async <T>(config: {
76
73
  "key": "value"
77
74
  }
78
75
  \`\`\`
79
-
76
+
80
77
  GOOD EXAMPLE:
81
78
  {
82
79
  "key": "value"
83
80
  }
84
-
85
- Output only the JSON schema, no 'triple quotes'json or any other text. Only the JSON schema.
86
- `,
81
+
82
+ OUTPUT ONLY THE JSON SCHEMA, NO 'TRIPLE QUOTES'JSON OR ANY OTHER TEXT. ONLY THE JSON SCHEMA.
83
+ `;
84
+
85
+ console.log("🔍 Generating object with context:");
86
+ console.log(`${config.prompt}\n${baseContext}\n`);
87
+ const response = await generateText({
88
+ model: config.model,
89
+ messages: !config.prompt
90
+ ? [
91
+ {
92
+ role: "system",
93
+ content: baseContext,
94
+ },
95
+ ...(config.messages ?? []),
96
+ ]
97
+ : undefined,
87
98
  system: config.system,
88
99
  temperature: config.temperature,
100
+ prompt: !config.prompt ? undefined : `${config.prompt}\n\n${baseContext}`,
89
101
  });
90
102
 
91
103
  try {
@@ -5,11 +5,11 @@ export const injectActions = (actions: ActionSchema[]) => {
5
5
  return actions.map((action) => {
6
6
  const parameters = action.parameters as z.ZodObject<any>;
7
7
  const schemaShape = Object.keys(parameters._def.shape()).join(", ");
8
- const actionString = `Name: ${action.name}, Description: ${
8
+ const actionString = `* ${action.name}( { ${schemaShape} }) (${
9
9
  action.description
10
- }, Arguments: { ${schemaShape} } ${
10
+ }) ${
11
11
  action.examples
12
- ? `Format examples: ${action.examples.map((example: any) => {
12
+ ? `Eg: ${action.examples.map((example: any) => {
13
13
  return JSON.stringify(example);
14
14
  })}`
15
15
  : ""
@@ -0,0 +1,25 @@
1
+ import { MyContext, SharedState } from "../types";
2
+
3
+ export class StateManager {
4
+ /**
5
+ * Updates the shared state while preserving immutability
6
+ * @param currentState Current shared state
7
+ * @param updates Partial updates to apply
8
+ * @returns Updated shared state
9
+ */
10
+ static updateState(
11
+ currentState: SharedState<MyContext>,
12
+ updates: Partial<SharedState<MyContext>>
13
+ ): SharedState<MyContext> {
14
+ const updatedState = {
15
+ ...currentState,
16
+ ...updates,
17
+ context: {
18
+ ...currentState.context,
19
+ ...(updates.context || {}),
20
+ },
21
+ };
22
+ console.log("🔄 Updated State:", updatedState);
23
+ return updatedState;
24
+ }
25
+ }
package/bull.ts DELETED
@@ -1,5 +0,0 @@
1
- import cron from "node-cron";
2
-
3
- cron.schedule("* * * * *", () => {
4
- console.log("running a task every minute");
5
- });
@@ -1,128 +0,0 @@
1
- import Redis from "ioredis";
2
- import cron from "node-cron";
3
-
4
- export interface CacheConfig {
5
- host: string;
6
- port: number;
7
- password?: string;
8
- ttl?: number; // Time to live in seconds (default 30 minutes)
9
- cleanupInterval?: string; // Cron expression (default every 30 minutes)
10
- }
11
-
12
- export class RedisCache {
13
- private redis: Redis;
14
- private readonly defaultTTL: number;
15
- private readonly cleanupJob: cron.ScheduledTask;
16
-
17
- constructor(config: CacheConfig) {
18
- this.redis = new Redis({
19
- host: config.host,
20
- port: config.port,
21
- password: config.password,
22
- });
23
-
24
- this.defaultTTL = config.ttl || 1800; // 30 minutes in seconds
25
-
26
- // Setup cleanup job (default: every 30 minutes)
27
- this.cleanupJob = cron.schedule(
28
- config.cleanupInterval || "*/30 * * * *",
29
- () => this.cleanup()
30
- );
31
- }
32
-
33
- /**
34
- * Store previous actions for a specific request
35
- */
36
- async storePreviousActions(requestId: string, actions: any[]): Promise<void> {
37
- const key = `previous_actions:${requestId}`;
38
- await this.redis.setex(
39
- key,
40
- this.defaultTTL,
41
- JSON.stringify({
42
- timestamp: new Date().toISOString(),
43
- actions,
44
- })
45
- );
46
- }
47
-
48
- /**
49
- * Get previous actions for a specific request
50
- */
51
- async getPreviousActions(requestId: string): Promise<any[]> {
52
- const key = `previous_actions:${requestId}`;
53
- const data = await this.redis.get(key);
54
- if (!data) return [];
55
-
56
- const parsed = JSON.parse(data);
57
- return parsed.actions;
58
- }
59
-
60
- /**
61
- * Store a recent message
62
- */
63
- async storeRecentMessage(
64
- message: string,
65
- metadata?: Record<string, any>
66
- ): Promise<void> {
67
- const id = crypto.randomUUID();
68
- const key = `recent_messages:${id}`;
69
- await this.redis.setex(
70
- key,
71
- this.defaultTTL,
72
- JSON.stringify({
73
- timestamp: new Date().toISOString(),
74
- message,
75
- metadata,
76
- })
77
- );
78
- }
79
-
80
- /**
81
- * Get recent messages
82
- */
83
- async getRecentMessages(limit: number = 10): Promise<any[]> {
84
- const keys = await this.redis.keys("recent_messages:*");
85
- if (!keys.length) return [];
86
-
87
- const messages = await Promise.all(
88
- keys.map(async (key) => {
89
- const data = await this.redis.get(key);
90
- return data ? JSON.parse(data) : null;
91
- })
92
- );
93
-
94
- return messages
95
- .filter(Boolean)
96
- .sort(
97
- (a, b) =>
98
- new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime()
99
- )
100
- .slice(0, limit);
101
- }
102
-
103
- /**
104
- * Cleanup expired keys
105
- */
106
- private async cleanup(): Promise<void> {
107
- console.log("🧹 Starting cache cleanup...");
108
- try {
109
- // Redis automatically removes expired keys
110
- // This is just for logging purposes
111
- const actionKeys = await this.redis.keys("previous_actions:*");
112
- const messageKeys = await this.redis.keys("recent_messages:*");
113
- console.log(
114
- `Cache status: ${actionKeys.length} actions, ${messageKeys.length} messages`
115
- );
116
- } catch (error) {
117
- console.error("❌ Cache cleanup error:", error);
118
- }
119
- }
120
-
121
- /**
122
- * Stop the cleanup job and close Redis connection
123
- */
124
- async close(): Promise<void> {
125
- this.cleanupJob.stop();
126
- await this.redis.quit();
127
- }
128
- }
package/t.spec DELETED
@@ -1,38 +0,0 @@
1
- # -*- mode: python ; coding: utf-8 -*-
2
-
3
-
4
- a = Analysis(
5
- ['t.py'],
6
- pathex=[],
7
- binaries=[],
8
- datas=[],
9
- hiddenimports=[],
10
- hookspath=[],
11
- hooksconfig={},
12
- runtime_hooks=[],
13
- excludes=[],
14
- noarchive=False,
15
- optimize=0,
16
- )
17
- pyz = PYZ(a.pure)
18
-
19
- exe = EXE(
20
- pyz,
21
- a.scripts,
22
- a.binaries,
23
- a.datas,
24
- [],
25
- name='t',
26
- debug=False,
27
- bootloader_ignore_signals=False,
28
- strip=False,
29
- upx=True,
30
- upx_exclude=[],
31
- runtime_tmpdir=None,
32
- console=True,
33
- disable_windowed_traceback=False,
34
- argv_emulation=False,
35
- target_arch=None,
36
- codesign_identity=None,
37
- entitlements_file=None,
38
- )