@ai.ntellect/core 0.0.24 → 0.0.26

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.
@@ -0,0 +1,139 @@
1
+ import { StreamTextResult } from "ai";
2
+ import { z } from "zod";
3
+ export interface BaseLLM {
4
+ process: (prompt: string) => Promise<string | object>;
5
+ streamProcess?: (prompt: string) => Promise<StreamTextResult<Record<string, any>>>;
6
+ }
7
+ export type User = {
8
+ id: string;
9
+ };
10
+ export interface QueueItem {
11
+ name: string;
12
+ parameters: QueueItemParameter[];
13
+ }
14
+ export interface IEventHandler {
15
+ emitQueueStart(actions: QueueItem[]): void;
16
+ emitActionStart(action: QueueItem): void;
17
+ emitActionComplete(action: QueueResult): void;
18
+ emitQueueComplete(): void;
19
+ }
20
+ export type AgentEvent = {
21
+ onMessage?: (data: any) => void;
22
+ onQueueStart?: (actions: QueueItem[]) => void;
23
+ onActionStart?: (action: QueueItem) => void;
24
+ onActionComplete?: (action: QueueResult) => void;
25
+ onQueueComplete?: (actions: QueueResult[]) => void;
26
+ onConfirmationRequired?: (message: string) => Promise<boolean>;
27
+ };
28
+ export interface QueueResult {
29
+ name: string;
30
+ parameters: Record<string, string>;
31
+ result: any;
32
+ error: string | null;
33
+ cancelled?: boolean;
34
+ }
35
+ export interface QueueCallbacks {
36
+ onActionStart?: (action: QueueItem) => void;
37
+ onActionComplete?: (result: QueueResult) => void;
38
+ onQueueComplete?: (results: QueueResult[]) => void;
39
+ onConfirmationRequired?: (message: string) => Promise<boolean>;
40
+ }
41
+ export interface ProcessPromptCallbacks {
42
+ onQueueStart?: (actions: QueueItem[]) => void | Promise<void>;
43
+ onActionStart?: (action: QueueItem) => void | Promise<void>;
44
+ onActionComplete?: (action: QueueResult) => void | Promise<void>;
45
+ onQueueComplete?: (actions: QueueResult[]) => void | Promise<void>;
46
+ onConfirmationRequired?: (message: string) => Promise<boolean>;
47
+ }
48
+ export interface ActionSchema {
49
+ name: string;
50
+ description: string;
51
+ parameters: z.ZodSchema;
52
+ execute: (args: any) => Promise<any>;
53
+ confirmation?: {
54
+ requireConfirmation: boolean;
55
+ message: string;
56
+ };
57
+ }
58
+ export type ProcessPromptResult = {
59
+ type: "success" | "clarification" | "confirmation";
60
+ data: QueueResult[] | {
61
+ validationErrors: string[];
62
+ prompt: string;
63
+ } | {
64
+ actions: QueueItem[];
65
+ };
66
+ initialPrompt: string;
67
+ };
68
+ export interface ActionPattern {
69
+ id: string;
70
+ actions: QueueResult[];
71
+ embeddings: number[][];
72
+ queries: string[];
73
+ purpose: string;
74
+ }
75
+ export interface MatchOptions {
76
+ similarityThreshold?: number;
77
+ maxResults?: number;
78
+ }
79
+ export interface MatchResult {
80
+ data: any;
81
+ similarityPercentage: number;
82
+ purpose: string;
83
+ name?: string;
84
+ parameters?: Record<string, any>;
85
+ }
86
+ export interface SummarizerAgent {
87
+ process: (results: object, onFinish?: (event: any) => void) => Promise<{
88
+ actions: {
89
+ name: string;
90
+ reasoning: string;
91
+ }[];
92
+ response: string;
93
+ } | StreamTextResult<Record<string, any>>>;
94
+ streamProcess: (results: object, onFinish?: (event: any) => void) => Promise<StreamTextResult<Record<string, any>>>;
95
+ }
96
+ export interface MemoryCacheOptions {
97
+ cacheTTL?: number;
98
+ redisUrl?: string;
99
+ cachePrefix?: string;
100
+ }
101
+ export interface CreateMemoryInput {
102
+ content: string;
103
+ type: MemoryType;
104
+ data: any;
105
+ userId?: string;
106
+ scope?: MemoryScope;
107
+ }
108
+ export interface Memory {
109
+ id: string;
110
+ type: MemoryType;
111
+ data: any;
112
+ purpose: string;
113
+ queries: string[];
114
+ embeddings: number[][];
115
+ userId?: string;
116
+ scope: MemoryScope;
117
+ createdAt: Date;
118
+ }
119
+ export declare enum MemoryType {
120
+ ACTION = "action",
121
+ CONVERSATION = "conversation",
122
+ KNOWLEDGE = "knowledge"
123
+ }
124
+ export declare enum MemoryScope {
125
+ GLOBAL = "global",
126
+ USER = "user"
127
+ }
128
+ export interface ActionData {
129
+ name?: string;
130
+ parameters?: Record<string, any>;
131
+ }
132
+ export interface QueueItemParameter {
133
+ name: string;
134
+ value: string;
135
+ }
136
+ export interface TransformedQueueItem {
137
+ name: string;
138
+ parameters: QueueItemParameter[];
139
+ }
@@ -0,0 +1,7 @@
1
+ import { ActionData, TransformedQueueItem } from "../types";
2
+ export declare class QueueItemTransformer {
3
+ static transformActionToQueueItem(action: ActionData): TransformedQueueItem;
4
+ static transformFromSimilarActions(similarActions: any[]): TransformedQueueItem[] | undefined;
5
+ private static transformParameters;
6
+ static transformActionsToQueueItems(actions: ActionData[] | undefined): TransformedQueueItem[] | undefined;
7
+ }
@@ -9,9 +9,8 @@ class QueueItemTransformer {
9
9
  };
10
10
  }
11
11
  static transformFromSimilarActions(similarActions) {
12
- var _a;
13
- const firstMatch = (_a = similarActions === null || similarActions === void 0 ? void 0 : similarActions[0]) === null || _a === void 0 ? void 0 : _a.data;
14
- return firstMatch === null || firstMatch === void 0 ? void 0 : firstMatch.map((action) => QueueItemTransformer.transformActionToQueueItem(action));
12
+ const firstMatch = similarActions?.[0]?.data;
13
+ return firstMatch?.map((action) => QueueItemTransformer.transformActionToQueueItem(action));
15
14
  }
16
15
  static transformParameters(parameters) {
17
16
  return Object.entries(parameters).map(([name, value]) => ({
@@ -20,7 +19,7 @@ class QueueItemTransformer {
20
19
  }));
21
20
  }
22
21
  static transformActionsToQueueItems(actions) {
23
- return actions === null || actions === void 0 ? void 0 : actions.map(action => this.transformActionToQueueItem(action));
22
+ return actions?.map(action => this.transformActionToQueueItem(action));
24
23
  }
25
24
  }
26
25
  exports.QueueItemTransformer = QueueItemTransformer;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ai.ntellect/core",
3
- "version": "0.0.24",
3
+ "version": "0.0.26",
4
4
  "description": "",
5
5
  "main": "dist/index.js",
6
6
  "scripts": {
package/tsconfig.json CHANGED
@@ -11,6 +11,5 @@
11
11
  "skipLibCheck": true,
12
12
  "forceConsistentCasingInFileNames": true
13
13
  },
14
- "include": ["src/**/*", "test/**/*"],
15
- "exclude": ["node_modules", "dist"]
14
+ "exclude": ["node_modules", "dist", "test"]
16
15
  }
@@ -1,40 +0,0 @@
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.Orchestrator = void 0;
13
- const openai_1 = require("@ai-sdk/openai");
14
- const ai_1 = require("ai");
15
- const zod_1 = require("zod");
16
- const context_1 = require("./context");
17
- class Orchestrator {
18
- constructor(tools) {
19
- this.model = (0, openai_1.openai)("gpt-4o-mini");
20
- this.tools = tools;
21
- }
22
- process(prompt) {
23
- return __awaiter(this, void 0, void 0, function* () {
24
- const response = yield (0, ai_1.generateObject)({
25
- model: this.model,
26
- schema: zod_1.z.object({
27
- actions: zod_1.z.array(zod_1.z.object({
28
- name: zod_1.z.string(),
29
- parameters: zod_1.z.record(zod_1.z.string(), zod_1.z.any()),
30
- })),
31
- answer: zod_1.z.string(),
32
- }),
33
- prompt: prompt,
34
- system: context_1.orchestratorContext.compose(this.tools),
35
- });
36
- return response.object;
37
- });
38
- }
39
- }
40
- exports.Orchestrator = Orchestrator;
@@ -1,54 +0,0 @@
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.Summarizer = void 0;
13
- const openai_1 = require("@ai-sdk/openai");
14
- const ai_1 = require("ai");
15
- const zod_1 = require("zod");
16
- const context_1 = require("./context");
17
- class Summarizer {
18
- constructor() {
19
- this.model = (0, openai_1.openai)("gpt-4-turbo");
20
- }
21
- process(prompt, onFinish) {
22
- return __awaiter(this, void 0, void 0, function* () {
23
- console.log("Summarizing results...");
24
- const result = yield (0, ai_1.generateObject)({
25
- model: this.model,
26
- schema: zod_1.z.object({
27
- actions: zod_1.z.array(zod_1.z.object({
28
- name: zod_1.z.string(),
29
- reasoning: zod_1.z.string(),
30
- })),
31
- response: zod_1.z.string(),
32
- }),
33
- prompt: context_1.summarizerContext.compose(prompt),
34
- system: context_1.summarizerContext.role,
35
- });
36
- console.log("Summarized results:", result.object);
37
- if (onFinish)
38
- onFinish(result.object);
39
- return result.object;
40
- });
41
- }
42
- streamProcess(prompt, onFinish) {
43
- return __awaiter(this, void 0, void 0, function* () {
44
- const result = yield (0, ai_1.streamText)({
45
- model: this.model,
46
- prompt: context_1.summarizerContext.compose(prompt),
47
- onFinish: onFinish,
48
- system: context_1.summarizerContext.role,
49
- });
50
- return result;
51
- });
52
- }
53
- }
54
- exports.Summarizer = Summarizer;
@@ -1,187 +0,0 @@
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.Workflow = void 0;
13
- const synthesizer_1 = require("../agents/synthesizer");
14
- const queue_1 = require("../services/queue");
15
- const types_1 = require("../types");
16
- const queue_item_transformer_1 = require("../utils/queue-item-transformer");
17
- class Workflow {
18
- constructor(user, dependencies) {
19
- this.user = user;
20
- this.dependencies = dependencies;
21
- this.CONFIRMATION_TIMEOUT = 5 * 60 * 1000; // 5 minutes
22
- this.SIMILARITY_THRESHOLD = 95;
23
- this.MAX_RESULTS = 1;
24
- }
25
- start(prompt, promptWithContext, stream) {
26
- return __awaiter(this, void 0, void 0, function* () {
27
- const request = yield this.dependencies.orchestrator.process(promptWithContext);
28
- this.dependencies.eventEmitter.emit("orchestrator-update", {
29
- type: "on-message",
30
- data: request,
31
- });
32
- if (request.actions.length > 0) {
33
- return this.handleActions(prompt, request.actions);
34
- }
35
- });
36
- }
37
- handleActions(prompt, actions) {
38
- return __awaiter(this, void 0, void 0, function* () {
39
- let predefinedActions = actions;
40
- console.log("\n🔍 Predefined actions:", predefinedActions);
41
- const similarActions = yield this.dependencies.memoryCache.findBestMatches(prompt, {
42
- similarityThreshold: this.SIMILARITY_THRESHOLD,
43
- maxResults: this.MAX_RESULTS,
44
- userId: this.user.id,
45
- scope: types_1.MemoryScope.USER,
46
- });
47
- console.log("\n🔍 Similar actions:", similarActions);
48
- predefinedActions =
49
- queue_item_transformer_1.QueueItemTransformer.transformActionsToQueueItems(predefinedActions) ||
50
- [];
51
- console.log("\n🔍 Transformed predefined actions:", predefinedActions);
52
- if (similarActions && similarActions.length > 0) {
53
- predefinedActions =
54
- queue_item_transformer_1.QueueItemTransformer.transformFromSimilarActions(similarActions) || [];
55
- console.log("\n🔍 Transformed similar actions:", predefinedActions);
56
- }
57
- console.log("\n🔍 Final actions:", predefinedActions);
58
- const callbacks = this.createCallbacks(prompt, similarActions);
59
- console.log("\n🔍 Queue prepared");
60
- const actionsResult = yield this.executeActions(predefinedActions, this.dependencies.orchestrator.tools, callbacks);
61
- console.log("\n🔍 Actions result:", actionsResult);
62
- return this.handleActionResults(Object.assign(Object.assign({}, actionsResult), { initialPrompt: prompt }), prompt);
63
- });
64
- }
65
- executeActions(predefinedActions, tools, callbacks) {
66
- return __awaiter(this, void 0, void 0, function* () {
67
- try {
68
- const queueManager = new queue_1.ActionQueueManager(tools, {
69
- onActionStart: callbacks === null || callbacks === void 0 ? void 0 : callbacks.onActionStart,
70
- onActionComplete: callbacks === null || callbacks === void 0 ? void 0 : callbacks.onActionComplete,
71
- onQueueComplete: callbacks === null || callbacks === void 0 ? void 0 : callbacks.onQueueComplete,
72
- onConfirmationRequired: (message) => __awaiter(this, void 0, void 0, function* () {
73
- if (callbacks === null || callbacks === void 0 ? void 0 : callbacks.onConfirmationRequired) {
74
- return yield callbacks.onConfirmationRequired(message);
75
- }
76
- return false;
77
- }),
78
- });
79
- queueManager.addToQueue(predefinedActions);
80
- if (callbacks === null || callbacks === void 0 ? void 0 : callbacks.onQueueStart) {
81
- callbacks.onQueueStart(predefinedActions);
82
- }
83
- console.log("Processing queue...");
84
- const results = yield queueManager.processQueue();
85
- console.log("Queue completed:");
86
- console.dir(results, { depth: null });
87
- return {
88
- type: "success",
89
- data: results || [],
90
- };
91
- }
92
- catch (error) {
93
- console.error("Error processing prompt:", error);
94
- throw error;
95
- }
96
- });
97
- }
98
- createCallbacks(prompt, similarActions) {
99
- return {
100
- onQueueStart: (actions) => __awaiter(this, void 0, void 0, function* () {
101
- console.dir(actions, { depth: null });
102
- this.dependencies.eventEmitter.emit("orchestrator-update", {
103
- type: "queue-start",
104
- actions,
105
- });
106
- }),
107
- onActionStart: (action) => {
108
- this.dependencies.eventEmitter.emit("orchestrator-update", {
109
- type: "action-start",
110
- action: action.name,
111
- args: action.parameters,
112
- });
113
- },
114
- onActionComplete: (action) => {
115
- this.dependencies.eventEmitter.emit("orchestrator-update", {
116
- type: "action-complete",
117
- action: action.name,
118
- result: action.result,
119
- });
120
- },
121
- onQueueComplete: (actions) => __awaiter(this, void 0, void 0, function* () {
122
- if (!similarActions.length) {
123
- yield this.saveToMemory(prompt, actions);
124
- }
125
- this.dependencies.eventEmitter.emit("orchestrator-update", {
126
- type: "queue-complete",
127
- });
128
- }),
129
- onConfirmationRequired: this.handleConfirmationRequest.bind(this),
130
- };
131
- }
132
- handleConfirmationRequest(message) {
133
- return __awaiter(this, void 0, void 0, function* () {
134
- return new Promise((resolve) => {
135
- const confirmationId = Date.now().toString();
136
- const handleConfirmation = (data) => {
137
- if (data.confirmationId === confirmationId) {
138
- this.dependencies.eventEmitter.removeListener("confirmation-response", handleConfirmation);
139
- resolve(data.confirmed);
140
- }
141
- };
142
- this.dependencies.eventEmitter.once("confirmation-response", handleConfirmation);
143
- this.dependencies.eventEmitter.emit("orchestrator-update", {
144
- type: "confirmation-required",
145
- id: confirmationId,
146
- message,
147
- });
148
- setTimeout(() => {
149
- this.dependencies.eventEmitter.removeListener("confirmation-response", handleConfirmation);
150
- resolve(false);
151
- }, this.CONFIRMATION_TIMEOUT);
152
- });
153
- });
154
- }
155
- saveToMemory(prompt, actions) {
156
- return __awaiter(this, void 0, void 0, function* () {
157
- console.log("\n🔍 Creating memory...");
158
- yield this.dependencies.memoryCache.createMemory({
159
- content: prompt,
160
- userId: this.user.id,
161
- scope: types_1.MemoryScope.USER,
162
- type: types_1.MemoryType.ACTION,
163
- data: actions,
164
- });
165
- });
166
- }
167
- handleActionResults(actionsResult_1, prompt_1) {
168
- return __awaiter(this, arguments, void 0, function* (actionsResult, prompt, stream = true) {
169
- if (!this.hasNonPrepareActions(actionsResult.data)) {
170
- return;
171
- }
172
- const summarizer = new synthesizer_1.Summarizer();
173
- const summaryData = JSON.stringify({
174
- result: actionsResult.data,
175
- initialPrompt: prompt,
176
- });
177
- return stream
178
- ? (yield summarizer.streamProcess(summaryData)).toDataStreamResponse()
179
- : yield summarizer.process(summaryData);
180
- });
181
- }
182
- hasNonPrepareActions(actions) {
183
- return (Array.isArray(actions) &&
184
- actions.some((action) => { var _a; return ((_a = action.name) === null || _a === void 0 ? void 0 : _a.split("-")[0]) !== "prepare"; }));
185
- }
186
- }
187
- exports.Workflow = Workflow;
File without changes
File without changes