@ai.ntellect/core 0.3.1 → 0.4.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 (86) hide show
  1. package/.nvmrc +1 -0
  2. package/README.FR.md +201 -261
  3. package/README.md +208 -260
  4. package/agent/index.ts +204 -185
  5. package/agent/tools/get-rss.ts +64 -0
  6. package/bull.ts +5 -0
  7. package/dist/agent/index.d.ts +29 -22
  8. package/dist/agent/index.js +124 -97
  9. package/dist/agent/tools/get-rss.d.ts +16 -0
  10. package/dist/agent/tools/get-rss.js +62 -0
  11. package/dist/bull.d.ts +1 -0
  12. package/dist/bull.js +9 -0
  13. package/dist/examples/index.d.ts +2 -0
  14. package/dist/examples/index.js +89 -0
  15. package/dist/llm/interpreter/context.d.ts +5 -22
  16. package/dist/llm/interpreter/context.js +8 -9
  17. package/dist/llm/interpreter/index.d.ts +9 -5
  18. package/dist/llm/interpreter/index.js +55 -48
  19. package/dist/llm/memory-manager/context.d.ts +2 -0
  20. package/dist/llm/memory-manager/context.js +22 -0
  21. package/dist/llm/memory-manager/index.d.ts +17 -0
  22. package/dist/llm/memory-manager/index.js +107 -0
  23. package/dist/llm/orchestrator/context.d.ts +2 -10
  24. package/dist/llm/orchestrator/context.js +19 -16
  25. package/dist/llm/orchestrator/index.d.ts +36 -21
  26. package/dist/llm/orchestrator/index.js +122 -88
  27. package/dist/llm/orchestrator/types.d.ts +12 -0
  28. package/dist/llm/orchestrator/types.js +2 -0
  29. package/dist/memory/cache.d.ts +6 -6
  30. package/dist/memory/cache.js +35 -42
  31. package/dist/memory/persistent.d.ts +9 -13
  32. package/dist/memory/persistent.js +94 -114
  33. package/dist/services/redis-cache.d.ts +37 -0
  34. package/dist/services/redis-cache.js +93 -0
  35. package/dist/services/scheduler.d.ts +40 -0
  36. package/dist/services/scheduler.js +99 -0
  37. package/dist/services/telegram-monitor.d.ts +0 -0
  38. package/dist/services/telegram-monitor.js +118 -0
  39. package/dist/test.d.ts +0 -167
  40. package/dist/test.js +437 -372
  41. package/dist/types.d.ts +60 -9
  42. package/dist/utils/generate-object.d.ts +12 -0
  43. package/dist/utils/generate-object.js +90 -0
  44. package/dist/utils/header-builder.d.ts +11 -0
  45. package/dist/utils/header-builder.js +34 -0
  46. package/dist/utils/inject-actions.js +2 -2
  47. package/dist/utils/queue-item-transformer.d.ts +2 -2
  48. package/dist/utils/schema-generator.d.ts +16 -0
  49. package/dist/utils/schema-generator.js +46 -0
  50. package/examples/index.ts +103 -0
  51. package/llm/interpreter/context.ts +20 -8
  52. package/llm/interpreter/index.ts +81 -54
  53. package/llm/memory-manager/context.ts +21 -0
  54. package/llm/memory-manager/index.ts +163 -0
  55. package/llm/orchestrator/context.ts +20 -13
  56. package/llm/orchestrator/index.ts +210 -130
  57. package/llm/orchestrator/types.ts +14 -0
  58. package/memory/cache.ts +41 -55
  59. package/memory/persistent.ts +121 -149
  60. package/package.json +11 -2
  61. package/services/redis-cache.ts +128 -0
  62. package/services/scheduler.ts +128 -0
  63. package/services/telegram-monitor.ts +138 -0
  64. package/t.py +79 -0
  65. package/t.spec +38 -0
  66. package/types.ts +64 -9
  67. package/utils/generate-object.ts +105 -0
  68. package/utils/header-builder.ts +40 -0
  69. package/utils/inject-actions.ts +4 -6
  70. package/utils/queue-item-transformer.ts +2 -1
  71. package/utils/schema-generator.ts +73 -0
  72. package/agent/handlers/ActionHandler.ts +0 -48
  73. package/agent/handlers/ConfirmationHandler.ts +0 -37
  74. package/agent/handlers/EventHandler.ts +0 -35
  75. package/dist/agent/handlers/ActionHandler.d.ts +0 -8
  76. package/dist/agent/handlers/ActionHandler.js +0 -36
  77. package/dist/agent/handlers/ConfirmationHandler.d.ts +0 -7
  78. package/dist/agent/handlers/ConfirmationHandler.js +0 -31
  79. package/dist/agent/handlers/EventHandler.d.ts +0 -10
  80. package/dist/agent/handlers/EventHandler.js +0 -34
  81. package/dist/llm/evaluator/context.d.ts +0 -10
  82. package/dist/llm/evaluator/context.js +0 -22
  83. package/dist/llm/evaluator/index.d.ts +0 -16
  84. package/dist/llm/evaluator/index.js +0 -151
  85. package/llm/evaluator/context.ts +0 -21
  86. package/llm/evaluator/index.ts +0 -194
@@ -0,0 +1,105 @@
1
+ import { LanguageModelV1, generateText } from "ai";
2
+ import { z } from "zod";
3
+
4
+ export const describeZodSchema = (schema: z.ZodType): string => {
5
+ if (schema instanceof z.ZodObject) {
6
+ const entries = Object.entries(schema.shape);
7
+ const fields = entries.map(([key, value]) => {
8
+ const description = (value as any)._def.description || "";
9
+ const fieldSchema = describeZodSchema(value as z.ZodType);
10
+ return description
11
+ ? `${key}: ${fieldSchema} // ${description}`
12
+ : `${key}: ${fieldSchema}`;
13
+ });
14
+ return `z.object({${fields.join(", ")}})`;
15
+ }
16
+
17
+ if (schema instanceof z.ZodArray) {
18
+ return `z.array(${describeZodSchema(schema.element)})`;
19
+ }
20
+
21
+ if (schema instanceof z.ZodString) {
22
+ return "z.string()";
23
+ }
24
+
25
+ if (schema instanceof z.ZodNumber) {
26
+ return "z.number()";
27
+ }
28
+
29
+ if (schema instanceof z.ZodBoolean) {
30
+ return "z.boolean()";
31
+ }
32
+
33
+ if (schema instanceof z.ZodOptional) {
34
+ return `z.optional(${describeZodSchema(schema._def.innerType)})`;
35
+ }
36
+
37
+ if (schema instanceof z.ZodUnion) {
38
+ return `z.union([${schema._def.options
39
+ .map((option: z.ZodType) => describeZodSchema(option))
40
+ .join(", ")}])`;
41
+ }
42
+
43
+ if (schema instanceof z.ZodEnum) {
44
+ return `z.enum(${JSON.stringify(schema._def.values)})`;
45
+ }
46
+
47
+ if (schema instanceof z.ZodLiteral) {
48
+ return `z.literal(${JSON.stringify(schema._def.value)})`;
49
+ }
50
+
51
+ return "z.unknown()"; // Fallback for unknown types
52
+ };
53
+
54
+ export const generateObject = async <T>(config: {
55
+ model: LanguageModelV1;
56
+ schema: z.ZodSchema;
57
+ prompt: string;
58
+ system: string;
59
+ temperature: number;
60
+ }): Promise<{ object: T }> => {
61
+ // Generate a detailed description of the schema
62
+ const schemaDescription = describeZodSchema(config.schema);
63
+
64
+ console.log("🔍 Schema Description:\n", schemaDescription);
65
+
66
+ const response = await generateText({
67
+ model: config.model,
68
+ prompt: `${config.prompt}
69
+
70
+ EXPECTED SCHEMA:
71
+ ${schemaDescription}
72
+
73
+ BAD EXAMPLE:
74
+ \`\`\`json
75
+ {
76
+ "key": "value"
77
+ }
78
+ \`\`\`
79
+
80
+ GOOD EXAMPLE:
81
+ {
82
+ "key": "value"
83
+ }
84
+
85
+ Output only the JSON schema, no 'triple quotes'json or any other text. Only the JSON schema.
86
+ `,
87
+ system: config.system,
88
+ temperature: config.temperature,
89
+ });
90
+
91
+ try {
92
+ // Clean the response text from any markdown or code block markers
93
+ const cleanText = response.text
94
+ .replace(/```json\s*/g, "")
95
+ .replace(/```\s*$/g, "")
96
+ .trim();
97
+
98
+ const parsedResponse = JSON.parse(cleanText);
99
+ const validatedResponse = config.schema.parse(parsedResponse);
100
+ return { object: validatedResponse as T };
101
+ } catch (error) {
102
+ console.error("Error parsing or validating JSON response:", error);
103
+ throw new Error("Failed to generate valid JSON response");
104
+ }
105
+ };
@@ -0,0 +1,40 @@
1
+ type HeaderValue = string | string[] | undefined;
2
+
3
+ export class LLMHeaderBuilder {
4
+ private headers: Map<string, HeaderValue>;
5
+ private _result: string;
6
+
7
+ constructor() {
8
+ this.headers = new Map();
9
+ this._result = "";
10
+ }
11
+
12
+ addHeader(key: string, value: HeaderValue): LLMHeaderBuilder {
13
+ if (Array.isArray(value)) {
14
+ this.headers.set(key, value.join("\n"));
15
+ } else {
16
+ this.headers.set(key, value);
17
+ }
18
+
19
+ // Build result immediately
20
+ this._result = Array.from(this.headers.entries())
21
+ .filter(([_, value]) => value !== undefined)
22
+ .map(([key, value]) => `# ${key}: ${value}`)
23
+ .join("\n")
24
+ .trim();
25
+
26
+ return this;
27
+ }
28
+
29
+ valueOf(): string {
30
+ return this._result;
31
+ }
32
+
33
+ toString(): string {
34
+ return this._result;
35
+ }
36
+
37
+ static create(): LLMHeaderBuilder {
38
+ return new LLMHeaderBuilder();
39
+ }
40
+ }
@@ -7,13 +7,11 @@ export const injectActions = (actions: ActionSchema[]) => {
7
7
  const schemaShape = Object.keys(parameters._def.shape()).join(", ");
8
8
  const actionString = `Name: ${action.name}, Description: ${
9
9
  action.description
10
- }, Arguments (STRICTLY REQUIRED): { ${schemaShape} } ${
10
+ }, Arguments: { ${schemaShape} } ${
11
11
  action.examples
12
- ? `Format examples (MUST RESPECT): ${action.examples.map(
13
- (example: any) => {
14
- return JSON.stringify(example);
15
- }
16
- )}`
12
+ ? `Format examples: ${action.examples.map((example: any) => {
13
+ return JSON.stringify(example);
14
+ })}`
17
15
  : ""
18
16
  }`;
19
17
  return actionString;
@@ -1,5 +1,6 @@
1
1
  import {
2
2
  ActionData,
3
+ QueueItem,
3
4
  QueueItemParameter,
4
5
  QueueResult,
5
6
  TransformedQueueItem,
@@ -34,7 +35,7 @@ export class QueueItemTransformer {
34
35
 
35
36
  static transformActionsToQueueItems(
36
37
  actions: ActionData[] | undefined
37
- ): TransformedQueueItem[] | undefined {
38
+ ): QueueItem[] | undefined {
38
39
  return actions?.map((action) => this.transformActionToQueueItem(action));
39
40
  }
40
41
  }
@@ -0,0 +1,73 @@
1
+ import { z } from "zod";
2
+
3
+ export interface SchemaConfig {
4
+ schema: z.ZodType;
5
+ instructions?: string;
6
+ outputExamples?: {
7
+ input: string;
8
+ output: string;
9
+ }[];
10
+ }
11
+
12
+ export class SchemaGenerator {
13
+ static generate(config: SchemaConfig): {
14
+ schema: string;
15
+ instructions: string;
16
+ outputExamples: string;
17
+ } {
18
+ const {
19
+ schema,
20
+ instructions = "Output only the JSON schema, no 'triple quotes'json or any other text. Only the JSON schema.",
21
+ outputExamples = [],
22
+ } = config;
23
+
24
+ const getSchemaString = (schema: z.ZodType): string => {
25
+ if (schema instanceof z.ZodObject) {
26
+ const entries = Object.entries(schema.shape);
27
+ const fields = entries.map(([key, value]) => {
28
+ const description = (value as any)._def.description;
29
+ const schemaStr = getSchemaString(value as z.ZodType);
30
+ return description
31
+ ? `${key}: ${schemaStr} // ${description}`
32
+ : `${key}: ${schemaStr}`;
33
+ });
34
+ return `z.object({${fields.join(", ")}})`;
35
+ }
36
+
37
+ if (schema instanceof z.ZodArray) {
38
+ return `z.array(${getSchemaString(schema.element)})`;
39
+ }
40
+
41
+ if (schema instanceof z.ZodString) {
42
+ return "z.string()";
43
+ }
44
+
45
+ if (schema instanceof z.ZodNumber) {
46
+ return "z.number()";
47
+ }
48
+
49
+ if (schema instanceof z.ZodBoolean) {
50
+ return "z.boolean()";
51
+ }
52
+
53
+ // Fallback for other Zod types
54
+ return `z.unknown()`;
55
+ };
56
+
57
+ const schemaString = getSchemaString(schema);
58
+
59
+ return {
60
+ schema: schemaString,
61
+ instructions,
62
+ outputExamples: outputExamples
63
+ .map(
64
+ (example) =>
65
+ `Input: ${JSON.stringify(example.input)}, Output: ${JSON.stringify(
66
+ example.output
67
+ )}`
68
+ )
69
+ .join("\n")
70
+ .trim(),
71
+ };
72
+ }
73
+ }
@@ -1,48 +0,0 @@
1
- import { ActionQueueManager } from "../../services/queue";
2
- import {
3
- ActionSchema,
4
- ProcessPromptCallbacks,
5
- QueueItem,
6
- QueueResult,
7
- } from "../../types";
8
-
9
- export class ActionHandler {
10
- async executeActions(
11
- predefinedActions: QueueItem[],
12
- tools: ActionSchema[],
13
- callbacks?: ProcessPromptCallbacks
14
- ) {
15
- try {
16
- const queueManager = new ActionQueueManager(tools, {
17
- onActionStart: callbacks?.onActionStart,
18
- onActionComplete: callbacks?.onActionComplete,
19
- onQueueComplete: callbacks?.onQueueComplete,
20
- onConfirmationRequired: async (message: any) => {
21
- if (callbacks?.onConfirmationRequired) {
22
- return await callbacks.onConfirmationRequired(message);
23
- }
24
- return false;
25
- },
26
- });
27
-
28
- queueManager.addToQueue(predefinedActions);
29
-
30
- if (callbacks?.onQueueStart) {
31
- callbacks.onQueueStart(predefinedActions);
32
- }
33
-
34
- const results = await queueManager.processQueue();
35
- return { type: "success", data: results || [] };
36
- } catch (error) {
37
- console.error("Error processing prompt:", error);
38
- throw error;
39
- }
40
- }
41
-
42
- hasNonPrepareActions(actions: QueueResult[]): boolean {
43
- return (
44
- Array.isArray(actions) &&
45
- actions.some((action) => action.name?.split("-")[0] !== "prepare")
46
- );
47
- }
48
- }
@@ -1,37 +0,0 @@
1
- import EventEmitter from "events";
2
-
3
- export class ConfirmationHandler {
4
- private readonly CONFIRMATION_TIMEOUT = 5 * 60 * 1000; // 5 minutes
5
-
6
- constructor(private readonly eventEmitter: EventEmitter) {}
7
-
8
- async handleConfirmationRequest(message: string): Promise<boolean> {
9
- return new Promise((resolve) => {
10
- const confirmationId = Date.now().toString();
11
- const handleConfirmation = (data: any) => {
12
- if (data.confirmationId === confirmationId) {
13
- this.eventEmitter.removeListener(
14
- "confirmation-response",
15
- handleConfirmation
16
- );
17
- resolve(data.confirmed);
18
- }
19
- };
20
-
21
- this.eventEmitter.once("confirmation-response", handleConfirmation);
22
- this.eventEmitter.emit("orchestrator-update", {
23
- type: "confirmation-required",
24
- id: confirmationId,
25
- message,
26
- });
27
-
28
- setTimeout(() => {
29
- this.eventEmitter.removeListener(
30
- "confirmation-response",
31
- handleConfirmation
32
- );
33
- resolve(false);
34
- }, this.CONFIRMATION_TIMEOUT);
35
- });
36
- }
37
- }
@@ -1,35 +0,0 @@
1
- import EventEmitter from "events";
2
- import { IEventHandler, QueueItem, QueueResult } from "../../types";
3
-
4
- export class EventHandler implements IEventHandler {
5
- constructor(private readonly eventEmitter: EventEmitter) {}
6
-
7
- emitQueueStart(actions: QueueItem[]) {
8
- this.eventEmitter.emit("orchestrator-update", {
9
- type: "queue-start",
10
- actions,
11
- });
12
- }
13
-
14
- emitActionStart(action: QueueItem) {
15
- this.eventEmitter.emit("orchestrator-update", {
16
- type: "action-start",
17
- action: action.name,
18
- args: action.parameters,
19
- });
20
- }
21
-
22
- emitActionComplete(action: QueueResult) {
23
- this.eventEmitter.emit("orchestrator-update", {
24
- type: "action-complete",
25
- action: action.name,
26
- result: action.result,
27
- });
28
- }
29
-
30
- emitQueueComplete() {
31
- this.eventEmitter.emit("orchestrator-update", {
32
- type: "queue-complete",
33
- });
34
- }
35
- }
@@ -1,8 +0,0 @@
1
- import { ActionSchema, ProcessPromptCallbacks, QueueItem, QueueResult } from "../../types";
2
- export declare class ActionHandler {
3
- executeActions(predefinedActions: QueueItem[], tools: ActionSchema[], callbacks?: ProcessPromptCallbacks): Promise<{
4
- type: string;
5
- data: QueueResult[];
6
- }>;
7
- hasNonPrepareActions(actions: QueueResult[]): boolean;
8
- }
@@ -1,36 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ActionHandler = void 0;
4
- const queue_1 = require("../../services/queue");
5
- class ActionHandler {
6
- async executeActions(predefinedActions, tools, callbacks) {
7
- try {
8
- const queueManager = new queue_1.ActionQueueManager(tools, {
9
- onActionStart: callbacks?.onActionStart,
10
- onActionComplete: callbacks?.onActionComplete,
11
- onQueueComplete: callbacks?.onQueueComplete,
12
- onConfirmationRequired: async (message) => {
13
- if (callbacks?.onConfirmationRequired) {
14
- return await callbacks.onConfirmationRequired(message);
15
- }
16
- return false;
17
- },
18
- });
19
- queueManager.addToQueue(predefinedActions);
20
- if (callbacks?.onQueueStart) {
21
- callbacks.onQueueStart(predefinedActions);
22
- }
23
- const results = await queueManager.processQueue();
24
- return { type: "success", data: results || [] };
25
- }
26
- catch (error) {
27
- console.error("Error processing prompt:", error);
28
- throw error;
29
- }
30
- }
31
- hasNonPrepareActions(actions) {
32
- return (Array.isArray(actions) &&
33
- actions.some((action) => action.name?.split("-")[0] !== "prepare"));
34
- }
35
- }
36
- exports.ActionHandler = ActionHandler;
@@ -1,7 +0,0 @@
1
- import EventEmitter from "events";
2
- export declare class ConfirmationHandler {
3
- private readonly eventEmitter;
4
- private readonly CONFIRMATION_TIMEOUT;
5
- constructor(eventEmitter: EventEmitter);
6
- handleConfirmationRequest(message: string): Promise<boolean>;
7
- }
@@ -1,31 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ConfirmationHandler = void 0;
4
- class ConfirmationHandler {
5
- constructor(eventEmitter) {
6
- this.eventEmitter = eventEmitter;
7
- this.CONFIRMATION_TIMEOUT = 5 * 60 * 1000; // 5 minutes
8
- }
9
- async handleConfirmationRequest(message) {
10
- return new Promise((resolve) => {
11
- const confirmationId = Date.now().toString();
12
- const handleConfirmation = (data) => {
13
- if (data.confirmationId === confirmationId) {
14
- this.eventEmitter.removeListener("confirmation-response", handleConfirmation);
15
- resolve(data.confirmed);
16
- }
17
- };
18
- this.eventEmitter.once("confirmation-response", handleConfirmation);
19
- this.eventEmitter.emit("orchestrator-update", {
20
- type: "confirmation-required",
21
- id: confirmationId,
22
- message,
23
- });
24
- setTimeout(() => {
25
- this.eventEmitter.removeListener("confirmation-response", handleConfirmation);
26
- resolve(false);
27
- }, this.CONFIRMATION_TIMEOUT);
28
- });
29
- }
30
- }
31
- exports.ConfirmationHandler = ConfirmationHandler;
@@ -1,10 +0,0 @@
1
- import EventEmitter from "events";
2
- import { IEventHandler, QueueItem, QueueResult } from "../../types";
3
- export declare class EventHandler implements IEventHandler {
4
- private readonly eventEmitter;
5
- constructor(eventEmitter: EventEmitter);
6
- emitQueueStart(actions: QueueItem[]): void;
7
- emitActionStart(action: QueueItem): void;
8
- emitActionComplete(action: QueueResult): void;
9
- emitQueueComplete(): void;
10
- }
@@ -1,34 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.EventHandler = void 0;
4
- class EventHandler {
5
- constructor(eventEmitter) {
6
- this.eventEmitter = eventEmitter;
7
- }
8
- emitQueueStart(actions) {
9
- this.eventEmitter.emit("orchestrator-update", {
10
- type: "queue-start",
11
- actions,
12
- });
13
- }
14
- emitActionStart(action) {
15
- this.eventEmitter.emit("orchestrator-update", {
16
- type: "action-start",
17
- action: action.name,
18
- args: action.parameters,
19
- });
20
- }
21
- emitActionComplete(action) {
22
- this.eventEmitter.emit("orchestrator-update", {
23
- type: "action-complete",
24
- action: action.name,
25
- result: action.result,
26
- });
27
- }
28
- emitQueueComplete() {
29
- this.eventEmitter.emit("orchestrator-update", {
30
- type: "queue-complete",
31
- });
32
- }
33
- }
34
- exports.EventHandler = EventHandler;
@@ -1,10 +0,0 @@
1
- export declare const evaluatorContext: {
2
- behavior: {
3
- language: string;
4
- role: string;
5
- guidelines: {
6
- important: string[];
7
- warnings: string[];
8
- };
9
- };
10
- };
@@ -1,22 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.evaluatorContext = void 0;
4
- exports.evaluatorContext = {
5
- behavior: {
6
- language: "user_language",
7
- role: "Your role is to verify if the goal has been achieved and make a response or suggest next actions.",
8
- guidelines: {
9
- important: [
10
- "Verify if all required actions were executed successfully.",
11
- "Check if the results align with the initial goal.",
12
- "If you retrieved the informations from your internal knowledge base, no need to store them in 'extraInformationsToStore'.",
13
- "Store ONLY extra new needed informations in 'extraInformationsToStore' (choose the most relevant informations and memory type: episodic, semantic, or procedural).",
14
- ],
15
- warnings: [
16
- "NEVER store an old data you retrieve from your internal knowledge base.",
17
- "NEVER make assumptions about missing data.",
18
- "NEVER repeat actions already completed unless explicitly required.",
19
- ],
20
- },
21
- },
22
- };
@@ -1,16 +0,0 @@
1
- import { CacheMemory } from "../../memory/cache";
2
- import { PersistentMemory } from "../../memory/persistent";
3
- import { ActionSchema, State } from "../../types";
4
- import { Interpreter } from "../interpreter";
5
- export declare class Evaluator {
6
- private readonly model;
7
- tools: ActionSchema[];
8
- private memory;
9
- private interpreters;
10
- constructor(tools: ActionSchema[], memory: {
11
- persistent: PersistentMemory;
12
- cache?: CacheMemory;
13
- }, interpreters: Interpreter[]);
14
- composeContext(state: State): string;
15
- process(prompt: string, results: string): Promise<any>;
16
- }