@ai.ntellect/core 0.4.1 → 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.
- package/.mocharc.json +1 -1
- package/README.md +311 -272
- package/dist/graph/controller.js +63 -0
- package/dist/graph/engine.js +563 -0
- package/dist/index.js +6 -6
- package/dist/memory/adapters/meilisearch/index.js +249 -0
- package/dist/memory/adapters/redis/index.js +96 -0
- package/dist/memory/index.js +9 -0
- package/dist/services/agenda.js +115 -0
- package/dist/services/embedding.js +40 -0
- package/dist/services/queue.js +99 -103
- package/dist/test/graph/controller.test.js +170 -0
- package/dist/test/graph/engine.test.js +465 -0
- package/dist/test/memory/adapters/meilisearch.test.js +250 -0
- package/dist/test/memory/adapters/redis.test.js +143 -0
- package/dist/test/memory/base.test.js +209 -0
- package/dist/test/services/agenda.test.js +230 -0
- package/dist/test/services/queue.test.js +258 -0
- package/dist/types/index.js +2 -0
- package/dist/utils/generate-object.js +32 -11
- package/dist/utils/inject-actions.js +2 -2
- package/dist/utils/queue-item-transformer.js +2 -2
- package/dist/utils/state-manager.js +20 -0
- package/graph/controller.ts +60 -0
- package/graph/engine.ts +709 -0
- package/index.ts +7 -7
- package/interfaces/index.ts +119 -0
- package/memory/adapters/meilisearch/index.ts +286 -0
- package/memory/adapters/redis/index.ts +103 -0
- package/memory/index.ts +22 -0
- package/package.json +9 -2
- package/services/agenda.ts +118 -0
- package/services/embedding.ts +26 -0
- package/services/queue.ts +5 -32
- package/test/.env.test +4 -0
- package/test/graph/controller.test.ts +186 -0
- package/test/graph/engine.test.ts +563 -0
- package/test/memory/adapters/meilisearch.test.ts +297 -0
- package/test/memory/adapters/redis.test.ts +160 -0
- package/test/memory/base.test.ts +229 -0
- package/test/services/agenda.test.ts +280 -0
- package/test/services/queue.test.ts +286 -44
- package/tsconfig.json +10 -9
- package/types/index.ts +270 -0
- package/utils/generate-object.js +111 -0
- package/utils/generate-object.ts +24 -12
- package/utils/header-builder.js +34 -0
- package/utils/inject-actions.js +16 -0
- package/utils/inject-actions.ts +3 -3
- package/utils/queue-item-transformer.js +24 -0
- package/utils/queue-item-transformer.ts +8 -11
- package/utils/sanitize-results.js +60 -0
- package/utils/schema-generator.js +46 -0
- package/utils/state-manager.js +20 -0
- package/utils/state-manager.ts +30 -0
- package/.nvmrc +0 -1
- package/README.FR.md +0 -365
- package/agent/index.ts +0 -244
- package/agent/tools/get-rss.ts +0 -64
- package/bull.ts +0 -5
- package/dist/agent/index.d.ts +0 -38
- package/dist/agent/index.js +0 -143
- package/dist/agent/tools/get-rss.d.ts +0 -16
- package/dist/agent/tools/get-rss.js +0 -62
- package/dist/bull.d.ts +0 -1
- package/dist/bull.js +0 -9
- package/dist/examples/index.d.ts +0 -2
- package/dist/examples/index.js +0 -89
- package/dist/index.d.ts +0 -7
- package/dist/llm/interpreter/context.d.ts +0 -15
- package/dist/llm/interpreter/context.js +0 -89
- package/dist/llm/interpreter/index.d.ts +0 -21
- package/dist/llm/interpreter/index.js +0 -87
- package/dist/llm/memory-manager/context.d.ts +0 -2
- package/dist/llm/memory-manager/context.js +0 -22
- package/dist/llm/memory-manager/index.d.ts +0 -17
- package/dist/llm/memory-manager/index.js +0 -107
- package/dist/llm/orchestrator/context.d.ts +0 -2
- package/dist/llm/orchestrator/context.js +0 -23
- package/dist/llm/orchestrator/index.d.ts +0 -44
- package/dist/llm/orchestrator/index.js +0 -139
- package/dist/llm/orchestrator/types.d.ts +0 -12
- package/dist/memory/cache.d.ts +0 -22
- package/dist/memory/cache.js +0 -165
- package/dist/memory/persistent.d.ts +0 -57
- package/dist/memory/persistent.js +0 -189
- package/dist/services/queue.d.ts +0 -13
- package/dist/services/redis-cache.d.ts +0 -37
- package/dist/services/redis-cache.js +0 -93
- package/dist/services/scheduler.d.ts +0 -40
- package/dist/services/scheduler.js +0 -99
- package/dist/services/telegram-monitor.d.ts +0 -0
- package/dist/services/telegram-monitor.js +0 -118
- package/dist/t.d.ts +0 -46
- package/dist/t.js +0 -102
- package/dist/test.d.ts +0 -0
- package/dist/test.js +0 -438
- package/dist/types.d.ts +0 -258
- package/dist/types.js +0 -22
- package/dist/utils/generate-object.d.ts +0 -12
- package/dist/utils/header-builder.d.ts +0 -11
- package/dist/utils/inject-actions.d.ts +0 -2
- package/dist/utils/queue-item-transformer.d.ts +0 -7
- package/dist/utils/sanitize-results.d.ts +0 -17
- package/dist/utils/schema-generator.d.ts +0 -16
- package/examples/index.ts +0 -103
- package/llm/interpreter/context.ts +0 -101
- package/llm/interpreter/index.ts +0 -136
- package/llm/memory-manager/context.ts +0 -21
- package/llm/memory-manager/index.ts +0 -163
- package/llm/orchestrator/context.ts +0 -22
- package/llm/orchestrator/index.ts +0 -232
- package/llm/orchestrator/types.ts +0 -14
- package/memory/cache.ts +0 -221
- package/memory/persistent.ts +0 -265
- package/services/redis-cache.ts +0 -128
- package/services/scheduler.ts +0 -128
- package/services/telegram-monitor.ts +0 -138
- package/t.py +0 -79
- package/t.spec +0 -38
- package/t.ts +0 -133
- package/test/llm/orchestrator.test.ts +0 -47
- package/test/llm/synthesizer.test.ts +0 -31
- package/types.ts +0 -288
- /package/dist/{llm/orchestrator/types.js → interfaces/index.js} +0 -0
package/types/index.ts
ADDED
@@ -0,0 +1,270 @@
|
|
1
|
+
import { z } from "zod";
|
2
|
+
|
3
|
+
/* ======================== MEMORY ======================== */
|
4
|
+
|
5
|
+
/**
|
6
|
+
* Represents the input structure for creating a memory entry.
|
7
|
+
* @typedef {Object} CreateMemoryInput
|
8
|
+
* @property {string} query - The query associated with the memory.
|
9
|
+
* @property {any} data - The data to be stored.
|
10
|
+
* @property {string} roomId - The room identifier.
|
11
|
+
* @property {number} [ttl] - Time-to-live in seconds (optional).
|
12
|
+
*/
|
13
|
+
export type CreateMemoryInput = {
|
14
|
+
query: string;
|
15
|
+
data: any;
|
16
|
+
roomId: string;
|
17
|
+
ttl?: number;
|
18
|
+
};
|
19
|
+
|
20
|
+
/**
|
21
|
+
* Represents a stored memory entry.
|
22
|
+
* @typedef {Object} BaseMemoryType
|
23
|
+
* @property {string} id - Unique identifier of the memory entry.
|
24
|
+
* @property {string} data - Stored data as a string.
|
25
|
+
* @property {string} query - The associated query.
|
26
|
+
* @property {number[] | null} embedding - Vector representation of the data.
|
27
|
+
* @property {string} roomId - The associated room ID.
|
28
|
+
* @property {Date} createdAt - Creation date.
|
29
|
+
*/
|
30
|
+
export type BaseMemoryType = {
|
31
|
+
id: string;
|
32
|
+
data: string;
|
33
|
+
query: string;
|
34
|
+
embedding: number[] | null;
|
35
|
+
roomId: string;
|
36
|
+
createdAt: Date;
|
37
|
+
};
|
38
|
+
|
39
|
+
/* ======================== QUEUE ======================== */
|
40
|
+
|
41
|
+
/**
|
42
|
+
* Represents a single parameter for a queued action.
|
43
|
+
* @typedef {Object} QueueItemParameter
|
44
|
+
* @property {string} name - Parameter name.
|
45
|
+
* @property {string} value - Parameter value.
|
46
|
+
*/
|
47
|
+
export type QueueItemParameter = {
|
48
|
+
name: string;
|
49
|
+
value: string;
|
50
|
+
};
|
51
|
+
|
52
|
+
/**
|
53
|
+
* Represents an action in the queue.
|
54
|
+
* @typedef {Object} QueueItem
|
55
|
+
* @property {string} name - Name of the action.
|
56
|
+
* @property {QueueItemParameter[]} parameters - List of parameters.
|
57
|
+
*/
|
58
|
+
export type QueueItem = {
|
59
|
+
name: string;
|
60
|
+
parameters: QueueItemParameter[];
|
61
|
+
};
|
62
|
+
|
63
|
+
/**
|
64
|
+
* Represents the result of a processed queue action.
|
65
|
+
* @typedef {Object} QueueResult
|
66
|
+
* @property {string} name - Action name.
|
67
|
+
* @property {Record<string, string>} parameters - Executed parameters.
|
68
|
+
* @property {any} result - The execution result.
|
69
|
+
* @property {string | null} error - Error message if any.
|
70
|
+
* @property {boolean} [cancelled] - Indicates if the action was cancelled.
|
71
|
+
*/
|
72
|
+
export type QueueResult = {
|
73
|
+
name: string;
|
74
|
+
parameters: Record<string, string>;
|
75
|
+
result: any;
|
76
|
+
error: string | null;
|
77
|
+
cancelled?: boolean;
|
78
|
+
};
|
79
|
+
|
80
|
+
/**
|
81
|
+
* Defines callback functions for queue execution events.
|
82
|
+
* @typedef {Object} QueueCallbacks
|
83
|
+
* @property {(action: QueueItem) => void} [onActionStart] - Triggered when an action starts.
|
84
|
+
* @property {(result: QueueResult) => void} [onActionComplete] - Triggered when an action completes.
|
85
|
+
* @property {(results: QueueResult[]) => void} [onQueueComplete] - Triggered when the queue is fully processed.
|
86
|
+
* @property {(message: string) => Promise<boolean>} [onConfirmationRequired] - Triggered when confirmation is needed.
|
87
|
+
*/
|
88
|
+
export type QueueCallbacks = {
|
89
|
+
onActionStart?: (action: QueueItem) => void;
|
90
|
+
onActionComplete?: (result: QueueResult) => void;
|
91
|
+
onQueueComplete?: (results: QueueResult[]) => void;
|
92
|
+
onConfirmationRequired?: (message: string) => Promise<boolean>;
|
93
|
+
};
|
94
|
+
|
95
|
+
/* ======================== ACTION ======================== */
|
96
|
+
|
97
|
+
/**
|
98
|
+
* Represents an executable action schema.
|
99
|
+
* @typedef {Object} ActionSchema
|
100
|
+
* @property {string} name - Action name.
|
101
|
+
* @property {string} description - Action description.
|
102
|
+
* @property {z.ZodObject<Record<string, z.ZodType>>} parameters - Schema for input parameters.
|
103
|
+
* @property {(args: any) => Promise<any>} execute - Function to execute the action.
|
104
|
+
* @property {Object[]} [examples] - Example usages of the action.
|
105
|
+
* @property {Object} [confirmation] - Confirmation requirements.
|
106
|
+
* @property {boolean} confirmation.requireConfirmation - Whether confirmation is needed.
|
107
|
+
* @property {string} confirmation.message - The confirmation message.
|
108
|
+
*/
|
109
|
+
export type ActionSchema = {
|
110
|
+
name: string;
|
111
|
+
description: string;
|
112
|
+
parameters: z.ZodObject<{ [key: string]: z.ZodType }>;
|
113
|
+
execute: (args: any) => Promise<any>;
|
114
|
+
examples?: {
|
115
|
+
role: string;
|
116
|
+
content: string;
|
117
|
+
parameters?: Record<string, any>;
|
118
|
+
}[];
|
119
|
+
confirmation?: {
|
120
|
+
requireConfirmation: boolean;
|
121
|
+
message: string;
|
122
|
+
};
|
123
|
+
};
|
124
|
+
|
125
|
+
/* ======================== SCHEDULING ======================== */
|
126
|
+
|
127
|
+
/**
|
128
|
+
* Represents a scheduled action with optional recurrence.
|
129
|
+
* @typedef {Object} ScheduledAction
|
130
|
+
* @property {string} id - Unique identifier for the scheduled action.
|
131
|
+
* @property {Object} action - The action details.
|
132
|
+
* @property {string} action.name - The action name.
|
133
|
+
* @property {QueueItemParameter[]} action.parameters - Action parameters.
|
134
|
+
* @property {Date} scheduledTime - The scheduled execution time.
|
135
|
+
* @property {string} userId - Associated user identifier.
|
136
|
+
* @property {"pending" | "completed" | "failed"} status - The execution status.
|
137
|
+
* @property {Object} [recurrence] - Recurrence details (optional).
|
138
|
+
* @property {"daily" | "weekly" | "monthly"} recurrence.type - Recurrence type.
|
139
|
+
* @property {number} recurrence.interval - Recurrence interval.
|
140
|
+
*/
|
141
|
+
export type ScheduledAction = {
|
142
|
+
id: string;
|
143
|
+
action: {
|
144
|
+
name: string;
|
145
|
+
parameters: QueueItemParameter[];
|
146
|
+
};
|
147
|
+
scheduledTime: Date;
|
148
|
+
userId: string;
|
149
|
+
status: "pending" | "completed" | "failed";
|
150
|
+
recurrence?: {
|
151
|
+
type: "daily" | "weekly" | "monthly";
|
152
|
+
interval: number;
|
153
|
+
};
|
154
|
+
};
|
155
|
+
|
156
|
+
/**
|
157
|
+
* Represents a scheduled request.
|
158
|
+
* @typedef {Object} ScheduledRequest
|
159
|
+
* @property {string} id - Unique identifier for the scheduled request.
|
160
|
+
* @property {string} originalRequest - The original request string.
|
161
|
+
* @property {string} cronExpression - The cron expression for scheduling.
|
162
|
+
* @property {boolean} isRecurring - Whether the request is recurring.
|
163
|
+
* @property {Date} createdAt - The creation date.
|
164
|
+
*/
|
165
|
+
export type ScheduledRequest = {
|
166
|
+
id: string;
|
167
|
+
originalRequest: string;
|
168
|
+
cronExpression: string;
|
169
|
+
isRecurring: boolean;
|
170
|
+
createdAt: Date;
|
171
|
+
};
|
172
|
+
|
173
|
+
/* ======================== GRAPH ======================== */
|
174
|
+
|
175
|
+
/**
|
176
|
+
* Defines a graph definition.
|
177
|
+
* @typedef {Object} GraphDefinition
|
178
|
+
* @property {string} name - The graph name.
|
179
|
+
* @property {string} entryNode - The entry node name.
|
180
|
+
* @property {Record<string, Node<T>>} nodes - The nodes in the graph.
|
181
|
+
* @property {z.ZodSchema<T>} [schema] - Optional schema for input validation.
|
182
|
+
*/
|
183
|
+
export type GraphDefinition<T> = {
|
184
|
+
name: string;
|
185
|
+
entryNode: string;
|
186
|
+
nodes: Record<string, Node<T>>;
|
187
|
+
schema?: z.ZodSchema<T>;
|
188
|
+
};
|
189
|
+
|
190
|
+
/**
|
191
|
+
* Defines a shared state context for execution graphs.
|
192
|
+
* @typedef {Object} SharedState
|
193
|
+
* @property {Partial<T>} context - The execution context.
|
194
|
+
*/
|
195
|
+
export type SharedState<T> = {
|
196
|
+
context: Partial<T>;
|
197
|
+
};
|
198
|
+
|
199
|
+
/**
|
200
|
+
* Defines a graph node within a graph execution structure.
|
201
|
+
* @typedef {Object} Node
|
202
|
+
* @property {string} name - The node name.
|
203
|
+
* @property {string} [description] - Optional description.
|
204
|
+
* @property {(params: P, state: SharedState<T>) => Promise<SharedState<T> | void>} execute - Execution function.
|
205
|
+
* @property {(state: SharedState<T>) => boolean} [condition] - Optional condition for execution.
|
206
|
+
* @property {NodeRelationship[]} [relationships] - Possible node transitions.
|
207
|
+
* @property {z.ZodSchema<P>} [schema] - Optional schema for input validation.
|
208
|
+
* @property {any} [state] - Internal node state.
|
209
|
+
* @property {string[]} [events] - Events triggered by the node.
|
210
|
+
*/
|
211
|
+
export type Node<T, P = any> = {
|
212
|
+
name: string;
|
213
|
+
description?: string;
|
214
|
+
execute: (params: P, state: SharedState<T>) => Promise<SharedState<T> | void>;
|
215
|
+
condition?: (state: SharedState<T>) => boolean;
|
216
|
+
relationships?: NodeRelationship[];
|
217
|
+
schema?: z.ZodSchema<P>;
|
218
|
+
state?: any;
|
219
|
+
events?: string[];
|
220
|
+
};
|
221
|
+
|
222
|
+
/**
|
223
|
+
* Defines a node relationship in an execution graph.
|
224
|
+
* @typedef {Object} NodeRelationship
|
225
|
+
* @property {string} name - Relationship name.
|
226
|
+
* @property {string} [description] - Optional description.
|
227
|
+
*/
|
228
|
+
export type NodeRelationship = {
|
229
|
+
name: string;
|
230
|
+
description?: string;
|
231
|
+
};
|
232
|
+
|
233
|
+
/* ======================== SEARCH ======================== */
|
234
|
+
|
235
|
+
/**
|
236
|
+
* Represents a document that can be indexed and searched.
|
237
|
+
* @typedef {Object} SearchDocument
|
238
|
+
* @property {string} [id] - Optional unique identifier of the document.
|
239
|
+
* @property {string} content - The searchable text content.
|
240
|
+
* @property {Record<string, any>} [metadata] - Additional metadata for context.
|
241
|
+
*/
|
242
|
+
export type SearchDocument = {
|
243
|
+
id?: string;
|
244
|
+
content: string;
|
245
|
+
metadata?: Record<string, any>;
|
246
|
+
};
|
247
|
+
|
248
|
+
/**
|
249
|
+
* Represents a search result with a similarity score.
|
250
|
+
* @typedef {Object} SearchResult
|
251
|
+
* @property {SearchDocument} document - The matched document.
|
252
|
+
* @property {number} score - The similarity score.
|
253
|
+
*/
|
254
|
+
export type SearchResult = {
|
255
|
+
document: SearchDocument;
|
256
|
+
score: number;
|
257
|
+
};
|
258
|
+
|
259
|
+
/* ======================== MEILISEARCH ======================== */
|
260
|
+
export type MeilisearchConfig = {
|
261
|
+
host: string;
|
262
|
+
apiKey: string;
|
263
|
+
searchableAttributes?: string[];
|
264
|
+
sortableAttributes?: string[];
|
265
|
+
};
|
266
|
+
|
267
|
+
export type MeilisearchSettings = {
|
268
|
+
searchableAttributes?: string[];
|
269
|
+
sortableAttributes?: string[];
|
270
|
+
};
|
@@ -0,0 +1,111 @@
|
|
1
|
+
"use strict";
|
2
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
3
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
4
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
5
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
6
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
7
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
8
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
9
|
+
});
|
10
|
+
};
|
11
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
12
|
+
exports.generateObject = exports.describeZodSchema = void 0;
|
13
|
+
const ai_1 = require("ai");
|
14
|
+
const zod_1 = require("zod");
|
15
|
+
const describeZodSchema = (schema) => {
|
16
|
+
if (schema instanceof zod_1.z.ZodObject) {
|
17
|
+
const entries = Object.entries(schema.shape);
|
18
|
+
const fields = entries.map(([key, value]) => {
|
19
|
+
const description = value._def.description || "";
|
20
|
+
const fieldSchema = (0, exports.describeZodSchema)(value);
|
21
|
+
return description
|
22
|
+
? `${key}: ${fieldSchema} // ${description}`
|
23
|
+
: `${key}: ${fieldSchema}`;
|
24
|
+
});
|
25
|
+
return `z.object({${fields.join(", ")}})`;
|
26
|
+
}
|
27
|
+
if (schema instanceof zod_1.z.ZodArray) {
|
28
|
+
return `z.array(${(0, exports.describeZodSchema)(schema.element)})`;
|
29
|
+
}
|
30
|
+
if (schema instanceof zod_1.z.ZodString) {
|
31
|
+
return "z.string()";
|
32
|
+
}
|
33
|
+
if (schema instanceof zod_1.z.ZodNumber) {
|
34
|
+
return "z.number()";
|
35
|
+
}
|
36
|
+
if (schema instanceof zod_1.z.ZodBoolean) {
|
37
|
+
return "z.boolean()";
|
38
|
+
}
|
39
|
+
if (schema instanceof zod_1.z.ZodOptional) {
|
40
|
+
return `z.optional(${(0, exports.describeZodSchema)(schema._def.innerType)})`;
|
41
|
+
}
|
42
|
+
if (schema instanceof zod_1.z.ZodUnion) {
|
43
|
+
return `z.union([${schema._def.options
|
44
|
+
.map((option) => (0, exports.describeZodSchema)(option))
|
45
|
+
.join(", ")}])`;
|
46
|
+
}
|
47
|
+
if (schema instanceof zod_1.z.ZodEnum) {
|
48
|
+
return `z.enum(${JSON.stringify(schema._def.values)})`;
|
49
|
+
}
|
50
|
+
if (schema instanceof zod_1.z.ZodLiteral) {
|
51
|
+
return `z.literal(${JSON.stringify(schema._def.value)})`;
|
52
|
+
}
|
53
|
+
return "z.unknown()"; // Fallback for unknown types
|
54
|
+
};
|
55
|
+
exports.describeZodSchema = describeZodSchema;
|
56
|
+
const generateObject = (config) => __awaiter(void 0, void 0, void 0, function* () {
|
57
|
+
var _a;
|
58
|
+
// Generate a detailed description of the schema
|
59
|
+
const schemaDescription = (0, exports.describeZodSchema)(config.schema);
|
60
|
+
const baseContext = `
|
61
|
+
${config.system}
|
62
|
+
EXPECTED SCHEMA:
|
63
|
+
${schemaDescription}
|
64
|
+
|
65
|
+
BAD EXAMPLE:
|
66
|
+
\`\`\`json
|
67
|
+
{
|
68
|
+
"key": "value"
|
69
|
+
}
|
70
|
+
\`\`\`
|
71
|
+
|
72
|
+
GOOD EXAMPLE:
|
73
|
+
{
|
74
|
+
"key": "value"
|
75
|
+
}
|
76
|
+
|
77
|
+
OUTPUT ONLY THE JSON SCHEMA, NO 'TRIPLE QUOTES'JSON OR ANY OTHER TEXT. ONLY THE JSON SCHEMA.
|
78
|
+
`;
|
79
|
+
console.log("🔍 Generating object with context:");
|
80
|
+
console.log(`${config.prompt}\n${baseContext}\n`);
|
81
|
+
const response = yield (0, ai_1.generateText)({
|
82
|
+
model: config.model,
|
83
|
+
messages: !config.prompt
|
84
|
+
? [
|
85
|
+
{
|
86
|
+
role: "system",
|
87
|
+
content: baseContext,
|
88
|
+
},
|
89
|
+
...((_a = config.messages) !== null && _a !== void 0 ? _a : []),
|
90
|
+
]
|
91
|
+
: undefined,
|
92
|
+
system: config.system,
|
93
|
+
temperature: config.temperature,
|
94
|
+
prompt: !config.prompt ? undefined : `${config.prompt}\n\n${baseContext}`,
|
95
|
+
});
|
96
|
+
try {
|
97
|
+
// Clean the response text from any markdown or code block markers
|
98
|
+
const cleanText = response.text
|
99
|
+
.replace(/```json\s*/g, "")
|
100
|
+
.replace(/```\s*$/g, "")
|
101
|
+
.trim();
|
102
|
+
const parsedResponse = JSON.parse(cleanText);
|
103
|
+
const validatedResponse = config.schema.parse(parsedResponse);
|
104
|
+
return { object: validatedResponse };
|
105
|
+
}
|
106
|
+
catch (error) {
|
107
|
+
console.error("Error parsing or validating JSON response:", error);
|
108
|
+
throw new Error("Failed to generate valid JSON response");
|
109
|
+
}
|
110
|
+
});
|
111
|
+
exports.generateObject = generateObject;
|
package/utils/generate-object.ts
CHANGED
@@ -1,4 +1,4 @@
|
|
1
|
-
import { LanguageModelV1, generateText } from "ai";
|
1
|
+
import { CoreMessage, LanguageModelV1, generateText } from "ai";
|
2
2
|
import { z } from "zod";
|
3
3
|
|
4
4
|
export const describeZodSchema = (schema: z.ZodType): string => {
|
@@ -54,19 +54,16 @@ export const describeZodSchema = (schema: z.ZodType): string => {
|
|
54
54
|
export const generateObject = async <T>(config: {
|
55
55
|
model: LanguageModelV1;
|
56
56
|
schema: z.ZodSchema;
|
57
|
-
prompt: string;
|
58
57
|
system: string;
|
59
58
|
temperature: number;
|
59
|
+
prompt?: string;
|
60
|
+
messages?: CoreMessage[];
|
60
61
|
}): Promise<{ object: T }> => {
|
61
62
|
// Generate a detailed description of the schema
|
62
63
|
const schemaDescription = describeZodSchema(config.schema);
|
63
64
|
|
64
|
-
|
65
|
-
|
66
|
-
const response = await generateText({
|
67
|
-
model: config.model,
|
68
|
-
prompt: `${config.prompt}
|
69
|
-
|
65
|
+
const baseContext = `
|
66
|
+
${config.system}
|
70
67
|
EXPECTED SCHEMA:
|
71
68
|
${schemaDescription}
|
72
69
|
|
@@ -76,16 +73,31 @@ export const generateObject = async <T>(config: {
|
|
76
73
|
"key": "value"
|
77
74
|
}
|
78
75
|
\`\`\`
|
79
|
-
|
76
|
+
|
80
77
|
GOOD EXAMPLE:
|
81
78
|
{
|
82
79
|
"key": "value"
|
83
80
|
}
|
84
|
-
|
85
|
-
|
86
|
-
|
81
|
+
|
82
|
+
OUTPUT ONLY THE JSON SCHEMA, NO 'TRIPLE QUOTES'JSON OR ANY OTHER TEXT. ONLY THE JSON SCHEMA.
|
83
|
+
`;
|
84
|
+
|
85
|
+
console.log("🔍 Generating object with context:");
|
86
|
+
console.log(`${config.prompt}\n${baseContext}\n`);
|
87
|
+
const response = await generateText({
|
88
|
+
model: config.model,
|
89
|
+
messages: !config.prompt
|
90
|
+
? [
|
91
|
+
{
|
92
|
+
role: "system",
|
93
|
+
content: baseContext,
|
94
|
+
},
|
95
|
+
...(config.messages ?? []),
|
96
|
+
]
|
97
|
+
: undefined,
|
87
98
|
system: config.system,
|
88
99
|
temperature: config.temperature,
|
100
|
+
prompt: !config.prompt ? undefined : `${config.prompt}\n\n${baseContext}`,
|
89
101
|
});
|
90
102
|
|
91
103
|
try {
|
@@ -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;
|
@@ -0,0 +1,16 @@
|
|
1
|
+
"use strict";
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
3
|
+
exports.injectActions = void 0;
|
4
|
+
const injectActions = (actions) => {
|
5
|
+
return actions.map((action) => {
|
6
|
+
const parameters = action.parameters;
|
7
|
+
const schemaShape = Object.keys(parameters._def.shape()).join(", ");
|
8
|
+
const actionString = `* ${action.name}( { ${schemaShape} }) (${action.description}) ${action.examples
|
9
|
+
? `Eg: ${action.examples.map((example) => {
|
10
|
+
return JSON.stringify(example);
|
11
|
+
})}`
|
12
|
+
: ""}`;
|
13
|
+
return actionString;
|
14
|
+
});
|
15
|
+
};
|
16
|
+
exports.injectActions = injectActions;
|
package/utils/inject-actions.ts
CHANGED
@@ -5,11 +5,11 @@ export const injectActions = (actions: ActionSchema[]) => {
|
|
5
5
|
return actions.map((action) => {
|
6
6
|
const parameters = action.parameters as z.ZodObject<any>;
|
7
7
|
const schemaShape = Object.keys(parameters._def.shape()).join(", ");
|
8
|
-
const actionString =
|
8
|
+
const actionString = `* ${action.name}( { ${schemaShape} }) (${
|
9
9
|
action.description
|
10
|
-
}
|
10
|
+
}) ${
|
11
11
|
action.examples
|
12
|
-
? `
|
12
|
+
? `Eg: ${action.examples.map((example: any) => {
|
13
13
|
return JSON.stringify(example);
|
14
14
|
})}`
|
15
15
|
: ""
|
@@ -0,0 +1,24 @@
|
|
1
|
+
"use strict";
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
3
|
+
exports.QueueItemTransformer = void 0;
|
4
|
+
class QueueItemTransformer {
|
5
|
+
static transformActionToQueueItem(action) {
|
6
|
+
return {
|
7
|
+
name: action.name || "",
|
8
|
+
parameters: QueueItemTransformer.transformParameters(action.parameters || {}),
|
9
|
+
};
|
10
|
+
}
|
11
|
+
static transformFromSimilarActions(similarActions) {
|
12
|
+
return similarActions === null || similarActions === void 0 ? void 0 : similarActions.map((action) => QueueItemTransformer.transformActionToQueueItem(action));
|
13
|
+
}
|
14
|
+
static transformParameters(parameters) {
|
15
|
+
return Object.entries(parameters).map(([name, value]) => ({
|
16
|
+
name,
|
17
|
+
value: typeof value === "object" ? JSON.stringify(value) : String(value),
|
18
|
+
}));
|
19
|
+
}
|
20
|
+
static transformActionsToQueueItems(actions) {
|
21
|
+
return actions === null || actions === void 0 ? void 0 : actions.map((action) => this.transformActionToQueueItem(action));
|
22
|
+
}
|
23
|
+
}
|
24
|
+
exports.QueueItemTransformer = QueueItemTransformer;
|
@@ -1,13 +1,10 @@
|
|
1
|
-
import {
|
2
|
-
ActionData,
|
3
|
-
QueueItem,
|
4
|
-
QueueItemParameter,
|
5
|
-
QueueResult,
|
6
|
-
TransformedQueueItem,
|
7
|
-
} from "../types";
|
1
|
+
import { QueueItem, QueueItemParameter, QueueResult } from "@/types";
|
8
2
|
|
9
3
|
export class QueueItemTransformer {
|
10
|
-
static transformActionToQueueItem(action:
|
4
|
+
static transformActionToQueueItem(action: {
|
5
|
+
name: string;
|
6
|
+
parameters: Record<string, any>;
|
7
|
+
}): QueueItem {
|
11
8
|
return {
|
12
9
|
name: action.name || "",
|
13
10
|
parameters: QueueItemTransformer.transformParameters(
|
@@ -18,8 +15,8 @@ export class QueueItemTransformer {
|
|
18
15
|
|
19
16
|
static transformFromSimilarActions(
|
20
17
|
similarActions: QueueResult[]
|
21
|
-
):
|
22
|
-
return similarActions?.map((action:
|
18
|
+
): QueueItem[] | undefined {
|
19
|
+
return similarActions?.map((action: QueueResult) =>
|
23
20
|
QueueItemTransformer.transformActionToQueueItem(action)
|
24
21
|
);
|
25
22
|
}
|
@@ -34,7 +31,7 @@ export class QueueItemTransformer {
|
|
34
31
|
}
|
35
32
|
|
36
33
|
static transformActionsToQueueItems(
|
37
|
-
actions:
|
34
|
+
actions: { name: string; parameters: Record<string, any> }[] | undefined
|
38
35
|
): QueueItem[] | undefined {
|
39
36
|
return actions?.map((action) => this.transformActionToQueueItem(action));
|
40
37
|
}
|
@@ -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;
|
@@ -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;
|