@ai.ntellect/core 0.4.1 → 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.
package/examples/index.ts CHANGED
@@ -4,33 +4,27 @@ import { deepseek } from "@ai-sdk/deepseek";
4
4
  import { configDotenv } from "dotenv";
5
5
  import readline from "readline";
6
6
  import { Agent } from "../agent";
7
- import { getRssNews } from "../agent/tools/get-rss";
8
7
  import { Interpreter } from "../llm/interpreter";
9
8
  import {
10
- generalInterpreterCharacter,
11
9
  marketInterpreterCharacter,
12
10
  securityInterpreterCharacter,
13
11
  } from "../llm/interpreter/context";
12
+ import { getRssNews } from "./actions/get-rss";
14
13
  configDotenv();
15
14
  // Initialiser l'agent une fois pour toute la session
16
15
  const initializeAgent = () => {
17
- const model = deepseek("deepseek-reasoner");
16
+ const model = deepseek("deepseek-chat");
18
17
 
19
18
  const securityInterpreter = new Interpreter({
20
- name: "security",
19
+ name: "security-check",
21
20
  model,
22
21
  character: securityInterpreterCharacter,
23
22
  });
24
23
  const marketInterpreter = new Interpreter({
25
- name: "market",
24
+ name: "market-analysis",
26
25
  model,
27
26
  character: marketInterpreterCharacter,
28
27
  });
29
- const generalInterpreter = new Interpreter({
30
- name: "general",
31
- model,
32
- character: generalInterpreterCharacter,
33
- });
34
28
 
35
29
  const agent = new Agent({
36
30
  cache: {
@@ -41,7 +35,7 @@ const initializeAgent = () => {
41
35
  model,
42
36
  tools: [getRssNews],
43
37
  },
44
- interpreters: [securityInterpreter, marketInterpreter, generalInterpreter],
38
+ interpreters: [securityInterpreter, marketInterpreter],
45
39
  memoryManager: {
46
40
  model,
47
41
  },
@@ -80,12 +74,13 @@ const startChatSession = async () => {
80
74
  return;
81
75
  }
82
76
 
83
- state.currentContext = input;
84
-
85
77
  console.log("Agent en réflexion...");
86
78
  try {
87
- const result = await agent.process(state);
88
- console.log(`Agent > ${result}\n`);
79
+ const result = await agent.process(input, {
80
+ onMessage: (message) => {
81
+ console.log(`Agent > ${message.socialResponse?.response}\n`);
82
+ },
83
+ });
89
84
  } catch (error) {
90
85
  console.error("Erreur avec l'agent :", error);
91
86
  }
package/index.html ADDED
@@ -0,0 +1,42 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
+ <title>Workflow Visualization with Order</title>
7
+ <script src="https://d3js.org/d3.v7.min.js"></script>
8
+ <style>
9
+ .node {
10
+ fill: steelblue;
11
+ stroke: black;
12
+ stroke-width: 1.5px;
13
+ cursor: pointer;
14
+ }
15
+ .node.selected {
16
+ fill: orange;
17
+ }
18
+ .link {
19
+ stroke: #ccc;
20
+ stroke-width: 2px;
21
+ opacity: 0.7;
22
+ }
23
+ .link.active {
24
+ stroke: orange;
25
+ stroke-width: 3px;
26
+ }
27
+ text {
28
+ font-size: 12px;
29
+ fill: black;
30
+ }
31
+ .order {
32
+ font-size: 10px;
33
+ fill: white;
34
+ font-weight: bold;
35
+ }
36
+ </style>
37
+ </head>
38
+ <body>
39
+ <svg id="graph" width="800" height="600"></svg>
40
+ <script src="script.js"></script>
41
+ </body>
42
+ </html>
@@ -0,0 +1,36 @@
1
+ import { deepseek } from "@ai-sdk/deepseek";
2
+ import { configDotenv } from "dotenv";
3
+ import { DynamicConditionGenerator } from "./index";
4
+
5
+ const schema = `{
6
+ "type": "object",
7
+ "properties": {
8
+ "volume": { "type": "number" }
9
+ },
10
+ "required": ["volume"]
11
+ }`;
12
+
13
+ const testData = {
14
+ volume: 100000,
15
+ };
16
+
17
+ configDotenv();
18
+
19
+ async function example() {
20
+ const generator = new DynamicConditionGenerator(
21
+ deepseek("deepseek-reasoner")
22
+ );
23
+
24
+ const result = await generator.generateCondition(
25
+ schema,
26
+ "check all pools with more than 100k volume",
27
+ {
28
+ functionName: "tradingCondition",
29
+ testData,
30
+ }
31
+ );
32
+
33
+ console.log("Generated function:", result);
34
+ }
35
+
36
+ example();
@@ -0,0 +1,108 @@
1
+ import { generateText, LanguageModel } from "ai";
2
+ import { z } from "zod";
3
+ import { LLMHeaderBuilder } from "../../utils/header-builder";
4
+
5
+ // Define the schema for condition validation
6
+ const conditionSchema = z.object({
7
+ function: z.string().describe("The generated dynamic condition function"),
8
+ testResult: z
9
+ .boolean()
10
+ .optional()
11
+ .describe("The test result if test data provided"),
12
+ });
13
+
14
+ export interface DynamicConditionConfig {
15
+ functionName?: string;
16
+ testData?: Record<string, any>;
17
+ }
18
+
19
+ export class DynamicConditionGenerator {
20
+ private readonly model: LanguageModel;
21
+
22
+ constructor(model: LanguageModel) {
23
+ this.model = model;
24
+ }
25
+
26
+ /** Generate a JavaScript function named dynamicCondition that takes an object matching this schema and returns true following the prompt.
27
+ The function must name 'dynamicCondition(data)' dynamically adapt to this schema. If fields are missing or do not match the schema, it should return false.
28
+ Only return one JavaScript function code.
29
+
30
+ BAD EXAMPLE:
31
+ \`\`\`javascript
32
+ function dynamicCondition(data) {
33
+ return data.amount > 0.1 && data.status === "completed";
34
+ }
35
+ \`\`\`
36
+
37
+ GOOD EXAMPLE:
38
+ function dynamicCondition(data) {
39
+ return data.amount > 0.1 && data.status === "completed";
40
+ }
41
+
42
+ OUTPUT ONLY THE FUNCTION CODE, NO 'TRIPLE QUOTES' OR ANY OTHER TEXT. ONLY THE FUNCTION CODE. */
43
+ private buildContext(schema: string, config: DynamicConditionConfig) {
44
+ const context = LLMHeaderBuilder.create()
45
+ .addHeader(
46
+ "ROLE",
47
+ "Generate a JavaScript function named 'dynamicCondition(data)' that takes an object matching this schema and returns true following the prompt."
48
+ )
49
+ .addHeader("IMPORTANT", [
50
+ "The function must name 'dynamicCondition(data)'",
51
+ "If fields are missing or do not match the schema, it should return false.",
52
+ "Only return one JavaScript function code.",
53
+ "OUTPUT ONLY THE FUNCTION CODE, NO 'TRIPLE QUOTES' OR ANY OTHER TEXT. ONLY THE FUNCTION CODE.",
54
+ ])
55
+ .addHeader(
56
+ "BAD EXAMPLE",
57
+ `\`\`\`javascript
58
+ function dynamicCondition(data) {
59
+ return data.amount > 0.1 && data.status === 'completed';
60
+ }
61
+ \`\`\``
62
+ )
63
+ .addHeader(
64
+ "GOOD EXAMPLE",
65
+ `
66
+ function dynamicCondition(data) {
67
+ return data.amount > 0.1 && data.status === 'completed';
68
+ }`
69
+ )
70
+ .addHeader("SCHEMA", schema)
71
+ .addHeader("FUNCTION_NAME", config.functionName || "dynamicCondition");
72
+
73
+ return context.toString();
74
+ }
75
+
76
+ async generateCondition(
77
+ schema: string,
78
+ condition: string,
79
+ config: DynamicConditionConfig = {}
80
+ ) {
81
+ try {
82
+ const context = this.buildContext(schema, config);
83
+
84
+ const result = await generateText({
85
+ model: this.model,
86
+ system: context.toString(),
87
+ prompt: `Generate a function that validates this condition: ${condition}`,
88
+ temperature: 0,
89
+ });
90
+
91
+ // Test the generated function if test data is provided
92
+ if (config.testData) {
93
+ try {
94
+ const functionEval = eval(`(${result.text})`);
95
+ const testResult = functionEval(config.testData);
96
+ console.log("Test result:", testResult);
97
+ } catch (error) {
98
+ console.error("Error testing function:", error);
99
+ }
100
+ }
101
+
102
+ return result.text;
103
+ } catch (error) {
104
+ console.error("Error generating condition:", error);
105
+ throw error;
106
+ }
107
+ }
108
+ }
@@ -11,18 +11,9 @@ export type Character = {
11
11
  }[];
12
12
  };
13
13
 
14
- export const generalInterpreterCharacter: Character = {
15
- role: "You are the general assistant. Your role is to provide a clear and factual analysis of the results.",
16
- language: "user_request",
17
- guidelines: {
18
- important: [],
19
- warnings: [],
20
- },
21
- };
22
-
23
14
  export const securityInterpreterCharacter: Character = {
24
15
  role: "You are the security expert. Your role is to provide a clear and factual analysis of the security of the token/coin.",
25
- language: "user_request",
16
+ language: "same_as_request",
26
17
  guidelines: {
27
18
  important: [
28
19
  "Start with a clear security analysis of the token/coin.",
@@ -52,7 +43,8 @@ export const securityInterpreterCharacter: Character = {
52
43
 
53
44
  ### Bad:
54
45
  Speak about the bad points of the security check. If there is no bad point, say "No bad point found"
55
-
46
+
47
+ TRANSLATE ALL THE TEXT TO LANGUAGE OF THE USER REQUEST
56
48
  STOP AFTER SECURITY CHECK SECTION WITHOUT ANY CONCLUDING STATEMENT OR DISCLAIMER OR ADDITIONAL COMMENTS
57
49
  --------------------------------
58
50
  `,
@@ -62,7 +54,7 @@ export const securityInterpreterCharacter: Character = {
62
54
 
63
55
  export const marketInterpreterCharacter: Character = {
64
56
  role: "You are the market expert. Your role is to provide a clear and factual analysis of the market sentiment of the token/coin.",
65
- language: "user_request",
57
+ language: "same_as_request",
66
58
  guidelines: {
67
59
  important: [
68
60
  "Start with a clear market sentiment (Market sentiment: Bullish/Bearish/Neutral 📈📉📊) without any additional comments before.",
@@ -93,6 +85,7 @@ export const marketInterpreterCharacter: Character = {
93
85
  ### Technical analysis (No sub-sections):
94
86
  Speak about key price levels, trading volume, technical indicators, market activity..etc
95
87
 
88
+ TRANSLATE ALL THE TEXT TO LANGUAGE OF THE USER REQUEST
96
89
  STOP AFTER TECHNICAL ANALYSIS SECTION WITHOUT ANY CONCLUDING STATEMENT OR DISCLAIMER OR ADDITIONAL COMMENTS
97
90
  --------------------------------
98
91
  `,
@@ -1,8 +1,9 @@
1
1
  import { LanguageModel, streamText, StreamTextResult } from "ai";
2
2
  import { z } from "zod";
3
- import { Behavior, State } from "../../types";
3
+ import { Behavior, MyContext, SharedState } from "../../types";
4
4
  import { generateObject } from "../../utils/generate-object";
5
5
  import { LLMHeaderBuilder } from "../../utils/header-builder";
6
+ import { State } from "../orchestrator/types";
6
7
 
7
8
  const interpreterSchema = z.object({
8
9
  requestLanguage: z
@@ -46,8 +47,7 @@ export class Interpreter {
46
47
  this.character = character;
47
48
  }
48
49
 
49
- private buildContext(state: State) {
50
- const { userRequest, results } = state;
50
+ private buildContext() {
51
51
  const { role, language, guidelines } = this.character;
52
52
  const { important, warnings, steps } = guidelines;
53
53
 
@@ -68,14 +68,11 @@ export class Interpreter {
68
68
  if (warnings.length > 0) {
69
69
  context.addHeader("NEVER", warnings);
70
70
  }
71
-
72
- context.addHeader("CURRENT_RESULTS", results);
73
71
  return context;
74
72
  }
75
73
 
76
74
  async process(
77
- prompt: string,
78
- state: State,
75
+ state: SharedState<MyContext>,
79
76
  onFinish?: (event: any) => void
80
77
  ): Promise<
81
78
  | {
@@ -88,17 +85,24 @@ export class Interpreter {
88
85
  | StreamTextResult<Record<string, any>>
89
86
  > {
90
87
  try {
91
- console.log("\n🎨 Starting interpretation process");
92
- console.log("Prompt:", prompt);
93
- console.log("Results to interpret:", JSON.stringify(state, null, 2));
94
-
95
- const context = this.buildContext(state);
96
- console.log("Context:", context.toString());
88
+ console.log("\n🎨 Start ing interpretation process");
89
+
90
+ const context = this.buildContext();
91
+ let prompt = LLMHeaderBuilder.create();
92
+ if (state.messages) {
93
+ prompt.addHeader(
94
+ "REQUEST",
95
+ state.messages[state.messages.length - 2].content.toString()
96
+ );
97
+ }
98
+ if (state.context.results) {
99
+ prompt.addHeader("RESULTS", JSON.stringify(state.context.results));
100
+ }
97
101
  const result = await generateObject<InterpretationResult>({
98
102
  model: this.model,
99
- prompt,
103
+ prompt: prompt.toString(),
100
104
  system: context.toString(),
101
- temperature: 1.3,
105
+ temperature: 0.5,
102
106
  schema: interpreterSchema,
103
107
  });
104
108
 
@@ -118,7 +122,7 @@ export class Interpreter {
118
122
  console.log("\n🎨 Starting streaming interpretation");
119
123
  console.log("Prompt:", prompt);
120
124
 
121
- const context = this.buildContext(state);
125
+ const context = this.buildContext();
122
126
 
123
127
  const result = await streamText({
124
128
  model: this.model,
@@ -1,15 +1,13 @@
1
1
  import { Character } from "../interpreter/context";
2
2
 
3
3
  export const memoryManagerInstructions: Character = {
4
- role: "You are the memory curator. Your role is to extract and format memories from interactions.",
5
- language: "user_request",
4
+ role: "You are the memory curator. Your role is to extract relevant memories from interactions.",
5
+ language: "same_as_request",
6
6
  guidelines: {
7
7
  important: [
8
- "Generate memories based on the user request",
9
- "Generate query for requested data as the user could ask for it later",
10
- "Should be short-term memories only if it's ephemeral but relevant and reusable",
8
+ "Generate query for requested data as the user could ask for it later (Eg: 'What is the price of Bitcoin today?')s",
9
+ "Short-term memories need to be necessary and reusable",
11
10
  "Only store as long-term: User information, User preferences, Important facts that don't change often, Historical milestones",
12
- "Make memory data concise and clear",
13
11
  "Set appropriate TTL based on data volatility",
14
12
  ],
15
13
  warnings: [
@@ -2,10 +2,9 @@ import { LanguageModelV1 } from "ai";
2
2
  import { z } from "zod";
3
3
  import { CacheMemory } from "../../memory/cache";
4
4
  import { PersistentMemory } from "../../memory/persistent";
5
- import { MemoryScope } from "../../types";
5
+ import { MyContext, SharedState } from "../../types";
6
6
  import { generateObject } from "../../utils/generate-object";
7
7
  import { LLMHeaderBuilder } from "../../utils/header-builder";
8
- import { State } from "../orchestrator/types";
9
8
  import { memoryManagerInstructions } from "./context";
10
9
 
11
10
  interface MemoryResponse {
@@ -27,7 +26,7 @@ interface MemoryResponse {
27
26
  }
28
27
  export class MemoryManager {
29
28
  private readonly model: LanguageModelV1;
30
- private readonly memory?: {
29
+ public readonly memory?: {
31
30
  cache?: CacheMemory;
32
31
  persistent?: PersistentMemory;
33
32
  };
@@ -43,19 +42,39 @@ export class MemoryManager {
43
42
  this.memory = config.memory;
44
43
  }
45
44
 
46
- buildContext(state: State) {
45
+ buildContext() {
47
46
  const context = LLMHeaderBuilder.create()
48
47
  .addHeader("ROLE", memoryManagerInstructions.role)
49
48
  .addHeader("LANGUAGE", memoryManagerInstructions.language)
50
49
  .addHeader("IMPORTANT", memoryManagerInstructions.guidelines.important)
51
- .addHeader("WARNINGS", memoryManagerInstructions.guidelines.warnings)
52
- .addHeader("CURRENT_CONTEXT", state.currentContext)
53
- .addHeader("RESULTS", JSON.stringify(state.results));
50
+ .addHeader("WARNINGS", memoryManagerInstructions.guidelines.warnings);
54
51
  return context.toString();
55
52
  }
56
53
 
57
- async process(state: State, result: string) {
58
- const context = this.buildContext(state);
54
+ async process(
55
+ state: SharedState<MyContext>,
56
+ callbacks?: {
57
+ onMemoriesGenerated?: (event: any) => void;
58
+ }
59
+ ) {
60
+ const context = this.buildContext();
61
+ let prompt = LLMHeaderBuilder.create();
62
+ if (state.messages) {
63
+ prompt.addHeader(
64
+ "REQUEST",
65
+ state.messages[state.messages.length - 2].content.toString()
66
+ );
67
+ }
68
+ if (state.messages && state.messages.length > 0) {
69
+ prompt.addHeader("RECENT_MESSAGES", JSON.stringify(state.messages));
70
+ }
71
+
72
+ if (state.context.actions) {
73
+ prompt.addHeader(
74
+ "PREVIOUS_ACTIONS",
75
+ JSON.stringify(state.context.actions)
76
+ );
77
+ }
59
78
 
60
79
  const memories = await generateObject<MemoryResponse>({
61
80
  model: this.model,
@@ -79,85 +98,18 @@ export class MemoryManager {
79
98
  })
80
99
  ),
81
100
  }),
82
- prompt: state.currentContext,
83
101
  system: context.toString(),
84
102
  temperature: 1,
103
+ prompt: prompt.toString(),
85
104
  });
86
105
 
87
- console.log("Memories:", memories.object.memories);
88
-
89
106
  if (!this.memory) {
90
107
  return;
91
108
  }
92
109
 
93
- // Store memories after all processing is complete
94
- await Promise.all([
95
- // Store short-term memories in cache
96
- ...memories.object.memories
97
- .filter((m: any) => m.type === "short-term")
98
- .map(async (memoryItem: any) => {
99
- if (!this.memory?.cache) {
100
- return;
101
- }
102
-
103
- const existingCacheMemories =
104
- await this.memory.cache.findSimilarActions(memoryItem.data, {
105
- similarityThreshold: 85,
106
- maxResults: 3,
107
- scope: MemoryScope.GLOBAL,
108
- });
109
-
110
- if (existingCacheMemories.length > 0) {
111
- console.log(
112
- "⚠️ Similar memory already exists in cache:",
113
- memoryItem.data
114
- );
115
- return;
116
- }
117
-
118
- await this.memory.cache.createMemory({
119
- query: memoryItem.queryForMemory,
120
- data: memoryItem.data,
121
- ttl: memoryItem.ttl, // Use TTL from LLM
122
- });
123
- console.log("✅ Memory stored in cache:", memoryItem.data);
124
- }),
125
-
126
- // Store long-term memories in persistent storage
127
- ...memories.object.memories
128
- .filter((m) => m.type === "long-term")
129
- .map(async (memoryItem) => {
130
- if (!this.memory?.persistent) {
131
- return;
132
- }
133
-
134
- const existingPersistentMemories =
135
- await this.memory.persistent.findRelevantDocuments(
136
- memoryItem.data,
137
- {
138
- similarityThreshold: 85,
139
- }
140
- );
141
-
142
- if (existingPersistentMemories.length > 0) {
143
- console.log(
144
- "⚠️ Similar memory already exists in persistent storage:",
145
- memoryItem.data
146
- );
147
- return;
148
- }
110
+ if (callbacks?.onMemoriesGenerated)
111
+ callbacks.onMemoriesGenerated(memories.object);
149
112
 
150
- await this.memory.persistent.createMemory({
151
- query: memoryItem.queryForMemory,
152
- data: memoryItem.data,
153
- category: memoryItem.category,
154
- tags: memoryItem.tags,
155
- roomId: "global",
156
- createdAt: new Date(),
157
- id: crypto.randomUUID(),
158
- });
159
- console.log("✅ Memory stored in persistent storage:", memoryItem);
160
- }),
161
- ]);
113
+ return memories.object;
162
114
  }
163
115
  }
@@ -1,16 +1,13 @@
1
1
  import { Character } from "../interpreter/context";
2
2
 
3
3
  export const orchestratorInstructions: Character = {
4
- role: "You are the orchestrator. Your role is to evaluate the current state and determine next actions.",
5
- language: "user_request",
4
+ role: "Your role is to evaluate the current state and determine next actions.",
5
+ language: "same_as_request",
6
6
  guidelines: {
7
7
  important: [
8
- "Continue executing actions until ALL necessary goals are achieved",
9
- "You can schedule actions in cron expression to be executed later (if needed)",
10
- "Only stop when you have a complete picture of the goal",
11
- "Social responses can be partial while gathering more data",
12
- "Set shouldContinue to false if no more actions are needed",
13
- "Once all actions are completed, choose the right interpreter to interpret the results",
8
+ "If no actions are needed, just answer",
9
+ "If required, you can schedule actions in cron expression to be executed later",
10
+ "If required, you choose one interpreter to interpret the results when you have a complete picture of the goal",
14
11
  ],
15
12
  warnings: [
16
13
  "Never use a tool if it's not related to the user request",