-
Notifications
You must be signed in to change notification settings - Fork 2k
/
agent.ts
225 lines (204 loc) Β· 6.73 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
import type { VectorStoreRetrieverInterface } from "@langchain/core/vectorstores";
import { Tool } from "@langchain/core/tools";
import {
AIMessage,
BaseMessage,
HumanMessage,
SystemMessage,
} from "@langchain/core/messages";
import { BaseChatModel } from "@langchain/core/language_models/chat_models";
import {
getEmbeddingContextSize,
getModelContextSize,
} from "@langchain/core/language_models/base";
import { LLMChain } from "../../chains/llm_chain.js";
import { AutoGPTOutputParser } from "./output_parser.js";
import { AutoGPTPrompt } from "./prompt.js";
// import { HumanInputRun } from "./tools/human/tool"; // TODO
import { ObjectTool, FINISH_NAME } from "./schema.js";
import { TokenTextSplitter } from "../../text_splitter.js";
/**
* Interface for the input parameters of the AutoGPT class.
*/
export interface AutoGPTInput {
aiName: string;
aiRole: string;
memory: VectorStoreRetrieverInterface;
humanInTheLoop?: boolean;
outputParser?: AutoGPTOutputParser;
maxIterations?: number;
}
/**
* Class representing the AutoGPT concept with LangChain primitives. It is
* designed to be used with a set of tools such as a search tool,
* write-file tool, and a read-file tool.
* @example
* ```typescript
* const autogpt = AutoGPT.fromLLMAndTools(
* new ChatOpenAI({ temperature: 0 }),
* [
* new ReadFileTool({ store: new InMemoryFileStore() }),
* new WriteFileTool({ store: new InMemoryFileStore() }),
* new SerpAPI("YOUR_SERPAPI_API_KEY", {
* location: "San Francisco,California,United States",
* hl: "en",
* gl: "us",
* }),
* ],
* {
* memory: new MemoryVectorStore(new OpenAIEmbeddings()).asRetriever(),
* aiName: "Tom",
* aiRole: "Assistant",
* },
* );
* const result = await autogpt.run(["write a weather report for SF today"]);
* ```
*/
export class AutoGPT {
aiName: string;
memory: VectorStoreRetrieverInterface;
fullMessageHistory: BaseMessage[];
nextActionCount: number;
chain: LLMChain;
outputParser: AutoGPTOutputParser;
tools: ObjectTool[];
feedbackTool?: Tool;
maxIterations: number;
// Currently not generic enough to support any text splitter.
textSplitter: TokenTextSplitter;
constructor({
aiName,
memory,
chain,
outputParser,
tools,
feedbackTool,
maxIterations,
}: Omit<Required<AutoGPTInput>, "aiRole" | "humanInTheLoop"> & {
chain: LLMChain;
tools: ObjectTool[];
feedbackTool?: Tool;
}) {
this.aiName = aiName;
this.memory = memory;
this.fullMessageHistory = [];
this.nextActionCount = 0;
this.chain = chain;
this.outputParser = outputParser;
this.tools = tools;
this.feedbackTool = feedbackTool;
this.maxIterations = maxIterations;
const chunkSize = getEmbeddingContextSize(
"modelName" in memory.vectorStore.embeddings
? (memory.vectorStore.embeddings.modelName as string)
: undefined
);
this.textSplitter = new TokenTextSplitter({
chunkSize,
chunkOverlap: Math.round(chunkSize / 10),
});
}
/**
* Creates a new AutoGPT instance from a given LLM and a set of tools.
* @param llm A BaseChatModel object.
* @param tools An array of ObjectTool objects.
* @param options.aiName The name of the AI.
* @param options.aiRole The role of the AI.
* @param options.memory A VectorStoreRetriever object that represents the memory of the AI.
* @param options.maxIterations The maximum number of iterations the AI can perform.
* @param options.outputParser An AutoGPTOutputParser object that parses the output of the AI.
* @returns A new instance of the AutoGPT class.
*/
static fromLLMAndTools(
llm: BaseChatModel,
tools: ObjectTool[],
{
aiName,
aiRole,
memory,
maxIterations = 100,
// humanInTheLoop = false,
outputParser = new AutoGPTOutputParser(),
}: AutoGPTInput
): AutoGPT {
const prompt = new AutoGPTPrompt({
aiName,
aiRole,
tools,
tokenCounter: llm.getNumTokens.bind(llm),
sendTokenLimit: getModelContextSize(
"modelName" in llm ? (llm.modelName as string) : "gpt2"
),
});
// const feedbackTool = humanInTheLoop ? new HumanInputRun() : null;
const chain = new LLMChain({ llm, prompt });
return new AutoGPT({
aiName,
memory,
chain,
outputParser,
tools,
// feedbackTool,
maxIterations,
});
}
/**
* Runs the AI with a given set of goals.
* @param goals An array of strings representing the goals.
* @returns A string representing the result of the run or undefined if the maximum number of iterations is reached without a result.
*/
async run(goals: string[]): Promise<string | undefined> {
const user_input =
"Determine which next command to use, and respond using the format specified above:";
let loopCount = 0;
while (loopCount < this.maxIterations) {
loopCount += 1;
const { text: assistantReply } = await this.chain.call({
goals,
user_input,
memory: this.memory,
messages: this.fullMessageHistory,
});
// Print the assistant reply
console.log(assistantReply);
this.fullMessageHistory.push(new HumanMessage(user_input));
this.fullMessageHistory.push(new AIMessage(assistantReply));
const action = await this.outputParser.parse(assistantReply);
const tools = this.tools.reduce(
(acc, tool) => ({ ...acc, [tool.name]: tool }),
{} as { [key: string]: ObjectTool }
);
if (action.name === FINISH_NAME) {
return action.args.response;
}
let result: string;
if (action.name in tools) {
const tool = tools[action.name];
let observation;
try {
observation = await tool.call(action.args);
} catch (e) {
observation = `Error in args: ${e}`;
}
result = `Command ${tool.name} returned: ${observation}`;
} else if (action.name === "ERROR") {
result = `Error: ${action.args}. `;
} else {
result = `Unknown command '${action.name}'. Please refer to the 'COMMANDS' list for available commands and only respond in the specified JSON format.`;
}
let memoryToAdd = `Assistant Reply: ${assistantReply}\nResult: ${result} `;
if (this.feedbackTool) {
const feedback = `\n${await this.feedbackTool.call("Input: ")}`;
if (feedback === "q" || feedback === "stop") {
console.log("EXITING");
return "EXITING";
}
memoryToAdd += feedback;
}
const documents = await this.textSplitter.createDocuments([memoryToAdd]);
await this.memory.addDocuments(documents);
this.fullMessageHistory.push(new SystemMessage(result));
}
return undefined;
}
}