@ai.ntellect/core 0.1.83 → 0.1.85
Sign up to get free protection for your applications and to get access to all the features.
- package/agent/index.ts +52 -25
- package/dist/agent/index.d.ts +1 -0
- package/dist/agent/index.js +41 -22
- package/dist/llm/evaluator/context.js +3 -5
- package/dist/llm/evaluator/index.js +25 -29
- package/dist/llm/orchestrator/index.js +10 -13
- package/dist/llm/synthesizer/index.d.ts +1 -5
- package/dist/llm/synthesizer/index.js +1 -5
- package/dist/memory/cache.d.ts +1 -1
- package/dist/memory/cache.js +2 -35
- package/dist/memory/persistent.d.ts +1 -1
- package/dist/memory/persistent.js +3 -3
- package/dist/test.d.ts +28 -0
- package/dist/test.js +36 -4
- package/dist/types.d.ts +26 -1
- package/dist/types.js +9 -1
- package/dist/utils/queue-item-transformer.d.ts +2 -2
- package/dist/utils/queue-item-transformer.js +5 -6
- package/dist/utils/sanitize-results.d.ts +17 -0
- package/dist/utils/sanitize-results.js +60 -0
- package/llm/evaluator/context.ts +29 -25
- package/llm/evaluator/index.ts +25 -31
- package/llm/orchestrator/index.ts +9 -17
- package/llm/synthesizer/index.ts +2 -10
- package/memory/cache.ts +4 -42
- package/memory/persistent.ts +3 -3
- package/package.json +1 -1
- package/types.ts +13 -1
- package/utils/queue-item-transformer.ts +25 -11
- package/utils/sanitize-results.ts +66 -0
package/dist/test.js
CHANGED
@@ -3,13 +3,41 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
3
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
4
4
|
};
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
6
|
-
exports.getRssNews = exports.getChainsTVL = void 0;
|
6
|
+
exports.getRssNews = exports.getChainsTVL = exports.fetchMarkPrice = void 0;
|
7
|
+
const ccxt_1 = __importDefault(require("ccxt"));
|
7
8
|
const rss_parser_1 = __importDefault(require("rss-parser"));
|
8
9
|
const zod_1 = require("zod");
|
9
10
|
const agent_1 = require("./agent");
|
10
11
|
const orchestrator_1 = require("./llm/orchestrator");
|
11
12
|
const cache_1 = require("./memory/cache");
|
12
13
|
const persistent_1 = require("./memory/persistent");
|
14
|
+
exports.fetchMarkPrice = {
|
15
|
+
name: "fetch-mark-price",
|
16
|
+
description: "Fetches mark price for the market",
|
17
|
+
parameters: zod_1.z.object({
|
18
|
+
symbol: zod_1.z
|
19
|
+
.string()
|
20
|
+
.describe("Unified symbol of the market to fetch the ticker for (default: BTC/USDT)"),
|
21
|
+
params: zod_1.z.object({
|
22
|
+
subType: zod_1.z
|
23
|
+
.string()
|
24
|
+
.describe("Type of funding rate: 'linear' or 'inverse'"),
|
25
|
+
}),
|
26
|
+
}),
|
27
|
+
execute: async ({ symbol, params }) => {
|
28
|
+
try {
|
29
|
+
const binance = new ccxt_1.default.binance({});
|
30
|
+
// Fetch mark price from the Binance API
|
31
|
+
const markPrice = await binance.fetchMarkPrice(symbol, params);
|
32
|
+
console.log("Mark price fetched:", markPrice);
|
33
|
+
return markPrice;
|
34
|
+
}
|
35
|
+
catch (error) {
|
36
|
+
console.error("Error fetching mark price:", error);
|
37
|
+
throw error;
|
38
|
+
}
|
39
|
+
},
|
40
|
+
};
|
13
41
|
exports.getChainsTVL = {
|
14
42
|
name: "get_chains_tvl",
|
15
43
|
description: "Get current TVL (Total Value Locked) of all chains from DeFiLlama",
|
@@ -53,7 +81,11 @@ exports.getChainsTVL = {
|
|
53
81
|
}
|
54
82
|
},
|
55
83
|
};
|
56
|
-
const RSS_FEEDS = [
|
84
|
+
const RSS_FEEDS = [
|
85
|
+
"https://www.investing.com/rss/news_301.rss",
|
86
|
+
"https://cointelegraph.com/rss/category/analysis",
|
87
|
+
"https://cointelegraph.com/rss/category/top-10-cryptocurrencies",
|
88
|
+
];
|
57
89
|
const parser = new rss_parser_1.default();
|
58
90
|
function stripHtmlTags(content) {
|
59
91
|
if (!content)
|
@@ -109,7 +141,7 @@ exports.getRssNews = {
|
|
109
141
|
host: "http://localhost:7700",
|
110
142
|
apiKey: "aSampleMasterKey",
|
111
143
|
});
|
112
|
-
const orchestrator = new orchestrator_1.Orchestrator([exports.getRssNews, exports.getChainsTVL], memory);
|
144
|
+
const orchestrator = new orchestrator_1.Orchestrator([exports.getRssNews, exports.getChainsTVL, exports.fetchMarkPrice], memory);
|
113
145
|
const agent = new agent_1.Agent({
|
114
146
|
user: {
|
115
147
|
id: "1",
|
@@ -120,7 +152,7 @@ exports.getRssNews = {
|
|
120
152
|
stream: false,
|
121
153
|
maxEvaluatorIteration: 1,
|
122
154
|
});
|
123
|
-
const prompt = "
|
155
|
+
const prompt = "analyse le ai16z";
|
124
156
|
const context = prompt;
|
125
157
|
// const save = await cacheMemory.createMemory({
|
126
158
|
// content: prompt,
|
package/dist/types.d.ts
CHANGED
@@ -101,7 +101,7 @@ export interface CacheMemoryOptions {
|
|
101
101
|
export interface CreateMemoryInput {
|
102
102
|
content: any;
|
103
103
|
type: MemoryType;
|
104
|
-
data:
|
104
|
+
data: QueueResult[];
|
105
105
|
userId?: string;
|
106
106
|
scope?: MemoryScope;
|
107
107
|
}
|
@@ -135,6 +135,31 @@ export interface Memory {
|
|
135
135
|
createdAt: Date;
|
136
136
|
chunks?: MemoryChunk[];
|
137
137
|
}
|
138
|
+
export declare const ActionSchema: z.ZodArray<z.ZodObject<{
|
139
|
+
name: z.ZodString;
|
140
|
+
parameters: z.ZodArray<z.ZodObject<{
|
141
|
+
name: z.ZodString;
|
142
|
+
value: z.ZodString;
|
143
|
+
}, "strip", z.ZodTypeAny, {
|
144
|
+
value: string;
|
145
|
+
name: string;
|
146
|
+
}, {
|
147
|
+
value: string;
|
148
|
+
name: string;
|
149
|
+
}>, "many">;
|
150
|
+
}, "strip", z.ZodTypeAny, {
|
151
|
+
name: string;
|
152
|
+
parameters: {
|
153
|
+
value: string;
|
154
|
+
name: string;
|
155
|
+
}[];
|
156
|
+
}, {
|
157
|
+
name: string;
|
158
|
+
parameters: {
|
159
|
+
value: string;
|
160
|
+
name: string;
|
161
|
+
}[];
|
162
|
+
}>, "many">;
|
138
163
|
export declare enum MemoryType {
|
139
164
|
ACTION = "action",
|
140
165
|
CONVERSATION = "conversation",
|
package/dist/types.js
CHANGED
@@ -1,6 +1,14 @@
|
|
1
1
|
"use strict";
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
3
|
-
exports.MemoryScope = exports.MemoryType = void 0;
|
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
|
+
}));
|
4
12
|
var MemoryType;
|
5
13
|
(function (MemoryType) {
|
6
14
|
MemoryType["ACTION"] = "action";
|
@@ -1,7 +1,7 @@
|
|
1
|
-
import { ActionData, TransformedQueueItem } from "../types";
|
1
|
+
import { ActionData, QueueResult, TransformedQueueItem } from "../types";
|
2
2
|
export declare class QueueItemTransformer {
|
3
3
|
static transformActionToQueueItem(action: ActionData): TransformedQueueItem;
|
4
|
-
static transformFromSimilarActions(similarActions:
|
4
|
+
static transformFromSimilarActions(similarActions: QueueResult[]): TransformedQueueItem[] | undefined;
|
5
5
|
private static transformParameters;
|
6
6
|
static transformActionsToQueueItems(actions: ActionData[] | undefined): TransformedQueueItem[] | undefined;
|
7
7
|
}
|
@@ -4,22 +4,21 @@ exports.QueueItemTransformer = void 0;
|
|
4
4
|
class QueueItemTransformer {
|
5
5
|
static transformActionToQueueItem(action) {
|
6
6
|
return {
|
7
|
-
name: action.name ||
|
8
|
-
parameters: QueueItemTransformer.transformParameters(action.parameters || {})
|
7
|
+
name: action.name || "",
|
8
|
+
parameters: QueueItemTransformer.transformParameters(action.parameters || {}),
|
9
9
|
};
|
10
10
|
}
|
11
11
|
static transformFromSimilarActions(similarActions) {
|
12
|
-
|
13
|
-
return firstMatch?.map((action) => QueueItemTransformer.transformActionToQueueItem(action));
|
12
|
+
return similarActions?.map((action) => QueueItemTransformer.transformActionToQueueItem(action));
|
14
13
|
}
|
15
14
|
static transformParameters(parameters) {
|
16
15
|
return Object.entries(parameters).map(([name, value]) => ({
|
17
16
|
name,
|
18
|
-
value: typeof value ===
|
17
|
+
value: typeof value === "object" ? JSON.stringify(value) : String(value),
|
19
18
|
}));
|
20
19
|
}
|
21
20
|
static transformActionsToQueueItems(actions) {
|
22
|
-
return actions?.map(action => this.transformActionToQueueItem(action));
|
21
|
+
return actions?.map((action) => this.transformActionToQueueItem(action));
|
23
22
|
}
|
24
23
|
}
|
25
24
|
exports.QueueItemTransformer = QueueItemTransformer;
|
@@ -0,0 +1,17 @@
|
|
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
|
+
}
|
@@ -0,0 +1,60 @@
|
|
1
|
+
"use strict";
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
3
|
+
exports.ResultSanitizer = void 0;
|
4
|
+
/**
|
5
|
+
* Utility class to sanitize JSON results for evaluation
|
6
|
+
*/
|
7
|
+
class ResultSanitizer {
|
8
|
+
/**
|
9
|
+
* Sanitizes JSON results by removing special characters and formatting
|
10
|
+
* @param results - The results to sanitize
|
11
|
+
* @returns Sanitized string
|
12
|
+
*/
|
13
|
+
static sanitize(results) {
|
14
|
+
if (!results)
|
15
|
+
return "";
|
16
|
+
try {
|
17
|
+
const jsonString = JSON.stringify(results);
|
18
|
+
return (jsonString
|
19
|
+
// Basic cleanup
|
20
|
+
.replace(/\\n/g, " ") // Remove newlines
|
21
|
+
.replace(/\s+/g, " ") // Remove extra spaces
|
22
|
+
.replace(/\\"/g, '"') // Fix escaped quotes
|
23
|
+
.replace(/\\+/g, "") // Remove extra backslashes
|
24
|
+
// Remove unnecessary quotes around objects and arrays
|
25
|
+
.replace(/"\[/g, "[") // Remove quotes around arrays start
|
26
|
+
.replace(/\]"/g, "]") // Remove quotes around arrays end
|
27
|
+
.replace(/"{/g, "{") // Remove quotes around objects start
|
28
|
+
.replace(/}"/g, "}") // Remove quotes around objects end
|
29
|
+
// Clean up numbers and values
|
30
|
+
.replace(/"(\d+\.?\d*)"/g, "$1") // Remove quotes around numbers
|
31
|
+
.replace(/:\s*"(true|false|null)"/g, ": $1") // Remove quotes around booleans and null
|
32
|
+
// Clean up URLs and content
|
33
|
+
.replace(/(?<=content":")([^"]+)(?=")/g, (match) => match.trim().replace(/\s+/g, " ") // Clean content spacing
|
34
|
+
)
|
35
|
+
.replace(/(?<=link":")([^"]+)(?=")/g, (match) => match.replace(/&/g, "&") // Fix URL encodings
|
36
|
+
)
|
37
|
+
// Final cleanup
|
38
|
+
.replace(/,\s*([}\]])/g, "$1") // Remove trailing commas
|
39
|
+
.replace(/:\s+/g, ":") // Remove spaces after colons
|
40
|
+
.replace(/,\s+/g, ",") // Remove spaces after commas
|
41
|
+
.trim()); // Remove leading/trailing whitespace
|
42
|
+
}
|
43
|
+
catch (error) {
|
44
|
+
console.error("Error sanitizing results:", error);
|
45
|
+
return String(results);
|
46
|
+
}
|
47
|
+
}
|
48
|
+
/**
|
49
|
+
* Formats numbers to a consistent format
|
50
|
+
* @param value - The number to format
|
51
|
+
* @returns Formatted number string
|
52
|
+
*/
|
53
|
+
static formatNumber(value) {
|
54
|
+
return value.toLocaleString("en-US", {
|
55
|
+
maximumFractionDigits: 2,
|
56
|
+
useGrouping: false,
|
57
|
+
});
|
58
|
+
}
|
59
|
+
}
|
60
|
+
exports.ResultSanitizer = ResultSanitizer;
|
package/llm/evaluator/context.ts
CHANGED
@@ -1,39 +1,43 @@
|
|
1
1
|
import { ActionSchema } from "../../types";
|
2
2
|
import { injectActions } from "../../utils/inject-actions";
|
3
|
-
|
4
3
|
export const evaluatorContext = {
|
5
4
|
role: "You are the evaluator agent. Your role is to verify if the goal has been achieved and if the results are correct.",
|
6
5
|
guidelines: {
|
7
6
|
important: [
|
8
|
-
"Verify if all required actions were executed successfully",
|
9
|
-
"Check if the results
|
10
|
-
"Identify
|
11
|
-
"
|
7
|
+
"Verify if all required actions were executed successfully.",
|
8
|
+
"Check if the results align with the initial goal.",
|
9
|
+
"Identify and extract additional relevant information naturally during the process. Examples:",
|
10
|
+
" - Link a token symbol (e.g., 'USDC') to its address (e.g., '0xA0b8...6EB48').",
|
11
|
+
" - Associate a wallet address (e.g., '0x1234...abcd') to a user-friendly name (e.g., 'Work Wallet').",
|
12
|
+
" - Map a token address (e.g., '0x6B17...71d0F') back to its symbol or name (e.g., 'DAI').",
|
13
|
+
"Store these facts in memory with their type (episodic, semantic, or procedural).",
|
12
14
|
],
|
13
15
|
warnings: [
|
14
|
-
"NEVER modify the results directly",
|
15
|
-
"NEVER make assumptions about missing data",
|
16
|
-
"NEVER repeat
|
16
|
+
"NEVER modify the results directly.",
|
17
|
+
"NEVER make assumptions about missing data.",
|
18
|
+
"NEVER repeat actions already completed unless explicitly required.",
|
17
19
|
],
|
18
20
|
},
|
19
21
|
compose: (goal: string, results: string, tools: ActionSchema[]) => {
|
20
22
|
return `
|
21
|
-
|
22
|
-
|
23
|
-
|
24
|
-
|
25
|
-
|
26
|
-
|
27
|
-
|
28
|
-
|
29
|
-
|
30
|
-
|
31
|
-
|
32
|
-
|
33
|
-
|
34
|
-
|
35
|
-
|
36
|
-
|
37
|
-
|
23
|
+
You are evaluating if the following goal has been achieved: "${goal}".
|
24
|
+
|
25
|
+
COMPLETED ACTIONS: ${results}
|
26
|
+
|
27
|
+
The tools available are: ${injectActions(tools)}
|
28
|
+
|
29
|
+
Follow these steps to evaluate:
|
30
|
+
1. Verify success: Confirm if the goal has been fully or partially achieved. If partially, describe what's missing.
|
31
|
+
2. Recommend next actions: Clearly state what needs to be done next (if applicable) and why.
|
32
|
+
3. Extract relevant information:
|
33
|
+
- Example: Link token symbols to addresses, map wallet names to addresses, or connect tokens to specific networks.
|
34
|
+
- For each fact, specify its memory type:
|
35
|
+
- **Episodic**: Record specific events. Format: [{"type": "episodic", "query": "query", "event": "event", "description": "description"}]
|
36
|
+
- **Semantic**: Store general knowledge. Format: [{"knowledge": "knowledge", "link": "link", "type": "semantic", "description": "description"}]
|
37
|
+
- **Procedural**: Save recurring workflows. Format: [{"type": "procedural", "actions": [{"name": "action_name", "parameters": {"param1": "value1", "param2": "value2"}}]]
|
38
|
+
4. Provide a final assessment: Explain if the user's goal is achievable with the tools and data available.
|
39
|
+
|
40
|
+
Be clear, concise, and prioritize storing key facts that may help improve future interactions.
|
41
|
+
`;
|
38
42
|
},
|
39
43
|
};
|
package/llm/evaluator/index.ts
CHANGED
@@ -20,24 +20,18 @@ export class Evaluator {
|
|
20
20
|
const response = await generateObject({
|
21
21
|
model: this.model,
|
22
22
|
schema: z.object({
|
23
|
-
|
24
|
-
|
25
|
-
name: z.string(),
|
26
|
-
parameters: z.object({
|
27
|
-
name: z.string(),
|
28
|
-
value: z.string(),
|
29
|
-
}),
|
30
|
-
})
|
31
|
-
),
|
32
|
-
why: z.string(),
|
33
|
-
isImportantToRemember: z.boolean(),
|
34
|
-
importantToRemembers: z.array(
|
23
|
+
isRemindNeeded: z.boolean(),
|
24
|
+
extraInformationsToRemember: z.array(
|
35
25
|
z.object({
|
36
26
|
memoryType: z.string(),
|
37
|
-
|
38
|
-
|
27
|
+
content: z.string(),
|
28
|
+
data: z.string(),
|
39
29
|
})
|
40
30
|
),
|
31
|
+
response: z.string(),
|
32
|
+
isNextActionNeeded: z.boolean(),
|
33
|
+
nextActionsNeeded: ActionSchema,
|
34
|
+
why: z.string(),
|
41
35
|
}),
|
42
36
|
prompt: prompt,
|
43
37
|
system: evaluatorContext.compose(goal, results, this.tools),
|
@@ -45,17 +39,17 @@ export class Evaluator {
|
|
45
39
|
|
46
40
|
const validatedResponse = {
|
47
41
|
...response.object,
|
48
|
-
nextActions: response.object.
|
42
|
+
nextActions: response.object.nextActionsNeeded.map((action) => ({
|
49
43
|
...action,
|
50
44
|
parameters: action.parameters || {},
|
51
45
|
})),
|
52
46
|
};
|
53
47
|
|
54
|
-
if (validatedResponse.
|
55
|
-
for (const item of validatedResponse.
|
48
|
+
if (validatedResponse.isRemindNeeded) {
|
49
|
+
for (const item of validatedResponse.extraInformationsToRemember) {
|
56
50
|
// Check if the item is already in the memory
|
57
51
|
const memories = await this.memory.searchSimilarQueries(
|
58
|
-
item.
|
52
|
+
item.content,
|
59
53
|
{
|
60
54
|
similarityThreshold: 95,
|
61
55
|
}
|
@@ -68,14 +62,14 @@ export class Evaluator {
|
|
68
62
|
}
|
69
63
|
if (memories.length === 0) {
|
70
64
|
console.log("Adding to memory", {
|
71
|
-
query: item.
|
72
|
-
data: item.
|
65
|
+
query: item.content,
|
66
|
+
data: item.data,
|
73
67
|
});
|
74
|
-
await this.memory.
|
68
|
+
await this.memory.createMemory({
|
75
69
|
id: crypto.randomUUID(),
|
76
70
|
purpose: item.memoryType,
|
77
|
-
query: item.
|
78
|
-
data: item.
|
71
|
+
query: item.content,
|
72
|
+
data: item.data,
|
79
73
|
scope: MemoryScope.GLOBAL,
|
80
74
|
createdAt: new Date(),
|
81
75
|
});
|
@@ -91,22 +85,22 @@ export class Evaluator {
|
|
91
85
|
console.log("Evaluator error");
|
92
86
|
console.dir(error.value, { depth: null });
|
93
87
|
console.error(error.message);
|
94
|
-
if (error.value.
|
95
|
-
for (const item of error.value.
|
88
|
+
if (error.value.extraInformationsToRemember.length > 0) {
|
89
|
+
for (const item of error.value.extraInformationsToRemember) {
|
96
90
|
// Check if the item is already in the memory
|
97
91
|
const memories = await this.memory.searchSimilarQueries(
|
98
|
-
item.
|
92
|
+
item.content
|
99
93
|
);
|
100
94
|
if (memories.length === 0) {
|
101
95
|
console.log("Adding to memory", {
|
102
|
-
query: item.
|
103
|
-
data: item.
|
96
|
+
query: item.content,
|
97
|
+
data: item.data,
|
104
98
|
});
|
105
|
-
await this.memory.
|
99
|
+
await this.memory.createMemory({
|
106
100
|
id: crypto.randomUUID(),
|
107
101
|
purpose: "importantToRemember",
|
108
|
-
query: item.
|
109
|
-
data: item.
|
102
|
+
query: item.content,
|
103
|
+
data: item.data,
|
110
104
|
scope: MemoryScope.USER,
|
111
105
|
createdAt: new Date(),
|
112
106
|
});
|
@@ -21,19 +21,21 @@ export class Orchestrator implements BaseLLM {
|
|
21
21
|
query: z.string(),
|
22
22
|
}),
|
23
23
|
execute: async ({ query }: { query: string }) => {
|
24
|
-
const memories = await this.memory.searchSimilarQueries(query
|
24
|
+
const memories = await this.memory.searchSimilarQueries(query, {
|
25
|
+
similarityThreshold: 95,
|
26
|
+
});
|
25
27
|
return memories;
|
26
28
|
},
|
27
29
|
},
|
28
30
|
{
|
29
31
|
name: "save_memory",
|
30
|
-
description: "Save
|
32
|
+
description: "Save relevant information in the internal knowledge base",
|
31
33
|
parameters: z.object({
|
32
34
|
query: z.string(),
|
33
|
-
|
35
|
+
memoryType: z.string(),
|
34
36
|
data: z.any(),
|
35
|
-
scope: z.
|
36
|
-
userId: z.string()
|
37
|
+
scope: z.string().default("GLOBAL").describe("GLOBAL or USER"),
|
38
|
+
userId: z.string(),
|
37
39
|
whyStored: z.string(),
|
38
40
|
}),
|
39
41
|
execute: async ({
|
@@ -49,7 +51,7 @@ export class Orchestrator implements BaseLLM {
|
|
49
51
|
scope: MemoryScopeType;
|
50
52
|
userId?: string;
|
51
53
|
}) => {
|
52
|
-
const memories = await this.memory.
|
54
|
+
const memories = await this.memory.createMemory({
|
53
55
|
query,
|
54
56
|
purpose,
|
55
57
|
data,
|
@@ -69,17 +71,7 @@ export class Orchestrator implements BaseLLM {
|
|
69
71
|
const response = await generateObject({
|
70
72
|
model: this.model,
|
71
73
|
schema: z.object({
|
72
|
-
actions:
|
73
|
-
z.object({
|
74
|
-
name: z.string(),
|
75
|
-
parameters: z.array(
|
76
|
-
z.object({
|
77
|
-
name: z.string(),
|
78
|
-
value: z.string(),
|
79
|
-
})
|
80
|
-
),
|
81
|
-
})
|
82
|
-
),
|
74
|
+
actions: ActionSchema,
|
83
75
|
answer: z.string(),
|
84
76
|
}),
|
85
77
|
prompt: prompt,
|
package/llm/synthesizer/index.ts
CHANGED
@@ -14,11 +14,7 @@ export class Synthesizer implements BaseLLM {
|
|
14
14
|
| {
|
15
15
|
actions: {
|
16
16
|
name: string;
|
17
|
-
|
18
|
-
explain: {
|
19
|
-
how: string;
|
20
|
-
why: string;
|
21
|
-
};
|
17
|
+
reasoning: string;
|
22
18
|
}[];
|
23
19
|
response: string;
|
24
20
|
}
|
@@ -31,11 +27,7 @@ export class Synthesizer implements BaseLLM {
|
|
31
27
|
actions: z.array(
|
32
28
|
z.object({
|
33
29
|
name: z.string(),
|
34
|
-
|
35
|
-
explain: z.object({
|
36
|
-
how: z.string(),
|
37
|
-
why: z.string(),
|
38
|
-
}),
|
30
|
+
reasoning: z.string(),
|
39
31
|
})
|
40
32
|
),
|
41
33
|
response: z.string(),
|
package/memory/cache.ts
CHANGED
@@ -1,7 +1,6 @@
|
|
1
1
|
import { openai } from "@ai-sdk/openai";
|
2
|
-
import { cosineSimilarity, embed
|
2
|
+
import { cosineSimilarity, embed } from "ai";
|
3
3
|
import { createClient } from "redis";
|
4
|
-
import { z } from "zod";
|
5
4
|
import {
|
6
5
|
CacheMemoryOptions,
|
7
6
|
CacheMemoryType,
|
@@ -86,15 +85,10 @@ export class CacheMemory {
|
|
86
85
|
.map((memory) => {
|
87
86
|
const similarity = cosineSimilarity(embedding, memory.embedding);
|
88
87
|
const similarityPercentage = (similarity + 1) * 50; // Conversion en pourcentage
|
89
|
-
|
90
|
-
console.log(`\n📊 Query "${memory.query}":
|
91
|
-
- Similarity: ${similarityPercentage.toFixed(2)}%`);
|
92
|
-
|
93
88
|
return {
|
94
89
|
data: memory.data,
|
95
90
|
query: memory.query,
|
96
91
|
similarityPercentage,
|
97
|
-
// Optionnel : ajouter des métadonnées utiles
|
98
92
|
memoryId: memory.id,
|
99
93
|
};
|
100
94
|
})
|
@@ -119,7 +113,6 @@ export class CacheMemory {
|
|
119
113
|
console.log("No matches found");
|
120
114
|
}
|
121
115
|
|
122
|
-
console.dir({ results });
|
123
116
|
return results;
|
124
117
|
}
|
125
118
|
|
@@ -161,7 +154,7 @@ export class CacheMemory {
|
|
161
154
|
|
162
155
|
public async createMemory(
|
163
156
|
input: CreateMemoryInput
|
164
|
-
): Promise<
|
157
|
+
): Promise<CacheMemoryType | undefined> {
|
165
158
|
console.log("Searching for similar memory", input);
|
166
159
|
const existingPattern = await this.findSimilarQueries(input.content, {
|
167
160
|
similarityThreshold: 95,
|
@@ -182,22 +175,7 @@ export class CacheMemory {
|
|
182
175
|
|
183
176
|
console.log("No similar memory found");
|
184
177
|
|
185
|
-
|
186
|
-
console.log("Generating variations...");
|
187
|
-
const variations = await generateObject({
|
188
|
-
model: openai("gpt-4"),
|
189
|
-
schema: z.object({
|
190
|
-
request: z.string().describe("The request to be performed"),
|
191
|
-
queries: z.array(z.object({ text: z.string() })),
|
192
|
-
}),
|
193
|
-
prompt: `For this input: "${input.content}"
|
194
|
-
Generate similar way to ask the same question.
|
195
|
-
Action results: ${JSON.stringify(input.data)}
|
196
|
-
- Keep variations natural and human-like
|
197
|
-
- Add 3-5 variations`,
|
198
|
-
});
|
199
|
-
console.log("Variations generated:", variations.object.queries);
|
200
|
-
await this.createSingleMemory({
|
178
|
+
const memory = await this.createSingleMemory({
|
201
179
|
id: crypto.randomUUID(),
|
202
180
|
content: input.content,
|
203
181
|
type: input.type,
|
@@ -206,23 +184,7 @@ export class CacheMemory {
|
|
206
184
|
scope: input.scope,
|
207
185
|
});
|
208
186
|
|
209
|
-
|
210
|
-
async (variation) => {
|
211
|
-
if (variation.text !== input.content) {
|
212
|
-
await this.createSingleMemory({
|
213
|
-
id: crypto.randomUUID(),
|
214
|
-
content: variation.text,
|
215
|
-
type: input.type,
|
216
|
-
data: input.data,
|
217
|
-
userId: input.userId,
|
218
|
-
scope: input.scope,
|
219
|
-
});
|
220
|
-
}
|
221
|
-
}
|
222
|
-
);
|
223
|
-
|
224
|
-
await Promise.all(variationPromises);
|
225
|
-
return variations.object.request;
|
187
|
+
return memory;
|
226
188
|
}
|
227
189
|
|
228
190
|
private async createSingleMemory(params: {
|
package/memory/persistent.ts
CHANGED
@@ -159,7 +159,7 @@ export class PersistentMemory {
|
|
159
159
|
/**
|
160
160
|
* Store a memory in the database
|
161
161
|
*/
|
162
|
-
async
|
162
|
+
async createMemory(memory: Memory) {
|
163
163
|
const indexName = this._getIndexName(memory.scope, memory.userId);
|
164
164
|
await this._getOrCreateIndex(indexName);
|
165
165
|
|
@@ -178,7 +178,7 @@ export class PersistentMemory {
|
|
178
178
|
body: JSON.stringify([document]),
|
179
179
|
}
|
180
180
|
);
|
181
|
-
console.log("Stored memory response:", response);
|
181
|
+
console.log("Stored persistent memory response:", response);
|
182
182
|
return response;
|
183
183
|
}
|
184
184
|
|
@@ -273,7 +273,7 @@ export class PersistentMemory {
|
|
273
273
|
|
274
274
|
// Log results
|
275
275
|
if (results.length > 0) {
|
276
|
-
console.log("\n✨ Similar queries found:");
|
276
|
+
console.log("\n✨ Similar queries found in persistent memory:");
|
277
277
|
results.forEach((match) => {
|
278
278
|
console.log(
|
279
279
|
`- ${match.query} : ${match.similarityPercentage.toFixed(2)}% (${
|
package/package.json
CHANGED
package/types.ts
CHANGED
@@ -128,7 +128,7 @@ export interface CacheMemoryOptions {
|
|
128
128
|
export interface CreateMemoryInput {
|
129
129
|
content: any;
|
130
130
|
type: MemoryType;
|
131
|
-
data:
|
131
|
+
data: QueueResult[];
|
132
132
|
userId?: string;
|
133
133
|
scope?: MemoryScope;
|
134
134
|
}
|
@@ -168,6 +168,18 @@ export interface Memory {
|
|
168
168
|
chunks?: MemoryChunk[];
|
169
169
|
}
|
170
170
|
|
171
|
+
export const ActionSchema = z.array(
|
172
|
+
z.object({
|
173
|
+
name: z.string(),
|
174
|
+
parameters: z.array(
|
175
|
+
z.object({
|
176
|
+
name: z.string(),
|
177
|
+
value: z.string(),
|
178
|
+
})
|
179
|
+
),
|
180
|
+
})
|
181
|
+
);
|
182
|
+
|
171
183
|
export enum MemoryType {
|
172
184
|
ACTION = "action",
|
173
185
|
CONVERSATION = "conversation",
|