@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
package/dist/types.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { Embedding, StreamTextResult } from "ai";
1
+ import { Embedding, EmbeddingModel, StreamTextResult } from "ai";
2
2
  import { z } from "zod";
3
3
  export interface BaseLLM {
4
4
  process: (prompt: string) => Promise<string | object>;
@@ -118,20 +118,41 @@ export interface SummarizerAgent {
118
118
  streamProcess: (results: object, onFinish?: (event: any) => void) => Promise<StreamTextResult<Record<string, any>>>;
119
119
  }
120
120
  export interface CacheMemoryOptions {
121
+ embeddingModel: EmbeddingModel<string>;
121
122
  cacheTTL?: number;
122
123
  redisUrl?: string;
123
124
  cachePrefix?: string;
124
125
  }
126
+ export type GenerateObjectResponse = {
127
+ shouldContinue: boolean;
128
+ actions: Array<{
129
+ name: string;
130
+ parameters: Array<{
131
+ name: string;
132
+ value: any;
133
+ }>;
134
+ scheduler?: {
135
+ isScheduled: boolean;
136
+ cronExpression: string;
137
+ reason?: string;
138
+ };
139
+ }>;
140
+ socialResponse?: {
141
+ shouldRespond: boolean;
142
+ response?: string;
143
+ isPartialResponse?: boolean;
144
+ };
145
+ interpreter?: string;
146
+ };
125
147
  export interface CreateMemoryInput {
126
- content: any;
127
- type: MemoryType;
128
- data: string[];
148
+ query: string;
149
+ data: any;
129
150
  userId?: string;
130
151
  scope?: MemoryScope;
152
+ ttl?: number;
131
153
  }
132
154
  export interface CacheMemoryType {
133
155
  id: string;
134
- type: MemoryType;
135
156
  data: any;
136
157
  query: string;
137
158
  embedding: Embedding;
@@ -149,15 +170,15 @@ export interface MemoryChunk {
149
170
  embedding: number[];
150
171
  }
151
172
  export type MemoryScopeType = (typeof MemoryScope)[keyof typeof MemoryScope];
152
- export interface Memory {
173
+ export interface LongTermMemory {
153
174
  id: string;
154
175
  query: string;
155
- purpose: string;
176
+ category: string;
156
177
  data: any;
157
- scope: MemoryScopeType;
158
- userId?: string;
178
+ roomId: string;
159
179
  createdAt: Date;
160
180
  chunks?: MemoryChunk[];
181
+ tags: string[];
161
182
  }
162
183
  export declare const ActionSchema: z.ZodArray<z.ZodObject<{
163
184
  name: z.ZodString;
@@ -205,3 +226,33 @@ export interface TransformedQueueItem {
205
226
  name: string;
206
227
  parameters: QueueItemParameter[];
207
228
  }
229
+ export interface ScheduledAction {
230
+ id: string;
231
+ action: {
232
+ name: string;
233
+ parameters: QueueItemParameter[];
234
+ };
235
+ scheduledTime: Date;
236
+ userId: string;
237
+ status: "pending" | "completed" | "failed";
238
+ recurrence?: {
239
+ type: "daily" | "weekly" | "monthly";
240
+ interval: number;
241
+ };
242
+ }
243
+ export interface ScheduledActionEvents {
244
+ onActionStart?: (action: ScheduledAction) => void;
245
+ onActionComplete?: (action: ScheduledAction, result: any) => void;
246
+ onActionFailed?: (action: ScheduledAction, error: Error) => void;
247
+ onActionScheduled?: (action: ScheduledAction) => void;
248
+ onActionCancelled?: (actionId: string) => void;
249
+ }
250
+ export interface WorkflowPattern {
251
+ query: string;
252
+ actions: Array<{
253
+ done: boolean;
254
+ name: string;
255
+ result: string;
256
+ }>;
257
+ success: boolean;
258
+ }
@@ -0,0 +1,12 @@
1
+ import { LanguageModelV1 } from "ai";
2
+ import { z } from "zod";
3
+ export declare const describeZodSchema: (schema: z.ZodType) => string;
4
+ export declare const generateObject: <T>(config: {
5
+ model: LanguageModelV1;
6
+ schema: z.ZodSchema;
7
+ prompt: string;
8
+ system: string;
9
+ temperature: number;
10
+ }) => Promise<{
11
+ object: T;
12
+ }>;
@@ -0,0 +1,90 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.generateObject = exports.describeZodSchema = void 0;
4
+ const ai_1 = require("ai");
5
+ const zod_1 = require("zod");
6
+ const describeZodSchema = (schema) => {
7
+ if (schema instanceof zod_1.z.ZodObject) {
8
+ const entries = Object.entries(schema.shape);
9
+ const fields = entries.map(([key, value]) => {
10
+ const description = value._def.description || "";
11
+ const fieldSchema = (0, exports.describeZodSchema)(value);
12
+ return description
13
+ ? `${key}: ${fieldSchema} // ${description}`
14
+ : `${key}: ${fieldSchema}`;
15
+ });
16
+ return `z.object({${fields.join(", ")}})`;
17
+ }
18
+ if (schema instanceof zod_1.z.ZodArray) {
19
+ return `z.array(${(0, exports.describeZodSchema)(schema.element)})`;
20
+ }
21
+ if (schema instanceof zod_1.z.ZodString) {
22
+ return "z.string()";
23
+ }
24
+ if (schema instanceof zod_1.z.ZodNumber) {
25
+ return "z.number()";
26
+ }
27
+ if (schema instanceof zod_1.z.ZodBoolean) {
28
+ return "z.boolean()";
29
+ }
30
+ if (schema instanceof zod_1.z.ZodOptional) {
31
+ return `z.optional(${(0, exports.describeZodSchema)(schema._def.innerType)})`;
32
+ }
33
+ if (schema instanceof zod_1.z.ZodUnion) {
34
+ return `z.union([${schema._def.options
35
+ .map((option) => (0, exports.describeZodSchema)(option))
36
+ .join(", ")}])`;
37
+ }
38
+ if (schema instanceof zod_1.z.ZodEnum) {
39
+ return `z.enum(${JSON.stringify(schema._def.values)})`;
40
+ }
41
+ if (schema instanceof zod_1.z.ZodLiteral) {
42
+ return `z.literal(${JSON.stringify(schema._def.value)})`;
43
+ }
44
+ return "z.unknown()"; // Fallback for unknown types
45
+ };
46
+ exports.describeZodSchema = describeZodSchema;
47
+ const generateObject = async (config) => {
48
+ // Generate a detailed description of the schema
49
+ const schemaDescription = (0, exports.describeZodSchema)(config.schema);
50
+ console.log("šŸ” Schema Description:\n", schemaDescription);
51
+ const response = await (0, ai_1.generateText)({
52
+ model: config.model,
53
+ prompt: `${config.prompt}
54
+
55
+ EXPECTED SCHEMA:
56
+ ${schemaDescription}
57
+
58
+ BAD EXAMPLE:
59
+ \`\`\`json
60
+ {
61
+ "key": "value"
62
+ }
63
+ \`\`\`
64
+
65
+ GOOD EXAMPLE:
66
+ {
67
+ "key": "value"
68
+ }
69
+
70
+ Output only the JSON schema, no 'triple quotes'json or any other text. Only the JSON schema.
71
+ `,
72
+ system: config.system,
73
+ temperature: config.temperature,
74
+ });
75
+ try {
76
+ // Clean the response text from any markdown or code block markers
77
+ const cleanText = response.text
78
+ .replace(/```json\s*/g, "")
79
+ .replace(/```\s*$/g, "")
80
+ .trim();
81
+ const parsedResponse = JSON.parse(cleanText);
82
+ const validatedResponse = config.schema.parse(parsedResponse);
83
+ return { object: validatedResponse };
84
+ }
85
+ catch (error) {
86
+ console.error("Error parsing or validating JSON response:", error);
87
+ throw new Error("Failed to generate valid JSON response");
88
+ }
89
+ };
90
+ exports.generateObject = generateObject;
@@ -0,0 +1,11 @@
1
+ type HeaderValue = string | string[] | undefined;
2
+ export declare class LLMHeaderBuilder {
3
+ private headers;
4
+ private _result;
5
+ constructor();
6
+ addHeader(key: string, value: HeaderValue): LLMHeaderBuilder;
7
+ valueOf(): string;
8
+ toString(): string;
9
+ static create(): LLMHeaderBuilder;
10
+ }
11
+ export {};
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.LLMHeaderBuilder = void 0;
4
+ class LLMHeaderBuilder {
5
+ constructor() {
6
+ this.headers = new Map();
7
+ this._result = "";
8
+ }
9
+ addHeader(key, value) {
10
+ if (Array.isArray(value)) {
11
+ this.headers.set(key, value.join("\n"));
12
+ }
13
+ else {
14
+ this.headers.set(key, value);
15
+ }
16
+ // Build result immediately
17
+ this._result = Array.from(this.headers.entries())
18
+ .filter(([_, value]) => value !== undefined)
19
+ .map(([key, value]) => `# ${key}: ${value}`)
20
+ .join("\n")
21
+ .trim();
22
+ return this;
23
+ }
24
+ valueOf() {
25
+ return this._result;
26
+ }
27
+ toString() {
28
+ return this._result;
29
+ }
30
+ static create() {
31
+ return new LLMHeaderBuilder();
32
+ }
33
+ }
34
+ exports.LLMHeaderBuilder = LLMHeaderBuilder;
@@ -5,8 +5,8 @@ const injectActions = (actions) => {
5
5
  return actions.map((action) => {
6
6
  const parameters = action.parameters;
7
7
  const schemaShape = Object.keys(parameters._def.shape()).join(", ");
8
- const actionString = `Name: ${action.name}, Description: ${action.description}, Arguments (STRICTLY REQUIRED): { ${schemaShape} } ${action.examples
9
- ? `Format examples (MUST RESPECT): ${action.examples.map((example) => {
8
+ const actionString = `Name: ${action.name}, Description: ${action.description}, Arguments: { ${schemaShape} } ${action.examples
9
+ ? `Format examples: ${action.examples.map((example) => {
10
10
  return JSON.stringify(example);
11
11
  })}`
12
12
  : ""}`;
@@ -1,7 +1,7 @@
1
- import { ActionData, QueueResult, TransformedQueueItem } from "../types";
1
+ import { ActionData, QueueItem, QueueResult, TransformedQueueItem } from "../types";
2
2
  export declare class QueueItemTransformer {
3
3
  static transformActionToQueueItem(action: ActionData): TransformedQueueItem;
4
4
  static transformFromSimilarActions(similarActions: QueueResult[]): TransformedQueueItem[] | undefined;
5
5
  private static transformParameters;
6
- static transformActionsToQueueItems(actions: ActionData[] | undefined): TransformedQueueItem[] | undefined;
6
+ static transformActionsToQueueItems(actions: ActionData[] | undefined): QueueItem[] | undefined;
7
7
  }
@@ -0,0 +1,16 @@
1
+ import { z } from "zod";
2
+ export interface SchemaConfig {
3
+ schema: z.ZodType;
4
+ instructions?: string;
5
+ outputExamples?: {
6
+ input: string;
7
+ output: string;
8
+ }[];
9
+ }
10
+ export declare class SchemaGenerator {
11
+ static generate(config: SchemaConfig): {
12
+ schema: string;
13
+ instructions: string;
14
+ outputExamples: string;
15
+ };
16
+ }
@@ -0,0 +1,46 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SchemaGenerator = void 0;
4
+ const zod_1 = require("zod");
5
+ class SchemaGenerator {
6
+ static generate(config) {
7
+ const { schema, instructions = "Output only the JSON schema, no 'triple quotes'json or any other text. Only the JSON schema.", outputExamples = [], } = config;
8
+ const getSchemaString = (schema) => {
9
+ if (schema instanceof zod_1.z.ZodObject) {
10
+ const entries = Object.entries(schema.shape);
11
+ const fields = entries.map(([key, value]) => {
12
+ const description = value._def.description;
13
+ const schemaStr = getSchemaString(value);
14
+ return description
15
+ ? `${key}: ${schemaStr} // ${description}`
16
+ : `${key}: ${schemaStr}`;
17
+ });
18
+ return `z.object({${fields.join(", ")}})`;
19
+ }
20
+ if (schema instanceof zod_1.z.ZodArray) {
21
+ return `z.array(${getSchemaString(schema.element)})`;
22
+ }
23
+ if (schema instanceof zod_1.z.ZodString) {
24
+ return "z.string()";
25
+ }
26
+ if (schema instanceof zod_1.z.ZodNumber) {
27
+ return "z.number()";
28
+ }
29
+ if (schema instanceof zod_1.z.ZodBoolean) {
30
+ return "z.boolean()";
31
+ }
32
+ // Fallback for other Zod types
33
+ return `z.unknown()`;
34
+ };
35
+ const schemaString = getSchemaString(schema);
36
+ return {
37
+ schema: schemaString,
38
+ instructions,
39
+ outputExamples: outputExamples
40
+ .map((example) => `Input: ${JSON.stringify(example.input)}, Output: ${JSON.stringify(example.output)}`)
41
+ .join("\n")
42
+ .trim(),
43
+ };
44
+ }
45
+ }
46
+ exports.SchemaGenerator = SchemaGenerator;
@@ -0,0 +1,103 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { deepseek } from "@ai-sdk/deepseek";
4
+ import { configDotenv } from "dotenv";
5
+ import readline from "readline";
6
+ import { Agent } from "../agent";
7
+ import { getRssNews } from "../agent/tools/get-rss";
8
+ import { Interpreter } from "../llm/interpreter";
9
+ import {
10
+ generalInterpreterCharacter,
11
+ marketInterpreterCharacter,
12
+ securityInterpreterCharacter,
13
+ } from "../llm/interpreter/context";
14
+ configDotenv();
15
+ // Initialiser l'agent une fois pour toute la session
16
+ const initializeAgent = () => {
17
+ const model = deepseek("deepseek-reasoner");
18
+
19
+ const securityInterpreter = new Interpreter({
20
+ name: "security",
21
+ model,
22
+ character: securityInterpreterCharacter,
23
+ });
24
+ const marketInterpreter = new Interpreter({
25
+ name: "market",
26
+ model,
27
+ character: marketInterpreterCharacter,
28
+ });
29
+ const generalInterpreter = new Interpreter({
30
+ name: "general",
31
+ model,
32
+ character: generalInterpreterCharacter,
33
+ });
34
+
35
+ const agent = new Agent({
36
+ cache: {
37
+ host: process.env.REDIS_HOST || "localhost",
38
+ port: Number(process.env.REDIS_PORT) || 6379,
39
+ },
40
+ orchestrator: {
41
+ model,
42
+ tools: [getRssNews],
43
+ },
44
+ interpreters: [securityInterpreter, marketInterpreter, generalInterpreter],
45
+ memoryManager: {
46
+ model,
47
+ },
48
+ maxIterations: 3,
49
+ });
50
+
51
+ return agent;
52
+ };
53
+
54
+ // Fonction pour lancer une session interactive
55
+ const startChatSession = async () => {
56
+ console.log("Bienvenue dans votre session de chat avec l'agent !");
57
+ console.log("Tapez 'exit' pour quitter.\n");
58
+
59
+ const agent = initializeAgent();
60
+
61
+ const rl = readline.createInterface({
62
+ input: process.stdin,
63
+ output: process.stdout,
64
+ prompt: "Vous > ",
65
+ });
66
+
67
+ let state = {
68
+ currentContext: "",
69
+ previousActions: [],
70
+ };
71
+
72
+ rl.prompt();
73
+
74
+ rl.on("line", async (line) => {
75
+ const input = line.trim();
76
+
77
+ if (input.toLowerCase() === "exit") {
78
+ console.log("Fin de la session. ƀ bientĆ“t !");
79
+ rl.close();
80
+ return;
81
+ }
82
+
83
+ state.currentContext = input;
84
+
85
+ console.log("Agent en rƩflexion...");
86
+ try {
87
+ const result = await agent.process(state);
88
+ console.log(`Agent > ${result}\n`);
89
+ } catch (error) {
90
+ console.error("Erreur avec l'agent :", error);
91
+ }
92
+
93
+ rl.prompt();
94
+ });
95
+
96
+ rl.on("close", () => {
97
+ console.log("Session terminƩe.");
98
+ process.exit(0);
99
+ });
100
+ };
101
+
102
+ // Lancer la session de chat
103
+ startChatSession();
@@ -1,15 +1,28 @@
1
- export const generalInterpreterContext = {
1
+ export type Character = {
2
+ role: string;
3
+ language: string;
4
+ guidelines: {
5
+ important: string[];
6
+ warnings: string[];
7
+ };
8
+ examplesMessages?: {
9
+ role: string;
10
+ content: string;
11
+ }[];
12
+ };
13
+
14
+ export const generalInterpreterCharacter: Character = {
2
15
  role: "You are the general assistant. Your role is to provide a clear and factual analysis of the results.",
3
- language: "same_as_user",
16
+ language: "user_request",
4
17
  guidelines: {
5
18
  important: [],
6
19
  warnings: [],
7
20
  },
8
21
  };
9
22
 
10
- export const securityInterpreterContext = {
23
+ export const securityInterpreterCharacter: Character = {
11
24
  role: "You are the security expert. Your role is to provide a clear and factual analysis of the security of the token/coin.",
12
- language: "user_language",
25
+ language: "user_request",
13
26
  guidelines: {
14
27
  important: [
15
28
  "Start with a clear security analysis of the token/coin.",
@@ -47,12 +60,12 @@ export const securityInterpreterContext = {
47
60
  ],
48
61
  };
49
62
 
50
- export const marketInterpreterContext = {
63
+ export const marketInterpreterCharacter: Character = {
51
64
  role: "You are the market expert. Your role is to provide a clear and factual analysis of the market sentiment of the token/coin.",
52
- language: "user_language",
65
+ language: "user_request",
53
66
  guidelines: {
54
67
  important: [
55
- "Start with a clear market sentiment (Bullish/Bearish/Neutral) without any additional comments before.",
68
+ "Start with a clear market sentiment (Market sentiment: Bullish/Bearish/Neutral šŸ“ˆšŸ“‰šŸ“Š) without any additional comments before.",
56
69
  "One section for fundamental analysis (important events, news, trends..etc). One section, no sub-sections.",
57
70
  "One section for technical analysis (key price levels, trading volume, technical indicators, market activity). One section, no sub-sections.",
58
71
  "STOP AFTER TECHNICAL ANALYSIS SECTION WITHOUT ANY ADDITIONAL COMMENTS",
@@ -60,7 +73,6 @@ export const marketInterpreterContext = {
60
73
  warnings: [
61
74
  "NEVER provide any financial advice.",
62
75
  "NEVER speak about details of your system or your capabilities.",
63
- "NEVER ADD ANY CONCLUDING STATEMENT OR DISCLAIMER AT THE END",
64
76
  ],
65
77
  },
66
78
  examplesMessages: [
@@ -1,33 +1,75 @@
1
- import { openai } from "@ai-sdk/openai";
2
- import { generateObject, streamText, StreamTextResult } from "ai";
1
+ import { LanguageModel, streamText, StreamTextResult } from "ai";
3
2
  import { z } from "zod";
4
3
  import { Behavior, State } from "../../types";
4
+ import { generateObject } from "../../utils/generate-object";
5
+ import { LLMHeaderBuilder } from "../../utils/header-builder";
6
+
7
+ const interpreterSchema = z.object({
8
+ requestLanguage: z
9
+ .string()
10
+ .describe("The language of the user's request (fr, en, es, etc.)"),
11
+ actionsCompleted: z
12
+ .array(
13
+ z.object({
14
+ name: z.string(),
15
+ reasoning: z.string(),
16
+ })
17
+ )
18
+ .describe("The actions done and why."),
19
+ response: z.string().describe("The response to the user's request."),
20
+ });
21
+
22
+ interface InterpretationResult {
23
+ actionsCompleted: {
24
+ name: string;
25
+ reasoning: string;
26
+ }[];
27
+ response: string;
28
+ }
5
29
 
6
30
  export class Interpreter {
7
- private readonly model = openai("gpt-4o");
31
+ public readonly model: LanguageModel;
8
32
  public readonly name: string;
33
+ public readonly character: Behavior;
9
34
 
10
- constructor(name: string, private readonly behavior: Behavior) {
35
+ constructor({
36
+ name,
37
+ model,
38
+ character,
39
+ }: {
40
+ name: string;
41
+ model: LanguageModel;
42
+ character: Behavior;
43
+ }) {
11
44
  this.name = name;
12
- this.behavior = behavior;
45
+ this.model = model;
46
+ this.character = character;
13
47
  }
14
48
 
15
- composeContext(state: State) {
49
+ private buildContext(state: State) {
16
50
  const { userRequest, results } = state;
17
- const { role, language, guidelines, examplesMessages } = this.behavior;
18
-
51
+ const { role, language, guidelines } = this.character;
19
52
  const { important, warnings, steps } = guidelines;
20
53
 
21
- const context = `
22
- # ROLE: ${role}
23
- # LANGUAGE: ${language}
24
- # IMPORTANT: ${important.join("\n")}
25
- # NEVER: ${warnings.join("\n")}
26
- # USER_REQUEST: ${userRequest}
27
- # CURRENT_RESULTS: ${results}
28
- # STEPS: ${steps?.join("\n") || ""}
29
- # MESSAGES EXAMPLES: ${JSON.stringify(examplesMessages, null, 2)}
30
- `;
54
+ const context = LLMHeaderBuilder.create();
55
+
56
+ if (role) {
57
+ context.addHeader("ROLE", role);
58
+ }
59
+
60
+ if (language) {
61
+ context.addHeader("LANGUAGE", language);
62
+ }
63
+
64
+ if (important.length > 0) {
65
+ context.addHeader("IMPORTANT", important);
66
+ }
67
+
68
+ if (warnings.length > 0) {
69
+ context.addHeader("NEVER", warnings);
70
+ }
71
+
72
+ context.addHeader("CURRENT_RESULTS", results);
31
73
  return context;
32
74
  }
33
75
 
@@ -45,43 +87,27 @@ export class Interpreter {
45
87
  }
46
88
  | StreamTextResult<Record<string, any>>
47
89
  > {
48
- console.log("\nšŸŽØ Starting interpretation process");
49
- console.log("Prompt:", prompt);
50
- console.log("Results to interpret:", JSON.stringify(state, null, 2));
90
+ try {
91
+ console.log("\nšŸŽØ Starting interpretation process");
92
+ console.log("Prompt:", prompt);
93
+ console.log("Results to interpret:", JSON.stringify(state, null, 2));
51
94
 
52
- const context = this.composeContext(state);
53
-
54
- const result = await generateObject({
55
- model: this.model,
56
- schema: z.object({
57
- requestLanguage: z.string(),
58
- actionsCompleted: z.array(
59
- z.object({
60
- name: z.string(),
61
- reasoning: z.string(),
62
- })
63
- ),
64
- response: z.string(),
65
- }),
66
- prompt,
67
- system: context,
68
- });
69
-
70
- console.log("\nāœ… Interpretation completed");
71
- console.log("─".repeat(50));
72
- console.log("Generated response:", result.object);
73
-
74
- if (result.object.actionsCompleted.length > 0) {
75
- console.log("\nšŸ“‹ Suggested actions:");
76
- result.object.actionsCompleted.forEach((action, index) => {
77
- console.log(`\n${index + 1}. Action Details:`);
78
- console.log(` Name: ${action.name}`);
79
- console.log(` Reasoning: ${action.reasoning}`);
95
+ const context = this.buildContext(state);
96
+ console.log("Context:", context.toString());
97
+ const result = await generateObject<InterpretationResult>({
98
+ model: this.model,
99
+ prompt,
100
+ system: context.toString(),
101
+ temperature: 1.3,
102
+ schema: interpreterSchema,
80
103
  });
81
- }
82
104
 
83
- if (onFinish) onFinish(result.object);
84
- return result.object;
105
+ if (onFinish) onFinish(result.object);
106
+ return result.object;
107
+ } catch (error) {
108
+ console.error("Error parsing schema:", error);
109
+ throw error;
110
+ }
85
111
  }
86
112
 
87
113
  async streamProcess(
@@ -92,7 +118,7 @@ export class Interpreter {
92
118
  console.log("\nšŸŽØ Starting streaming interpretation");
93
119
  console.log("Prompt:", prompt);
94
120
 
95
- const context = this.composeContext(state);
121
+ const context = this.buildContext(state);
96
122
 
97
123
  const result = await streamText({
98
124
  model: this.model,
@@ -101,7 +127,8 @@ export class Interpreter {
101
127
  if (onFinish) onFinish(event);
102
128
  },
103
129
  prompt,
104
- system: context,
130
+ system: context.toString(),
131
+ temperature: 1.3,
105
132
  });
106
133
 
107
134
  return result;