-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
agent.ts
354 lines (323 loc) Β· 10 KB
/
agent.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
import type { BaseLanguageModelInterface } from "@langchain/core/language_models/base";
import type { VectorStoreInterface } from "@langchain/core/vectorstores";
import { Document } from "@langchain/core/documents";
import { ChainValues } from "@langchain/core/utils/types";
import { CallbackManagerForChainRun } from "@langchain/core/callbacks/manager";
import { BaseChain, ChainInputs } from "../../chains/base.js";
import { SerializedBaseChain } from "../../chains/serde.js";
import { Optional } from "../../types/type-utils.js";
import { TaskCreationChain } from "./task_creation.js";
import { TaskExecutionChain } from "./task_execution.js";
import { TaskPrioritizationChain } from "./task_prioritization.js";
/**
* Interface defining the structure of a task. A task has a `taskID` and a
* `taskName`.
*/
export interface Task {
taskID: string;
taskName: string;
}
/**
* Interface defining the structure of the inputs for the `BabyAGI` class.
* It extends the `ChainInputs` interface, omitting the 'memory' and
* 'callbackManager' properties, and adds properties specific to
* `BabyAGI`.
*/
export interface BabyAGIInputs
extends Omit<ChainInputs, "memory" | "callbackManager"> {
creationChain: BaseChain;
prioritizationChain: BaseChain;
executionChain: BaseChain;
vectorstore: VectorStoreInterface;
maxIterations?: number;
}
/**
* Class responsible for managing tasks, including their creation,
* prioritization, and execution. It uses three chains for these
* operations: `creationChain`, `prioritizationChain`, and
* `executionChain`.
* @example
* ```typescript
* const babyAGI = BabyAGI.fromLLM({
* llm: new OpenAI({ temperature: 0 }),
* vectorstore: new MemoryVectorStore(new OpenAIEmbeddings()),
* maxIterations: 3,
* });
*
* const result = await babyAGI.call({
* objective: "Write a weather report for SF today",
* });
* ```
*/
export class BabyAGI extends BaseChain implements BabyAGIInputs {
static lc_name() {
return "BabyAGI";
}
taskList: Task[];
creationChain: BaseChain;
prioritizationChain: BaseChain;
executionChain: BaseChain;
taskIDCounter: number;
vectorstore: VectorStoreInterface;
maxIterations: number;
constructor({
creationChain,
prioritizationChain,
executionChain,
vectorstore,
maxIterations = 100,
verbose,
callbacks,
}: BabyAGIInputs) {
super(undefined, verbose, callbacks);
this.taskList = [];
this.creationChain = creationChain;
this.prioritizationChain = prioritizationChain;
this.executionChain = executionChain;
this.taskIDCounter = 1;
this.vectorstore = vectorstore;
this.maxIterations = maxIterations;
}
_chainType() {
return "BabyAGI" as const;
}
get inputKeys() {
return ["objective", "firstTask"];
}
get outputKeys() {
return [];
}
/**
* Adds a task to the task list.
* @param task The task to be added.
* @returns Promise resolving to void.
*/
async addTask(task: Task) {
this.taskList.push(task);
}
/**
* Prints the current task list to the console.
* @returns void
*/
printTaskList() {
console.log("\x1b[95m\x1b[1m\n*****TASK LIST*****\n\x1b[0m\x1b[0m");
for (const t of this.taskList) {
console.log(`${t.taskID}: ${t.taskName}`);
}
}
/**
* Prints the next task to the console.
* @param task The next task to be printed.
* @returns void
*/
printNextTask(task: Task) {
console.log("\x1b[92m\x1b[1m\n*****NEXT TASK*****\n\x1b[0m\x1b[0m");
console.log(`${task.taskID}: ${task.taskName}`);
}
/**
* Prints the result of a task to the console.
* @param result The result of the task.
* @returns void
*/
printTaskResult(result: string) {
console.log("\x1b[93m\x1b[1m\n*****TASK RESULT*****\n\x1b[0m\x1b[0m");
console.log(result.trim());
}
/**
* Generates the next tasks based on the result of the previous task, the
* task description, and the objective.
* @param result The result of the previous task.
* @param task_description The description of the task.
* @param objective The objective of the task.
* @param runManager Optional CallbackManagerForChainRun instance.
* @returns Promise resolving to an array of tasks without taskID.
*/
async getNextTasks(
result: string,
task_description: string,
objective: string,
runManager?: CallbackManagerForChainRun
): Promise<Optional<Task, "taskID">[]> {
const taskNames = this.taskList.map((t) => t.taskName);
const incomplete_tasks = taskNames.join(", ");
const { [this.creationChain.outputKeys[0]]: text } =
await this.creationChain.call(
{
result,
task_description,
incomplete_tasks,
objective,
},
runManager?.getChild()
);
const newTasks = (text as string).split("\n");
return newTasks
.filter((taskName) => taskName.trim())
.map((taskName) => ({ taskName }));
}
/**
* Prioritizes the tasks based on the current task ID and the objective.
* @param thisTaskID The ID of the current task.
* @param objective The objective of the task.
* @param runManager Optional CallbackManagerForChainRun instance.
* @returns Promise resolving to an array of prioritized tasks.
*/
async prioritizeTasks(
thisTaskID: number,
objective: string,
runManager?: CallbackManagerForChainRun
) {
const taskNames = this.taskList.map((t) => t.taskName);
const nextTaskID = thisTaskID + 1;
const { [this.prioritizationChain.outputKeys[0]]: text } =
await this.prioritizationChain.call(
{
task_names: taskNames.join(", "),
next_task_id: String(nextTaskID),
objective,
},
runManager?.getChild()
);
const newTasks = (text as string).trim().split("\n");
const prioritizedTaskList = [];
for (const taskString of newTasks) {
const taskParts = taskString.trim().split(".", 2);
if (taskParts.length === 2) {
const taskID = taskParts[0].trim();
const taskName = taskParts[1].trim();
prioritizedTaskList.push({ taskID, taskName });
}
}
return prioritizedTaskList;
}
/**
* Retrieves the top tasks that are most similar to the given query.
* @param query The query to search for.
* @param k The number of top tasks to retrieve.
* @returns Promise resolving to an array of top tasks.
*/
async getTopTasks(query: string, k = 5) {
const results = await this.vectorstore.similaritySearch(query, k);
if (!results) {
return [];
}
return results.map((item) => String(item.metadata.task));
}
/**
* Executes a task based on the objective and the task description.
* @param objective The objective of the task.
* @param task The task to be executed.
* @param runManager Optional CallbackManagerForChainRun instance.
* @returns Promise resolving to the result of the task execution as a string.
*/
async executeTask(
objective: string,
task: string,
runManager?: CallbackManagerForChainRun
) {
const context = await this.getTopTasks(objective);
const { [this.executionChain.outputKeys[0]]: text } =
await this.executionChain.call(
{
objective,
context: context.join("\n"),
task,
},
runManager?.getChild()
);
return text as string;
}
async _call(
{ objective, firstTask = "Make a todo list" }: ChainValues,
runManager?: CallbackManagerForChainRun
) {
this.taskList = [];
this.taskIDCounter = 1;
await this.addTask({ taskID: "1", taskName: firstTask });
let numIters = 0;
while (numIters < this.maxIterations && this.taskList.length > 0) {
this.printTaskList();
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const task = this.taskList.shift()!;
this.printNextTask(task);
const result = await this.executeTask(
objective,
task.taskName,
runManager
);
const thisTaskID = parseInt(task.taskID, 10);
this.printTaskResult(result);
await this.vectorstore.addDocuments([
new Document({
pageContent: result,
metadata: { task: task.taskName },
}),
]);
const newTasks = await this.getNextTasks(
result,
task.taskName,
objective,
runManager
);
for (const newTask of newTasks) {
this.taskIDCounter += 1;
newTask.taskID = this.taskIDCounter.toFixed();
await this.addTask(newTask as Task);
}
this.taskList = await this.prioritizeTasks(
thisTaskID,
objective,
runManager
);
numIters += 1;
}
return {};
}
serialize(): SerializedBaseChain {
throw new Error("Method not implemented.");
}
/**
* Static method to create a new BabyAGI instance from a
* BaseLanguageModel.
* @param llm BaseLanguageModel instance used to generate a new BabyAGI instance.
* @param vectorstore VectorStore instance used to store and retrieve vectors.
* @param executionChain Optional BaseChain instance used to execute tasks.
* @param verbose Optional boolean indicating whether to log verbose output.
* @param callbacks Optional callbacks to be used during the execution of tasks.
* @param rest Optional additional parameters.
* @returns A new instance of BabyAGI.
*/
static fromLLM({
llm,
vectorstore,
executionChain,
verbose,
callbacks,
...rest
}: Optional<
BabyAGIInputs,
"executionChain" | "creationChain" | "prioritizationChain"
> & { llm: BaseLanguageModelInterface }) {
const creationChain = TaskCreationChain.fromLLM({
llm,
verbose,
callbacks,
});
const prioritizationChain = TaskPrioritizationChain.fromLLM({
llm,
verbose,
callbacks,
});
return new BabyAGI({
creationChain,
prioritizationChain,
executionChain:
executionChain ||
TaskExecutionChain.fromLLM({ llm, verbose, callbacks }),
vectorstore,
verbose,
callbacks,
...rest,
});
}
}