@ai.ntellect/core 0.8.0 → 0.8.2
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/README.md +206 -74
- package/dist/graph/index.d.ts +3 -4
- package/dist/graph/index.d.ts.map +1 -1
- package/dist/graph/index.js +6 -6
- package/dist/graph/index.js.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/modules/agent/agent.d.ts.map +1 -1
- package/dist/modules/agent/agent.js +2 -5
- package/dist/modules/agent/agent.js.map +1 -1
- package/dist/modules/agent/generic-assistant.d.ts.map +1 -1
- package/dist/modules/agent/generic-assistant.js +2 -2
- package/dist/modules/agent/generic-assistant.js.map +1 -1
- package/dist/modules/agent/generic-executor.d.ts +1 -0
- package/dist/modules/agent/generic-executor.d.ts.map +1 -1
- package/dist/modules/agent/generic-executor.js +23 -34
- package/dist/modules/agent/generic-executor.js.map +1 -1
- package/dist/types/index.d.ts +89 -24
- package/dist/types/index.d.ts.map +1 -1
- package/graph/index.ts +8 -10
- package/index.ts +2 -0
- package/modules/agent/agent.ts +6 -7
- package/modules/agent/generic-assistant.ts +6 -4
- package/modules/agent/generic-executor.ts +32 -39
- package/package.json +1 -1
- package/test/graph/controller.test.ts +2 -2
- package/test/graph/index.test.ts +27 -27
- package/test/graph/observer.test.ts +18 -23
- package/types/index.ts +91 -27
@@ -17,6 +17,7 @@ const chalk_1 = __importDefault(require("chalk"));
|
|
17
17
|
const zod_1 = require("zod");
|
18
18
|
const executor_1 = require("./base/executor");
|
19
19
|
const llm_factory_1 = require("./llm-factory");
|
20
|
+
const prompt_builder_1 = require("./prompt-builder");
|
20
21
|
/**
|
21
22
|
* Generic executor that handles the interaction between the agent and LLM
|
22
23
|
* Uses a structured prompt format:
|
@@ -86,6 +87,25 @@ ${graph
|
|
86
87
|
})
|
87
88
|
.join("\n\n");
|
88
89
|
}
|
90
|
+
buildSystemPrompt(context) {
|
91
|
+
return __awaiter(this, void 0, void 0, function* () {
|
92
|
+
return new prompt_builder_1.PromptBuilder()
|
93
|
+
.addSection("ROLE", this.agent.getRole())
|
94
|
+
.addSection("GOAL", this.agent.getGoal())
|
95
|
+
.addSection("BACKSTORY", this.agent.getBackstory())
|
96
|
+
.addSection("RECENT ACTIONS (check this before deciding what to do)", context.knowledge || "None")
|
97
|
+
.addSection("AVAILABLE ACTIONS (only if you need)", this.generateActionSchema())
|
98
|
+
.addSection("INSTRUCTIONS", `
|
99
|
+
- Never take actions if an recent action matches the user's input
|
100
|
+
- If you need to take actions, structure parameters according to the action's schema
|
101
|
+
- If goal is achieved, explain that you achieved for examples:
|
102
|
+
- "I have achieved the goal"
|
103
|
+
- "I have done what I needed to do"
|
104
|
+
- "I have completed the task"
|
105
|
+
`)
|
106
|
+
.build(context);
|
107
|
+
});
|
108
|
+
}
|
89
109
|
/**
|
90
110
|
* Makes a decision based on the current context using the LLM
|
91
111
|
* @param {AgentContext} context - The context to base the decision on
|
@@ -93,44 +113,13 @@ ${graph
|
|
93
113
|
*/
|
94
114
|
makeDecision(context) {
|
95
115
|
return __awaiter(this, void 0, void 0, function* () {
|
96
|
-
var _a;
|
97
116
|
this.log("thinking", chalk_1.default.dim("Analyzing context and available actions..."));
|
98
|
-
const
|
99
|
-
|
100
|
-
this.log("info", chalk_1.default.dim("Retrieved relevant memories:"));
|
101
|
-
memories.forEach((m) => this.log("info", chalk_1.default.dim(`- ${m.content}`)));
|
102
|
-
context.knowledge =
|
103
|
-
(context.knowledge || "") +
|
104
|
-
"\n" +
|
105
|
-
memories.map((m) => m.content).join("\n");
|
106
|
-
}
|
107
|
-
const systemPrompt = `
|
108
|
-
## ROLE
|
109
|
-
${this.agent.getRole()}
|
110
|
-
|
111
|
-
## GOAL
|
112
|
-
${this.agent.getGoal()}
|
113
|
-
|
114
|
-
## BACKSTORY
|
115
|
-
${this.agent.getBackstory()}
|
116
|
-
|
117
|
-
## RECENT ACTIONS
|
118
|
-
${context.knowledge ? `${context.knowledge}\n` : "None"}
|
119
|
-
|
120
|
-
## AVAILABLE ACTIONS
|
121
|
-
${this.generateActionSchema()}
|
122
|
-
|
123
|
-
## INSTRUCTIONS
|
124
|
-
- Analyze the user input and what you have done (if no action is needed, just return an empty array)
|
125
|
-
- Choose appropriate actions based on their parameters
|
126
|
-
- Structure parameters according to the action's schema
|
127
|
-
- Look at the goal and the actions you have done, if you have achieved the goal, STOP
|
128
|
-
`;
|
117
|
+
const systemPrompt = yield this.buildSystemPrompt(context);
|
118
|
+
console.log({ systemPrompt });
|
129
119
|
this.log("info", chalk_1.default.dim("Generating response..."));
|
130
120
|
const result = yield this.llm.generate({
|
131
121
|
system: systemPrompt,
|
132
|
-
user: `User
|
133
|
-
Actions you have already done: ${((_a = context.executedActions) === null || _a === void 0 ? void 0 : _a.map((a) => `\n- ${a.name} => ${JSON.stringify(a.result)}`).join("")) || "None"}`,
|
122
|
+
user: `User sent you this message at ${new Date().toISOString()}\n${context.input.raw}`,
|
134
123
|
}, zod_1.z.object({
|
135
124
|
actions: zod_1.z.array(zod_1.z.object({
|
136
125
|
name: zod_1.z.string(),
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"generic-executor.js","sourceRoot":"","sources":["../../../modules/agent/generic-executor.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,kDAA0B;AAC1B,6BAAwB;AASxB,8CAAgD;AAChD,+CAA2C;
|
1
|
+
{"version":3,"file":"generic-executor.js","sourceRoot":"","sources":["../../../modules/agent/generic-executor.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,kDAA0B;AAC1B,6BAAwB;AASxB,8CAAgD;AAChD,+CAA2C;AAC3C,qDAAiD;AAEjD;;;;;;;;;;;GAWG;AACH,MAAa,eAAgB,SAAQ,wBAAa;IAIhD;;;;;OAKG;IACH,YACE,KAAgB,EAChB,MAAwB,EACxB,MAAsB;;QAEtB,KAAK,CAAC,KAAK,EA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C,OAAO,CACnC,SAAS,EACT,SAAS,EACT,eAAe,CAChB,CAAC;gBAEF,IAAI,CAAC,GAAG,CAAC,SAAS,EAAE,eAAK,CAAC,KAAK,CAAC,YAAY,QAAQ,CAAC,IAAI,YAAY,CAAC,CAAC,CAAC;gBACxE,IAAI,CAAC,GAAG,CAAC,MAAM,EAAE,eAAK,CAAC,GAAG,CAAC,WAAW,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;gBAE1E,IAAI,OAAO,CAAC,eAAe,EAAE,CAAC;oBAC5B,OAAO,CAAC,eAAe,CAAC,IAAI,CAAC;wBAC3B,IAAI,EAAE,QAAQ,CAAC,IAAI;wBACnB,MAAM,EAAE,MAAM;wBACd,SAAS,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;wBACnC,UAAU,EAAE,IAAI;qBACjB,CAAC,CAAC;gBACL,CAAC;YACH,CAAC;QACH,CAAC;KAAA;CACF;AAjOD,0CAiOC"}
|
package/dist/types/index.d.ts
CHANGED
@@ -65,12 +65,44 @@ export type GraphContext<T extends ZodSchema> = {
|
|
65
65
|
[key: string]: any;
|
66
66
|
};
|
67
67
|
/**
|
68
|
-
* Configuration for event handling in
|
68
|
+
* Configuration for event handling strategies in nodes
|
69
|
+
* @typedef {Object} EventStrategy
|
70
|
+
* @property {"single" | "all" | "correlate"} type - The type of event handling strategy
|
71
|
+
* - single: Waits for any single event from the specified events
|
72
|
+
* - all: Waits for all specified events to occur
|
73
|
+
* - correlate: Uses a correlation function to match related events
|
74
|
+
* @property {(events: any[]) => boolean} [correlation] - Optional correlation function for "correlate" strategy
|
69
75
|
*/
|
70
76
|
export type EventStrategy = {
|
71
77
|
type: "single" | "all" | "correlate";
|
72
78
|
correlation?: (events: any[]) => boolean;
|
73
79
|
};
|
80
|
+
/**
|
81
|
+
* Configuration for event handling in nodes
|
82
|
+
* @typedef {Object} EventConfig
|
83
|
+
* @property {string[]} events - Array of event names to wait for
|
84
|
+
* @property {number} [timeout] - Optional timeout in milliseconds
|
85
|
+
* @property {EventStrategy} strategy - Strategy for handling multiple events
|
86
|
+
* @property {(events: any[]) => Promise<void>} [onSuccess] - Optional callback when events are successfully received
|
87
|
+
* @property {() => Promise<void>} [onTimeout] - Optional callback when event waiting times out
|
88
|
+
* @example
|
89
|
+
* ```typescript
|
90
|
+
* const eventConfig: EventConfig = {
|
91
|
+
* events: ["payment.received", "order.validated"],
|
92
|
+
* timeout: 5000,
|
93
|
+
* strategy: {
|
94
|
+
* type: "correlate",
|
95
|
+
* correlation: (events) => events.every(e => e.transactionId === events[0].transactionId)
|
96
|
+
* },
|
97
|
+
* onSuccess: async (events) => {
|
98
|
+
* console.log("Correlated events received:", events);
|
99
|
+
* },
|
100
|
+
* onTimeout: async () => {
|
101
|
+
* console.log("Event waiting timed out");
|
102
|
+
* }
|
103
|
+
* };
|
104
|
+
* ```
|
105
|
+
*/
|
74
106
|
export type EventConfig = {
|
75
107
|
events: string[];
|
76
108
|
timeout?: number;
|
@@ -78,12 +110,60 @@ export type EventConfig = {
|
|
78
110
|
onSuccess?: (events: any[]) => Promise<void>;
|
79
111
|
onTimeout?: () => Promise<void>;
|
80
112
|
};
|
113
|
+
/**
|
114
|
+
* Represents an event in the graph system
|
115
|
+
* @template T - Schema type for context validation
|
116
|
+
* @property {string} type - The type/name of the event
|
117
|
+
* @property {any} [payload] - Optional payload data
|
118
|
+
* @property {number} timestamp - Unix timestamp of when the event occurred
|
119
|
+
* @example
|
120
|
+
* ```typescript
|
121
|
+
* const event: GraphEvent<MySchema> = {
|
122
|
+
* type: "payment.received",
|
123
|
+
* payload: {
|
124
|
+
* transactionId: "tx123",
|
125
|
+
* amount: 100,
|
126
|
+
* currency: "USD"
|
127
|
+
* },
|
128
|
+
* timestamp: Date.now()
|
129
|
+
* };
|
130
|
+
* ```
|
131
|
+
*/
|
132
|
+
export type GraphEvent<T extends ZodSchema> = {
|
133
|
+
type: string;
|
134
|
+
payload?: any;
|
135
|
+
timestamp: number;
|
136
|
+
};
|
137
|
+
/**
|
138
|
+
* Configuration for waiting on multiple events
|
139
|
+
* @template T - Schema type for context validation
|
140
|
+
* @property {string[]} events - Array of event names to wait for
|
141
|
+
* @property {number} [timeout] - Optional timeout in milliseconds
|
142
|
+
* @property {"all" | "any" | "race"} strategy - Strategy for handling multiple events
|
143
|
+
* @property {(context: GraphContext<T>) => Promise<void>} [onSuccess] - Optional success callback
|
144
|
+
* @example
|
145
|
+
* ```typescript
|
146
|
+
* const config: WaitForEvents<MySchema> = {
|
147
|
+
* events: ["event1", "event2"],
|
148
|
+
* timeout: 5000,
|
149
|
+
* strategy: "all",
|
150
|
+
* onSuccess: async (context) => {
|
151
|
+
* console.log("All events received");
|
152
|
+
* }
|
153
|
+
* };
|
154
|
+
* ```
|
155
|
+
*/
|
156
|
+
export type WaitForEvents<T extends ZodSchema> = {
|
157
|
+
events: string[];
|
158
|
+
timeout?: number;
|
159
|
+
strategy: "all" | "any" | "race";
|
160
|
+
onSuccess?: <T extends ZodSchema>(context: GraphContext<T>) => Promise<void>;
|
161
|
+
};
|
81
162
|
/**
|
82
163
|
* Interface representing a node in the graph
|
83
164
|
* @interface
|
84
165
|
* @template T - Schema type
|
85
|
-
* @template
|
86
|
-
* @template O - Output schema type
|
166
|
+
* @template P - Parameters type
|
87
167
|
*/
|
88
168
|
export interface GraphNodeConfig<T extends ZodSchema, P = any> {
|
89
169
|
/** Name of the node */
|
@@ -96,9 +176,9 @@ export interface GraphNodeConfig<T extends ZodSchema, P = any> {
|
|
96
176
|
execute: (context: GraphContext<T>, params?: P, tools?: {
|
97
177
|
eventEmitter: IEventEmitter;
|
98
178
|
}) => Promise<void>;
|
99
|
-
/** Optional condition for node
|
179
|
+
/** Optional condition for node execution */
|
100
180
|
condition?: (context: GraphContext<T>, params?: P) => boolean;
|
101
|
-
/** Array of next node names or objects with conditions
|
181
|
+
/** Array of next node names or objects with conditions */
|
102
182
|
next?: Array<string | {
|
103
183
|
node: string;
|
104
184
|
condition: (context: GraphContext<T>) => boolean;
|
@@ -109,13 +189,9 @@ export interface GraphNodeConfig<T extends ZodSchema, P = any> {
|
|
109
189
|
when?: EventConfig;
|
110
190
|
/** Retry configuration */
|
111
191
|
retry?: {
|
112
|
-
/** Maximum number of retry attempts */
|
113
192
|
maxAttempts: number;
|
114
|
-
/** Delay between retries in milliseconds */
|
115
193
|
delay: number;
|
116
|
-
/** Error handler function */
|
117
194
|
onRetryFailed?: (error: Error, context: GraphContext<T>) => Promise<void>;
|
118
|
-
/** Continue execution on failed retry */
|
119
195
|
continueOnFailed?: boolean;
|
120
196
|
};
|
121
197
|
/** Error handler function */
|
@@ -130,12 +206,12 @@ export interface GraphNodeConfig<T extends ZodSchema, P = any> {
|
|
130
206
|
export type GraphConfig<T extends ZodSchema> = {
|
131
207
|
/** Name of the graph */
|
132
208
|
name: string;
|
133
|
-
/** Array of nodes in the graph */
|
134
|
-
nodes: GraphNodeConfig<T, any>[];
|
135
|
-
/** Initial context */
|
136
|
-
context: SchemaType<T>;
|
137
209
|
/** Schema for validation */
|
138
210
|
schema: T;
|
211
|
+
/** Initial context */
|
212
|
+
context: SchemaType<T>;
|
213
|
+
/** Array of nodes in the graph */
|
214
|
+
nodes: GraphNodeConfig<T, any>[];
|
139
215
|
/** Global error handler */
|
140
216
|
onError?: (error: Error, context: GraphContext<T>) => void;
|
141
217
|
/** Entry node name */
|
@@ -178,17 +254,6 @@ export type MeilisearchSettings = {
|
|
178
254
|
/** Array of sortable attributes */
|
179
255
|
sortableAttributes?: string[];
|
180
256
|
};
|
181
|
-
export type GraphEvent<T extends ZodSchema> = {
|
182
|
-
type: string;
|
183
|
-
payload?: any;
|
184
|
-
timestamp: number;
|
185
|
-
};
|
186
|
-
export type WaitForEvents<T extends ZodSchema> = {
|
187
|
-
events: string[];
|
188
|
-
timeout?: number;
|
189
|
-
strategy: "all" | "any" | "race";
|
190
|
-
onSuccess?: <T extends ZodSchema>(context: GraphContext<T>) => Promise<void>;
|
191
|
-
};
|
192
257
|
/**
|
193
258
|
* Configuration interface for NLP Engine
|
194
259
|
* @interface NLPConfig
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../types/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AACtC,OAAO,EAAE,SAAS,EAAE,MAAM,KAAK,CAAC;AAChC,OAAO,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAI9C;;;;;;;GAOG;AACH,MAAM,WAAW,iBAAiB;IAChC,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IAC/B,SAAS,CAAC,EAAE,MAAM,EAAE,CAAC;IACrB,MAAM,EAAE,MAAM,CAAC;IACf,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AAED;;;;;;;;;GASG;AACH,MAAM,WAAW,cAAc;IAC7B,EAAE,EAAE,MAAM,CAAC;IACX,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IAC/B,SAAS,CAAC,EAAE,MAAM,EAAE,CAAC;IACrB,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,IAAI,CAAC;CACjB;AAID;;;GAGG;AACH,MAAM,MAAM,gBAAgB,GAAG;IAC7B,kDAAkD;IAClD,EAAE,EAAE,MAAM,CAAC;IACX,kCAAkC;IAClC,eAAe,EAAE,MAAM,CAAC;IACxB,yCAAyC;IACzC,cAAc,EAAE,MAAM,CAAC;IACvB,uCAAuC;IACvC,WAAW,EAAE,OAAO,CAAC;IACrB,wBAAwB;IACxB,SAAS,EAAE,IAAI,CAAC;CACjB,CAAC;AAIF;;;GAGG;AACH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,CAAC;CAC/B,CAAC"}
|
package/graph/index.ts
CHANGED
@@ -37,6 +37,7 @@ export class GraphFlow<T extends ZodSchema> {
|
|
37
37
|
private entryNode?: string;
|
38
38
|
private verbose: boolean = false;
|
39
39
|
public nodes: Map<string, GraphNodeConfig<T, any>>;
|
40
|
+
public name: string;
|
40
41
|
|
41
42
|
private eventSubject: Subject<GraphEvent<T>> = new Subject();
|
42
43
|
private stateSubject: BehaviorSubject<GraphContext<T>>;
|
@@ -51,15 +52,11 @@ export class GraphFlow<T extends ZodSchema> {
|
|
51
52
|
|
52
53
|
/**
|
53
54
|
* Creates a new instance of GraphFlow
|
54
|
-
* @param {
|
55
|
-
* @param {GraphConfig<T>} config - Configuration object containing nodes, schema, context, and error handlers
|
55
|
+
* @param {GraphConfig<T>} config - Configuration object containing name, nodes, schema, context, and error handlers
|
56
56
|
* @param {Object} options - Optional options for the graph flow
|
57
57
|
*/
|
58
|
-
constructor(
|
59
|
-
|
60
|
-
config: GraphConfig<T>,
|
61
|
-
options: { verbose?: boolean } = {}
|
62
|
-
) {
|
58
|
+
constructor(config: GraphConfig<T>, options: { verbose?: boolean } = {}) {
|
59
|
+
this.name = config.name;
|
63
60
|
this.nodes = new Map(
|
64
61
|
config.nodes.map((node: GraphNodeConfig<T, any>) => [node.name, node])
|
65
62
|
);
|
@@ -69,22 +66,23 @@ export class GraphFlow<T extends ZodSchema> {
|
|
69
66
|
this.eventEmitter =
|
70
67
|
config.eventEmitter || (new EventEmitter() as IEventEmitter);
|
71
68
|
this.graphEvents = config.events;
|
69
|
+
this.entryNode = config.entryNode;
|
72
70
|
this.verbose = options.verbose ?? false;
|
73
71
|
|
74
72
|
this.stateSubject = new BehaviorSubject<GraphContext<T>>(this.context);
|
75
73
|
|
76
|
-
this.logger = new GraphLogger(name, options.verbose);
|
74
|
+
this.logger = new GraphLogger(this.name, options.verbose);
|
77
75
|
this.eventManager = new GraphEventManager(
|
78
76
|
this.eventEmitter,
|
79
77
|
this.nodes,
|
80
|
-
name,
|
78
|
+
this.name,
|
81
79
|
this.context,
|
82
80
|
config.events,
|
83
81
|
config.entryNode,
|
84
82
|
config.onError
|
85
83
|
);
|
86
84
|
this.nodeExecutor = new GraphNode(
|
87
|
-
this.nodes
|
85
|
+
this.nodes,
|
88
86
|
this.logger,
|
89
87
|
this.eventManager,
|
90
88
|
this.eventSubject,
|
package/index.ts
CHANGED
@@ -12,6 +12,7 @@
|
|
12
12
|
*/
|
13
13
|
|
14
14
|
export * from "./modules/agent/agent";
|
15
|
+
export * from "./modules/agent/prompt-builder";
|
15
16
|
|
16
17
|
export * from "./graph/controller";
|
17
18
|
export * from "./graph/event-manager";
|
@@ -23,6 +24,7 @@ export * from "./graph/visualizer";
|
|
23
24
|
export * from "./interfaces";
|
24
25
|
export * from "./modules/agenda";
|
25
26
|
export * from "./modules/embedding";
|
27
|
+
export * from "./modules/memory";
|
26
28
|
|
27
29
|
export * from "./types";
|
28
30
|
|
package/modules/agent/agent.ts
CHANGED
@@ -1,3 +1,4 @@
|
|
1
|
+
import { GraphContext } from "@/types";
|
1
2
|
import { GraphFlow } from "../../graph/index";
|
2
3
|
import {
|
3
4
|
AgentConfig,
|
@@ -51,31 +52,29 @@ export class Agent {
|
|
51
52
|
* @returns {GraphFlow<typeof AgentContextSchema>} The configured workflow
|
52
53
|
*/
|
53
54
|
private setupWorkflow(): GraphFlow<typeof AgentContextSchema> {
|
54
|
-
return new GraphFlow(
|
55
|
+
return new GraphFlow({
|
55
56
|
name: "assistant",
|
56
57
|
schema: AgentContextSchema,
|
57
58
|
context: {
|
58
59
|
input: { raw: "" },
|
59
60
|
actions: [],
|
60
61
|
response: "",
|
61
|
-
executedActions: [],
|
62
62
|
},
|
63
63
|
nodes: [
|
64
64
|
{
|
65
65
|
name: "process",
|
66
|
-
execute: async (context) => {
|
66
|
+
execute: async (context: GraphContext<typeof AgentContextSchema>) => {
|
67
67
|
const agentContext = context as unknown as AgentContext;
|
68
68
|
const decision = await this.executor.makeDecision(agentContext);
|
69
69
|
context.actions = decision.actions;
|
70
70
|
context.response = decision.response;
|
71
71
|
},
|
72
|
-
next: (context
|
72
|
+
next: (context: GraphContext<typeof AgentContextSchema>) =>
|
73
|
+
context.actions.length > 0 ? ["execute"] : [],
|
73
74
|
},
|
74
75
|
{
|
75
76
|
name: "execute",
|
76
|
-
execute: async (context) => {
|
77
|
-
console.log(`Executing actions:`);
|
78
|
-
console.log(context.actions);
|
77
|
+
execute: async (context: GraphContext<typeof AgentContextSchema>) => {
|
79
78
|
const timestamp = new Date().toISOString();
|
80
79
|
context.knowledge = `Date: ${timestamp}\n${JSON.stringify(
|
81
80
|
context.actions
|
@@ -1,3 +1,4 @@
|
|
1
|
+
import { GraphContext } from "@/types";
|
1
2
|
import { GraphFlow } from "../../graph/index";
|
2
3
|
import {
|
3
4
|
AgentConfig,
|
@@ -41,7 +42,7 @@ export class Agent {
|
|
41
42
|
}
|
42
43
|
|
43
44
|
private setupWorkflow(): GraphFlow<typeof AgentContextSchema> {
|
44
|
-
return new GraphFlow(
|
45
|
+
return new GraphFlow({
|
45
46
|
name: "assistant",
|
46
47
|
schema: AgentContextSchema,
|
47
48
|
context: {
|
@@ -53,17 +54,18 @@ export class Agent {
|
|
53
54
|
nodes: [
|
54
55
|
{
|
55
56
|
name: "process",
|
56
|
-
execute: async (context) => {
|
57
|
+
execute: async (context: GraphContext<typeof AgentContextSchema>) => {
|
57
58
|
const agentContext = context as unknown as AgentContext;
|
58
59
|
const decision = await this.executor.makeDecision(agentContext);
|
59
60
|
context.actions = decision.actions;
|
60
61
|
context.response = decision.response;
|
61
62
|
},
|
62
|
-
next: (context
|
63
|
+
next: (context: GraphContext<typeof AgentContextSchema>) =>
|
64
|
+
context.actions.length > 0 ? ["execute"] : [],
|
63
65
|
},
|
64
66
|
{
|
65
67
|
name: "execute",
|
66
|
-
execute: async (context) => {
|
68
|
+
execute: async (context: GraphContext<typeof AgentContextSchema>) => {
|
67
69
|
console.log(`Executing actions:`);
|
68
70
|
console.log(context.actions);
|
69
71
|
|
@@ -10,6 +10,7 @@ import {
|
|
10
10
|
import { BaseAgent } from "./base";
|
11
11
|
import { AgentExecutor } from "./base/executor";
|
12
12
|
import { LLMFactory } from "./llm-factory";
|
13
|
+
import { PromptBuilder } from "./prompt-builder";
|
13
14
|
|
14
15
|
/**
|
15
16
|
* Generic executor that handles the interaction between the agent and LLM
|
@@ -96,6 +97,33 @@ ${graph
|
|
96
97
|
.join("\n\n");
|
97
98
|
}
|
98
99
|
|
100
|
+
private async buildSystemPrompt(context: AgentContext): Promise<string> {
|
101
|
+
return new PromptBuilder()
|
102
|
+
.addSection("ROLE", this.agent.getRole())
|
103
|
+
.addSection("GOAL", this.agent.getGoal())
|
104
|
+
.addSection("BACKSTORY", this.agent.getBackstory())
|
105
|
+
.addSection(
|
106
|
+
"RECENT ACTIONS (check this before deciding what to do)",
|
107
|
+
context.knowledge || "None"
|
108
|
+
)
|
109
|
+
.addSection(
|
110
|
+
"AVAILABLE ACTIONS (only if you need)",
|
111
|
+
this.generateActionSchema()
|
112
|
+
)
|
113
|
+
.addSection(
|
114
|
+
"INSTRUCTIONS",
|
115
|
+
`
|
116
|
+
- Never take actions if an recent action matches the user's input
|
117
|
+
- If you need to take actions, structure parameters according to the action's schema
|
118
|
+
- If goal is achieved, explain that you achieved for examples:
|
119
|
+
- "I have achieved the goal"
|
120
|
+
- "I have done what I needed to do"
|
121
|
+
- "I have completed the task"
|
122
|
+
`
|
123
|
+
)
|
124
|
+
.build(context);
|
125
|
+
}
|
126
|
+
|
99
127
|
/**
|
100
128
|
* Makes a decision based on the current context using the LLM
|
101
129
|
* @param {AgentContext} context - The context to base the decision on
|
@@ -107,50 +135,16 @@ ${graph
|
|
107
135
|
chalk.dim("Analyzing context and available actions...")
|
108
136
|
);
|
109
137
|
|
110
|
-
const
|
111
|
-
if (memories.length > 0) {
|
112
|
-
this.log("info", chalk.dim("Retrieved relevant memories:"));
|
113
|
-
memories.forEach((m) => this.log("info", chalk.dim(`- ${m.content}`)));
|
114
|
-
|
115
|
-
context.knowledge =
|
116
|
-
(context.knowledge || "") +
|
117
|
-
"\n" +
|
118
|
-
memories.map((m) => m.content).join("\n");
|
119
|
-
}
|
120
|
-
|
121
|
-
const systemPrompt = `
|
122
|
-
## ROLE
|
123
|
-
${this.agent.getRole()}
|
124
|
-
|
125
|
-
## GOAL
|
126
|
-
${this.agent.getGoal()}
|
127
|
-
|
128
|
-
## BACKSTORY
|
129
|
-
${this.agent.getBackstory()}
|
130
|
-
|
131
|
-
## RECENT ACTIONS
|
132
|
-
${context.knowledge ? `${context.knowledge}\n` : "None"}
|
133
|
-
|
134
|
-
## AVAILABLE ACTIONS
|
135
|
-
${this.generateActionSchema()}
|
136
|
-
|
137
|
-
## INSTRUCTIONS
|
138
|
-
- Analyze the user input and what you have done (if no action is needed, just return an empty array)
|
139
|
-
- Choose appropriate actions based on their parameters
|
140
|
-
- Structure parameters according to the action's schema
|
141
|
-
- Look at the goal and the actions you have done, if you have achieved the goal, STOP
|
142
|
-
`;
|
138
|
+
const systemPrompt = await this.buildSystemPrompt(context);
|
143
139
|
|
140
|
+
console.log({ systemPrompt });
|
144
141
|
this.log("info", chalk.dim("Generating response..."));
|
145
142
|
|
146
143
|
const result = await this.llm.generate(
|
147
144
|
{
|
148
145
|
system: systemPrompt,
|
149
|
-
user: `User
|
150
|
-
|
151
|
-
context.executedActions
|
152
|
-
?.map((a) => `\n- ${a.name} => ${JSON.stringify(a.result)}`)
|
153
|
-
.join("") || "None"
|
146
|
+
user: `User sent you this message at ${new Date().toISOString()}\n${
|
147
|
+
context.input.raw
|
154
148
|
}`,
|
155
149
|
},
|
156
150
|
z.object({
|
@@ -168,7 +162,6 @@ ${graph
|
|
168
162
|
response: z.string(),
|
169
163
|
})
|
170
164
|
);
|
171
|
-
|
172
165
|
if (result.object.actions.length > 0) {
|
173
166
|
this.log("success", chalk.green("Decided to take actions:"));
|
174
167
|
result.object.actions.forEach(
|
package/package.json
CHANGED
@@ -27,7 +27,7 @@ describe("GraphController", () => {
|
|
27
27
|
},
|
28
28
|
];
|
29
29
|
|
30
|
-
return new GraphFlow(
|
30
|
+
return new GraphFlow({
|
31
31
|
name,
|
32
32
|
nodes,
|
33
33
|
schema: TestSchema,
|
@@ -119,7 +119,7 @@ describe("GraphController", () => {
|
|
119
119
|
});
|
120
120
|
|
121
121
|
it("should handle errors in parallel execution", async () => {
|
122
|
-
const errorGraph = new GraphFlow(
|
122
|
+
const errorGraph = new GraphFlow({
|
123
123
|
name: "errorGraph",
|
124
124
|
nodes: [
|
125
125
|
{
|