-
Notifications
You must be signed in to change notification settings - Fork 314
/
base.ts
387 lines (339 loc) · 8.96 KB
/
base.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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
import { randomUUID } from "crypto";
import { CallbackManager } from "../../callbacks/CallbackManager.js";
import type { ChatEngineAgentParams } from "../../engines/chat/index.js";
import {
AgentChatResponse,
ChatResponseMode,
StreamingAgentChatResponse,
} from "../../engines/chat/index.js";
import type { ChatMessage, LLM } from "../../llm/index.js";
import { ChatMemoryBuffer } from "../../memory/ChatMemoryBuffer.js";
import type { BaseMemory } from "../../memory/types.js";
import type { AgentWorker, TaskStepOutput } from "../types.js";
import { Task, TaskStep } from "../types.js";
import { AgentState, BaseAgentRunner, TaskState } from "./types.js";
const validateStepFromArgs = (
taskId: string,
input?: string | null,
step?: any,
kwargs?: any,
): TaskStep | undefined => {
if (step) {
if (input) {
throw new Error("Cannot specify both `step` and `input`");
}
return step;
} else {
if (!input) return;
return new TaskStep(taskId, step, input, kwargs);
}
};
type AgentRunnerParams = {
agentWorker: AgentWorker;
chatHistory?: ChatMessage[];
state?: AgentState;
memory?: BaseMemory;
llm?: LLM;
callbackManager?: CallbackManager;
initTaskStateKwargs?: Record<string, any>;
deleteTaskOnFinish?: boolean;
defaultToolChoice?: string;
};
export class AgentRunner extends BaseAgentRunner {
agentWorker: AgentWorker;
state: AgentState;
memory: BaseMemory;
callbackManager: CallbackManager;
initTaskStateKwargs: Record<string, any>;
deleteTaskOnFinish: boolean;
defaultToolChoice: string;
/**
* Creates an AgentRunner.
*/
constructor(params: AgentRunnerParams) {
super();
this.agentWorker = params.agentWorker;
this.state = params.state ?? new AgentState();
this.memory =
params.memory ??
new ChatMemoryBuffer({
chatHistory: params.chatHistory,
});
this.callbackManager = params.callbackManager ?? new CallbackManager();
this.initTaskStateKwargs = params.initTaskStateKwargs ?? {};
this.deleteTaskOnFinish = params.deleteTaskOnFinish ?? false;
this.defaultToolChoice = params.defaultToolChoice ?? "auto";
}
/**
* Creates a task.
* @param input
* @param kwargs
*/
createTask(input: string, kwargs?: any): Task {
let extraState;
if (!this.initTaskStateKwargs) {
if (kwargs && "extraState" in kwargs) {
if (extraState) {
delete extraState["extraState"];
}
}
} else {
if (kwargs && "extraState" in kwargs) {
throw new Error(
"Cannot specify both `extraState` and `initTaskStateKwargs`",
);
} else {
extraState = this.initTaskStateKwargs;
}
}
const task = new Task({
taskId: randomUUID(),
input,
memory: this.memory,
extraState,
...kwargs,
});
const initialStep = this.agentWorker.initializeStep(task);
const taskState = new TaskState({
task,
stepQueue: [initialStep],
});
this.state.taskDict[task.taskId] = taskState;
return task;
}
/**
* Deletes the task.
* @param taskId
*/
deleteTask(taskId: string): void {
delete this.state.taskDict[taskId];
}
/**
* Returns the list of tasks.
*/
listTasks(): Task[] {
return Object.values(this.state.taskDict).map(
(taskState) => taskState.task,
);
}
/**
* Returns the task.
*/
getTask(taskId: string): Task {
return this.state.taskDict[taskId].task;
}
/**
* Returns the completed steps in the task.
* @param taskId
* @param kwargs
*/
getCompletedSteps(taskId: string): TaskStepOutput[] {
return this.state.taskDict[taskId].completedSteps;
}
/**
* Returns the next steps in the task.
* @param taskId
* @param kwargs
*/
getUpcomingSteps(taskId: string, kwargs: any): TaskStep[] {
return this.state.taskDict[taskId].stepQueue;
}
private async _runStep(
taskId: string,
step?: TaskStep,
mode: ChatResponseMode = ChatResponseMode.WAIT,
kwargs?: any,
): Promise<TaskStepOutput> {
const task = this.state.getTask(taskId);
const curStep = step || this.state.getStepQueue(taskId).shift();
let curStepOutput;
if (!curStep) {
throw new Error(`No step found for task ${taskId}`);
}
if (mode === ChatResponseMode.WAIT) {
curStepOutput = await this.agentWorker.runStep(curStep, task, kwargs);
} else if (mode === ChatResponseMode.STREAM) {
curStepOutput = await this.agentWorker.streamStep(curStep, task, kwargs);
} else {
throw new Error(`Invalid mode: ${mode}`);
}
const nextSteps = curStepOutput.nextSteps;
this.state.addSteps(taskId, nextSteps);
this.state.addCompletedStep(taskId, [curStepOutput]);
return curStepOutput;
}
/**
* Runs the next step in the task.
* @param taskId
* @param kwargs
* @param step
* @returns
*/
async runStep(
taskId: string,
input?: string | null,
step?: TaskStep,
kwargs: any = {},
): Promise<TaskStepOutput> {
const curStep = validateStepFromArgs(taskId, input, step, kwargs);
return this._runStep(taskId, curStep, ChatResponseMode.WAIT, kwargs);
}
/**
* Runs the step and returns the response.
* @param taskId
* @param input
* @param step
* @param kwargs
*/
async streamStep(
taskId: string,
input: string,
step?: TaskStep,
kwargs?: any,
): Promise<TaskStepOutput> {
const curStep = validateStepFromArgs(taskId, input, step, kwargs);
return this._runStep(taskId, curStep, ChatResponseMode.STREAM, kwargs);
}
/**
* Finalizes the response and returns it.
* @param taskId
* @param kwargs
* @param stepOutput
* @returns
*/
async finalizeResponse(
taskId: string,
stepOutput: TaskStepOutput,
kwargs?: any,
): Promise<AgentChatResponse | StreamingAgentChatResponse> {
if (!stepOutput) {
stepOutput =
this.getCompletedSteps(taskId)[
this.getCompletedSteps(taskId).length - 1
];
}
if (!stepOutput.isLast) {
throw new Error(
"finalizeResponse can only be called on the last step output",
);
}
if (!(stepOutput.output instanceof StreamingAgentChatResponse)) {
if (!(stepOutput.output instanceof AgentChatResponse)) {
throw new Error(
`When \`isLast\` is True, cur_step_output.output must be AGENT_CHAT_RESPONSE_TYPE: ${stepOutput.output}`,
);
}
}
this.agentWorker.finalizeTask(this.getTask(taskId), kwargs);
if (this.deleteTaskOnFinish) {
this.deleteTask(taskId);
}
return stepOutput.output;
}
protected async _chat({
message,
toolChoice,
stream,
}: ChatEngineAgentParams): Promise<AgentChatResponse>;
protected async _chat({
message,
toolChoice,
stream,
}: ChatEngineAgentParams & {
stream: true;
}): Promise<StreamingAgentChatResponse>;
protected async _chat({
message,
toolChoice,
stream,
}: ChatEngineAgentParams): Promise<
AgentChatResponse | StreamingAgentChatResponse
> {
const task = this.createTask(message as string);
let resultOutput;
const mode = stream ? ChatResponseMode.STREAM : ChatResponseMode.WAIT;
while (true) {
const curStepOutput = await this._runStep(task.taskId, undefined, mode, {
toolChoice,
});
if (curStepOutput.isLast) {
resultOutput = curStepOutput;
break;
}
toolChoice = "auto";
}
return this.finalizeResponse(task.taskId, resultOutput);
}
/**
* Sends a message to the LLM and returns the response.
* @param message
* @param chatHistory
* @param toolChoice
* @returns
*/
public async chat({
message,
chatHistory,
toolChoice,
stream,
}: ChatEngineAgentParams & {
stream?: false;
}): Promise<AgentChatResponse>;
public async chat({
message,
chatHistory,
toolChoice,
stream,
}: ChatEngineAgentParams & {
stream: true;
}): Promise<StreamingAgentChatResponse>;
public async chat({
message,
chatHistory,
toolChoice,
stream,
}: ChatEngineAgentParams): Promise<
AgentChatResponse | StreamingAgentChatResponse
> {
if (!toolChoice) {
toolChoice = this.defaultToolChoice;
}
const chatResponse = await this._chat({
message,
chatHistory,
toolChoice,
stream,
});
return chatResponse;
}
protected _getPromptModules(): string[] {
return [];
}
protected _getPrompts(): string[] {
return [];
}
/**
* Resets the agent.
*/
reset(): void {
this.state = new AgentState();
}
getCompletedStep(
taskId: string,
stepId: string,
kwargs: any,
): TaskStepOutput {
const completedSteps = this.getCompletedSteps(taskId);
for (const stepOutput of completedSteps) {
if (stepOutput.taskStep.stepId === stepId) {
return stepOutput;
}
}
throw new Error(`Step ${stepId} not found in task ${taskId}`);
}
/**
* Undoes the step.
* @param taskId
*/
undoStep(taskId: string): void {}
}