@ai.ntellect/core 0.5.0 → 0.6.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 (131) hide show
  1. package/.mocharc.json +1 -1
  2. package/README.md +311 -272
  3. package/dist/graph/controller.js +63 -0
  4. package/dist/graph/engine.js +563 -0
  5. package/dist/index.js +6 -6
  6. package/dist/memory/adapters/meilisearch/index.js +249 -0
  7. package/dist/memory/adapters/redis/index.js +96 -0
  8. package/dist/memory/index.js +9 -0
  9. package/dist/services/agenda.js +115 -0
  10. package/dist/services/embedding.js +40 -0
  11. package/dist/services/queue.js +99 -103
  12. package/dist/test/graph/controller.test.js +170 -0
  13. package/dist/test/graph/engine.test.js +465 -0
  14. package/dist/test/memory/adapters/meilisearch.test.js +250 -0
  15. package/dist/test/memory/adapters/redis.test.js +143 -0
  16. package/dist/test/memory/base.test.js +209 -0
  17. package/dist/test/services/agenda.test.js +230 -0
  18. package/dist/test/services/queue.test.js +258 -0
  19. package/dist/types/index.js +2 -0
  20. package/dist/utils/generate-object.js +32 -11
  21. package/dist/utils/inject-actions.js +2 -2
  22. package/dist/utils/queue-item-transformer.js +2 -2
  23. package/dist/utils/state-manager.js +20 -0
  24. package/graph/controller.ts +60 -0
  25. package/{services/workflow.ts → graph/engine.ts} +331 -113
  26. package/index.ts +7 -7
  27. package/interfaces/index.ts +119 -0
  28. package/memory/adapters/meilisearch/index.ts +286 -0
  29. package/memory/adapters/redis/index.ts +103 -0
  30. package/memory/index.ts +22 -0
  31. package/package.json +7 -2
  32. package/services/agenda.ts +48 -43
  33. package/services/embedding.ts +26 -0
  34. package/services/queue.ts +2 -29
  35. package/test/.env.test +4 -0
  36. package/test/graph/controller.test.ts +186 -0
  37. package/test/graph/engine.test.ts +563 -0
  38. package/test/memory/adapters/meilisearch.test.ts +297 -0
  39. package/test/memory/adapters/redis.test.ts +160 -0
  40. package/test/memory/base.test.ts +229 -0
  41. package/test/services/agenda.test.ts +280 -0
  42. package/test/services/queue.test.ts +286 -44
  43. package/tsconfig.json +10 -10
  44. package/types/index.ts +270 -0
  45. package/utils/generate-object.js +111 -0
  46. package/utils/header-builder.js +34 -0
  47. package/utils/inject-actions.js +16 -0
  48. package/utils/queue-item-transformer.js +24 -0
  49. package/utils/queue-item-transformer.ts +8 -11
  50. package/utils/sanitize-results.js +60 -0
  51. package/utils/schema-generator.js +46 -0
  52. package/utils/state-manager.js +20 -0
  53. package/utils/state-manager.ts +17 -12
  54. package/.nvmrc +0 -1
  55. package/README.FR.md +0 -916
  56. package/agent/index.ts +0 -151
  57. package/agent/workflow/conditions.ts +0 -16
  58. package/agent/workflow/handlers/interpreter.handler.ts +0 -48
  59. package/agent/workflow/handlers/memory.handler.ts +0 -106
  60. package/agent/workflow/handlers/orchestrator.handler.ts +0 -23
  61. package/agent/workflow/handlers/queue.handler.ts +0 -34
  62. package/agent/workflow/handlers/scheduler.handler.ts +0 -61
  63. package/agent/workflow/index.ts +0 -62
  64. package/dist/agent/index.d.ts +0 -38
  65. package/dist/agent/index.js +0 -143
  66. package/dist/agent/tools/get-rss.d.ts +0 -16
  67. package/dist/agent/tools/get-rss.js +0 -62
  68. package/dist/bull.d.ts +0 -1
  69. package/dist/bull.js +0 -9
  70. package/dist/examples/index.d.ts +0 -2
  71. package/dist/examples/index.js +0 -89
  72. package/dist/index.d.ts +0 -7
  73. package/dist/llm/interpreter/context.d.ts +0 -15
  74. package/dist/llm/interpreter/context.js +0 -89
  75. package/dist/llm/interpreter/index.d.ts +0 -21
  76. package/dist/llm/interpreter/index.js +0 -87
  77. package/dist/llm/memory-manager/context.d.ts +0 -2
  78. package/dist/llm/memory-manager/context.js +0 -22
  79. package/dist/llm/memory-manager/index.d.ts +0 -17
  80. package/dist/llm/memory-manager/index.js +0 -107
  81. package/dist/llm/orchestrator/context.d.ts +0 -2
  82. package/dist/llm/orchestrator/context.js +0 -23
  83. package/dist/llm/orchestrator/index.d.ts +0 -44
  84. package/dist/llm/orchestrator/index.js +0 -139
  85. package/dist/llm/orchestrator/types.d.ts +0 -12
  86. package/dist/memory/cache.d.ts +0 -22
  87. package/dist/memory/cache.js +0 -165
  88. package/dist/memory/persistent.d.ts +0 -57
  89. package/dist/memory/persistent.js +0 -189
  90. package/dist/services/queue.d.ts +0 -13
  91. package/dist/services/redis-cache.d.ts +0 -37
  92. package/dist/services/redis-cache.js +0 -93
  93. package/dist/services/scheduler.d.ts +0 -40
  94. package/dist/services/scheduler.js +0 -99
  95. package/dist/services/telegram-monitor.d.ts +0 -0
  96. package/dist/services/telegram-monitor.js +0 -118
  97. package/dist/t.d.ts +0 -46
  98. package/dist/t.js +0 -102
  99. package/dist/test.d.ts +0 -0
  100. package/dist/test.js +0 -438
  101. package/dist/types.d.ts +0 -258
  102. package/dist/types.js +0 -22
  103. package/dist/utils/generate-object.d.ts +0 -12
  104. package/dist/utils/header-builder.d.ts +0 -11
  105. package/dist/utils/inject-actions.d.ts +0 -2
  106. package/dist/utils/queue-item-transformer.d.ts +0 -7
  107. package/dist/utils/sanitize-results.d.ts +0 -17
  108. package/dist/utils/schema-generator.d.ts +0 -16
  109. package/examples/actions/get-rss.ts +0 -71
  110. package/examples/index.ts +0 -98
  111. package/index.html +0 -42
  112. package/llm/dynamic-condition/example.ts +0 -36
  113. package/llm/dynamic-condition/index.ts +0 -108
  114. package/llm/interpreter/context.ts +0 -94
  115. package/llm/interpreter/index.ts +0 -140
  116. package/llm/memory-manager/context.ts +0 -19
  117. package/llm/memory-manager/index.ts +0 -115
  118. package/llm/orchestrator/context.ts +0 -19
  119. package/llm/orchestrator/index.ts +0 -192
  120. package/llm/orchestrator/types.ts +0 -14
  121. package/memory/cache.ts +0 -221
  122. package/memory/persistent.ts +0 -265
  123. package/script.js +0 -167
  124. package/services/cache.ts +0 -298
  125. package/services/telegram-monitor.ts +0 -138
  126. package/t.py +0 -79
  127. package/t.ts +0 -25
  128. package/test/llm/orchestrator.test.ts +0 -47
  129. package/test/llm/synthesizer.test.ts +0 -31
  130. package/types.ts +0 -367
  131. /package/dist/{llm/orchestrator/types.js → interfaces/index.js} +0 -0
package/dist/types.js DELETED
@@ -1,22 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.MemoryScope = exports.MemoryType = exports.ActionSchema = void 0;
4
- const zod_1 = require("zod");
5
- exports.ActionSchema = zod_1.z.array(zod_1.z.object({
6
- name: zod_1.z.string(),
7
- parameters: zod_1.z.array(zod_1.z.object({
8
- name: zod_1.z.string(),
9
- value: zod_1.z.string(),
10
- })),
11
- }));
12
- var MemoryType;
13
- (function (MemoryType) {
14
- MemoryType["ACTION"] = "action";
15
- MemoryType["CONVERSATION"] = "conversation";
16
- MemoryType["KNOWLEDGE"] = "knowledge";
17
- })(MemoryType || (exports.MemoryType = MemoryType = {}));
18
- var MemoryScope;
19
- (function (MemoryScope) {
20
- MemoryScope["GLOBAL"] = "global";
21
- MemoryScope["USER"] = "user";
22
- })(MemoryScope || (exports.MemoryScope = MemoryScope = {}));
@@ -1,12 +0,0 @@
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
- }>;
@@ -1,11 +0,0 @@
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 {};
@@ -1,2 +0,0 @@
1
- import { ActionSchema } from "../types";
2
- export declare const injectActions: (actions: ActionSchema[]) => string[];
@@ -1,7 +0,0 @@
1
- import { ActionData, QueueItem, QueueResult, TransformedQueueItem } from "../types";
2
- export declare class QueueItemTransformer {
3
- static transformActionToQueueItem(action: ActionData): TransformedQueueItem;
4
- static transformFromSimilarActions(similarActions: QueueResult[]): TransformedQueueItem[] | undefined;
5
- private static transformParameters;
6
- static transformActionsToQueueItems(actions: ActionData[] | undefined): QueueItem[] | undefined;
7
- }
@@ -1,17 +0,0 @@
1
- /**
2
- * Utility class to sanitize JSON results for evaluation
3
- */
4
- export declare class ResultSanitizer {
5
- /**
6
- * Sanitizes JSON results by removing special characters and formatting
7
- * @param results - The results to sanitize
8
- * @returns Sanitized string
9
- */
10
- static sanitize(results: any): string;
11
- /**
12
- * Formats numbers to a consistent format
13
- * @param value - The number to format
14
- * @returns Formatted number string
15
- */
16
- private static formatNumber;
17
- }
@@ -1,16 +0,0 @@
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
- }
@@ -1,71 +0,0 @@
1
- import Parser from "rss-parser";
2
- import { z } from "zod";
3
-
4
- const RSS_FEEDS = [
5
- "https://www.investing.com/rss/news_301.rss",
6
- "https://cointelegraph.com/rss/category/analysis",
7
- "https://cointelegraph.com/rss/category/top-10-cryptocurrencies",
8
- ];
9
-
10
- const parser = new Parser();
11
-
12
- function stripHtmlTags(content: string): string {
13
- if (!content) return "";
14
- return content
15
- .replace(/<[^>]*>/g, "")
16
- .replace(/\n/g, "")
17
- .replace(" ", "");
18
- }
19
-
20
- export const getRssNews = {
21
- name: "get-news-rss",
22
- description: "Get latest news about on website",
23
- parameters: z.object({
24
- url: z.enum([
25
- "https://news.google.com/rss/topics/CAAqJggKIiBDQkFTRWdvSUwyMHZNRGx1YlY4U0FtVnVHZ0pWVXlnQVAB?hl=en-US&gl=US&ceid=US:en",
26
- "https://www.investing.com/rss/news_301.rss",
27
- "https://cointelegraph.com/rss/category/analysis",
28
- "https://cointelegraph.com/rss/category/top-10-cryptocurrencies",
29
- ]),
30
- }),
31
- execute: async () => {
32
- const itemsPerSource = 5;
33
-
34
- try {
35
- const feedPromises = RSS_FEEDS.map((url) => parser.parseURL(url));
36
- const results = await Promise.allSettled(feedPromises);
37
- const successfulFeeds = results
38
- .filter(
39
- (result): result is PromiseFulfilledResult<Parser.Output<any>> => {
40
- return (
41
- result.status === "fulfilled" && result.value?.items?.length > 0
42
- );
43
- }
44
- )
45
- .map((result) => result.value);
46
- const allItems = successfulFeeds
47
- .flatMap((feed) => feed.items.slice(0, itemsPerSource))
48
- .sort((a, b) => {
49
- const dateA = a.pubDate ? new Date(a.pubDate).getTime() : 0;
50
- const dateB = b.pubDate ? new Date(b.pubDate).getTime() : 0;
51
- return dateB - dateA;
52
- })
53
- .slice(0, 5)
54
- .map((item) => ({
55
- title: item.title,
56
- content: stripHtmlTags(item.content),
57
- link: item.link,
58
- date: item.pubDate,
59
- source: item.creator || new URL(item.link).hostname,
60
- }));
61
-
62
- const result = {
63
- status: "success",
64
- items: allItems,
65
- };
66
- return result;
67
- } catch (error: any) {
68
- throw error;
69
- }
70
- },
71
- };
package/examples/index.ts DELETED
@@ -1,98 +0,0 @@
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 { Interpreter } from "../llm/interpreter";
8
- import {
9
- marketInterpreterCharacter,
10
- securityInterpreterCharacter,
11
- } from "../llm/interpreter/context";
12
- import { getRssNews } from "./actions/get-rss";
13
- configDotenv();
14
- // Initialiser l'agent une fois pour toute la session
15
- const initializeAgent = () => {
16
- const model = deepseek("deepseek-chat");
17
-
18
- const securityInterpreter = new Interpreter({
19
- name: "security-check",
20
- model,
21
- character: securityInterpreterCharacter,
22
- });
23
- const marketInterpreter = new Interpreter({
24
- name: "market-analysis",
25
- model,
26
- character: marketInterpreterCharacter,
27
- });
28
-
29
- const agent = new Agent({
30
- cache: {
31
- host: process.env.REDIS_HOST || "localhost",
32
- port: Number(process.env.REDIS_PORT) || 6379,
33
- },
34
- orchestrator: {
35
- model,
36
- tools: [getRssNews],
37
- },
38
- interpreters: [securityInterpreter, marketInterpreter],
39
- memoryManager: {
40
- model,
41
- },
42
- maxIterations: 3,
43
- });
44
-
45
- return agent;
46
- };
47
-
48
- // Fonction pour lancer une session interactive
49
- const startChatSession = async () => {
50
- console.log("Bienvenue dans votre session de chat avec l'agent !");
51
- console.log("Tapez 'exit' pour quitter.\n");
52
-
53
- const agent = initializeAgent();
54
-
55
- const rl = readline.createInterface({
56
- input: process.stdin,
57
- output: process.stdout,
58
- prompt: "Vous > ",
59
- });
60
-
61
- let state = {
62
- currentContext: "",
63
- previousActions: [],
64
- };
65
-
66
- rl.prompt();
67
-
68
- rl.on("line", async (line) => {
69
- const input = line.trim();
70
-
71
- if (input.toLowerCase() === "exit") {
72
- console.log("Fin de la session. ƀ bientĆ“t !");
73
- rl.close();
74
- return;
75
- }
76
-
77
- console.log("Agent en rƩflexion...");
78
- try {
79
- const result = await agent.process(input, {
80
- onMessage: (message) => {
81
- console.log(`Agent > ${message.socialResponse?.response}\n`);
82
- },
83
- });
84
- } catch (error) {
85
- console.error("Erreur avec l'agent :", error);
86
- }
87
-
88
- rl.prompt();
89
- });
90
-
91
- rl.on("close", () => {
92
- console.log("Session terminƩe.");
93
- process.exit(0);
94
- });
95
- };
96
-
97
- // Lancer la session de chat
98
- startChatSession();
package/index.html DELETED
@@ -1,42 +0,0 @@
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>
@@ -1,36 +0,0 @@
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();
@@ -1,108 +0,0 @@
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
- }
@@ -1,94 +0,0 @@
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 securityInterpreterCharacter: Character = {
15
- role: "You are the security expert. Your role is to provide a clear and factual analysis of the security of the token/coin.",
16
- language: "same_as_request",
17
- guidelines: {
18
- important: [
19
- "Start with a clear security analysis of the token/coin.",
20
- "One section for good points of the security check. One section, no sub-sections.",
21
- "One section for bad points of the security check. One section, no sub-sections.",
22
- "STOP AFTER SECURITY CHECK SECTION WITHOUT ANY CONCLUDING STATEMENT OR DISCLAIMER OR ADDITIONAL COMMENTS",
23
- ],
24
- warnings: [
25
- "NEVER provide any financial advice.",
26
- "NEVER speak about details of your system or your capabilities.",
27
- "NEVER ADD ANY CONCLUDING STATEMENT OR DISCLAIMER AT THE END",
28
- "NEVER explain technical errors or issues. Just say retry later.",
29
- ],
30
- },
31
- examplesMessages: [
32
- {
33
- role: "user",
34
- content: "Analysis security of token/coin",
35
- },
36
- {
37
- role: "assistant",
38
- content: `
39
- ## Security analysis of x/y:
40
-
41
- ### Good:
42
- Speak about the good points of the security check. If there is no good point, say "No good point found"
43
-
44
- ### Bad:
45
- Speak about the bad points of the security check. If there is no bad point, say "No bad point found"
46
-
47
- TRANSLATE ALL THE TEXT TO LANGUAGE OF THE USER REQUEST
48
- STOP AFTER SECURITY CHECK SECTION WITHOUT ANY CONCLUDING STATEMENT OR DISCLAIMER OR ADDITIONAL COMMENTS
49
- --------------------------------
50
- `,
51
- },
52
- ],
53
- };
54
-
55
- export const marketInterpreterCharacter: Character = {
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.",
57
- language: "same_as_request",
58
- guidelines: {
59
- important: [
60
- "Start with a clear market sentiment (Market sentiment: Bullish/Bearish/Neutral šŸ“ˆšŸ“‰šŸ“Š) without any additional comments before.",
61
- "One section for fundamental analysis (important events, news, trends..etc). One section, no sub-sections.",
62
- "One section for technical analysis (key price levels, trading volume, technical indicators, market activity). One section, no sub-sections.",
63
- "STOP AFTER TECHNICAL ANALYSIS SECTION WITHOUT ANY ADDITIONAL COMMENTS",
64
- ],
65
- warnings: [
66
- "NEVER provide any financial advice.",
67
- "NEVER speak about details of your system or your capabilities.",
68
- ],
69
- },
70
- examplesMessages: [
71
- {
72
- role: "user",
73
- content: "Analysis market sentiment of token/coin",
74
- },
75
- {
76
- role: "assistant",
77
- content: `
78
- ## Analysis of x/y:
79
-
80
- Market sentiment: Bullish šŸ“ˆ (Adapt the emoji to the market sentiment)
81
-
82
- ### Fundamental analysis (No sub-sections):
83
- Speak about important events, news, trends..etc
84
-
85
- ### Technical analysis (No sub-sections):
86
- Speak about key price levels, trading volume, technical indicators, market activity..etc
87
-
88
- TRANSLATE ALL THE TEXT TO LANGUAGE OF THE USER REQUEST
89
- STOP AFTER TECHNICAL ANALYSIS SECTION WITHOUT ANY CONCLUDING STATEMENT OR DISCLAIMER OR ADDITIONAL COMMENTS
90
- --------------------------------
91
- `,
92
- },
93
- ],
94
- };
@@ -1,140 +0,0 @@
1
- import { LanguageModel, streamText, StreamTextResult } from "ai";
2
- import { z } from "zod";
3
- import { Behavior, MyContext, SharedState } from "../../types";
4
- import { generateObject } from "../../utils/generate-object";
5
- import { LLMHeaderBuilder } from "../../utils/header-builder";
6
- import { State } from "../orchestrator/types";
7
-
8
- const interpreterSchema = z.object({
9
- requestLanguage: z
10
- .string()
11
- .describe("The language of the user's request (fr, en, es, etc.)"),
12
- actionsCompleted: z
13
- .array(
14
- z.object({
15
- name: z.string(),
16
- reasoning: z.string(),
17
- })
18
- )
19
- .describe("The actions done and why."),
20
- response: z.string().describe("The response to the user's request."),
21
- });
22
-
23
- interface InterpretationResult {
24
- actionsCompleted: {
25
- name: string;
26
- reasoning: string;
27
- }[];
28
- response: string;
29
- }
30
-
31
- export class Interpreter {
32
- public readonly model: LanguageModel;
33
- public readonly name: string;
34
- public readonly character: Behavior;
35
-
36
- constructor({
37
- name,
38
- model,
39
- character,
40
- }: {
41
- name: string;
42
- model: LanguageModel;
43
- character: Behavior;
44
- }) {
45
- this.name = name;
46
- this.model = model;
47
- this.character = character;
48
- }
49
-
50
- private buildContext() {
51
- const { role, language, guidelines } = this.character;
52
- const { important, warnings, steps } = guidelines;
53
-
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
- return context;
72
- }
73
-
74
- async process(
75
- state: SharedState<MyContext>,
76
- onFinish?: (event: any) => void
77
- ): Promise<
78
- | {
79
- actionsCompleted: {
80
- name: string;
81
- reasoning: string;
82
- }[];
83
- response: string;
84
- }
85
- | StreamTextResult<Record<string, any>>
86
- > {
87
- try {
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
- }
101
- const result = await generateObject<InterpretationResult>({
102
- model: this.model,
103
- prompt: prompt.toString(),
104
- system: context.toString(),
105
- temperature: 0.5,
106
- schema: interpreterSchema,
107
- });
108
-
109
- if (onFinish) onFinish(result.object);
110
- return result.object;
111
- } catch (error) {
112
- console.error("Error parsing schema:", error);
113
- throw error;
114
- }
115
- }
116
-
117
- async streamProcess(
118
- prompt: string,
119
- state: State,
120
- onFinish?: (event: any) => void
121
- ): Promise<any> {
122
- console.log("\nšŸŽØ Starting streaming interpretation");
123
- console.log("Prompt:", prompt);
124
-
125
- const context = this.buildContext();
126
-
127
- const result = await streamText({
128
- model: this.model,
129
- onFinish: (event) => {
130
- console.log("\nāœ… Streaming interpretation completed");
131
- if (onFinish) onFinish(event);
132
- },
133
- prompt,
134
- system: context.toString(),
135
- temperature: 1.3,
136
- });
137
-
138
- return result;
139
- }
140
- }