-
Notifications
You must be signed in to change notification settings - Fork 2k
/
prompt.ts
179 lines (161 loc) Β· 5.49 KB
/
prompt.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
import type { VectorStoreRetrieverInterface } from "@langchain/core/vectorstores";
import {
BaseChatPromptTemplate,
SerializedBasePromptTemplate,
} from "@langchain/core/prompts";
import {
BaseMessage,
HumanMessage,
SystemMessage,
} from "@langchain/core/messages";
import { PartialValues } from "@langchain/core/utils/types";
import { getPrompt } from "./prompt_generator.js";
import { ObjectTool } from "./schema.js";
/**
* Interface for the input parameters of the AutoGPTPrompt class.
*/
export interface AutoGPTPromptInput {
aiName: string;
aiRole: string;
tools: ObjectTool[];
tokenCounter: (text: string) => Promise<number>;
sendTokenLimit?: number;
}
/**
* Class used to generate prompts for the AutoGPT model. It takes into
* account the AI's name, role, tools, token counter, and send token
* limit. The class also handles the formatting of messages and the
* construction of the full prompt.
*/
export class AutoGPTPrompt
extends BaseChatPromptTemplate
implements AutoGPTPromptInput
{
aiName: string;
aiRole: string;
tools: ObjectTool[];
tokenCounter: (text: string) => Promise<number>;
sendTokenLimit: number;
constructor(fields: AutoGPTPromptInput) {
super({ inputVariables: ["goals", "memory", "messages", "user_input"] });
this.aiName = fields.aiName;
this.aiRole = fields.aiRole;
this.tools = fields.tools;
this.tokenCounter = fields.tokenCounter;
this.sendTokenLimit = fields.sendTokenLimit || 4196;
}
_getPromptType() {
return "autogpt" as const;
}
/**
* Constructs the full prompt based on the provided goals.
* @param goals An array of goals.
* @returns The full prompt as a string.
*/
constructFullPrompt(goals: string[]): string {
const promptStart = `Your decisions must always be made independently
without seeking user assistance. Play to your strengths
as an LLM and pursue simple strategies with no legal complications.
If you have completed all your tasks,
make sure to use the "finish" command.`;
let fullPrompt = `You are ${this.aiName}, ${this.aiRole}\n${promptStart}\n\nGOALS:\n\n`;
goals.forEach((goal, index) => {
fullPrompt += `${index + 1}. ${goal}\n`;
});
fullPrompt += `\n\n${getPrompt(this.tools)}`;
return fullPrompt;
}
/**
* Formats the messages based on the provided parameters.
* @param goals An array of goals.
* @param memory A VectorStoreRetriever instance.
* @param messages An array of previous messages.
* @param user_input The user's input.
* @returns An array of formatted messages.
*/
async formatMessages({
goals,
memory,
messages: previousMessages,
user_input,
}: {
goals: string[];
memory: VectorStoreRetrieverInterface;
messages: BaseMessage[];
user_input: string;
}) {
const basePrompt = new SystemMessage(this.constructFullPrompt(goals));
const timePrompt = new SystemMessage(
`The current time and date is ${new Date().toLocaleString()}`
);
if (
typeof basePrompt.content !== "string" ||
typeof timePrompt.content !== "string"
) {
throw new Error("Non-string message content is not supported.");
}
const usedTokens =
(await this.tokenCounter(basePrompt.content)) +
(await this.tokenCounter(timePrompt.content));
const relevantDocs = await memory.getRelevantDocuments(
JSON.stringify(previousMessages.slice(-10))
);
const relevantMemory = relevantDocs.map(
(d: { pageContent: string }) => d.pageContent
);
let relevantMemoryTokens = await relevantMemory.reduce(
async (acc: Promise<number>, doc: string) =>
(await acc) + (await this.tokenCounter(doc)),
Promise.resolve(0)
);
while (usedTokens + relevantMemoryTokens > 2500) {
relevantMemory.pop();
relevantMemoryTokens = await relevantMemory.reduce(
async (acc: Promise<number>, doc: string) =>
(await acc) + (await this.tokenCounter(doc)),
Promise.resolve(0)
);
}
const contentFormat = `This reminds you of these events from your past:\n${relevantMemory.join(
"\n"
)}\n\n`;
const memoryMessage = new SystemMessage(contentFormat);
if (typeof memoryMessage.content !== "string") {
throw new Error("Non-string message content is not supported.");
}
const usedTokensWithMemory =
usedTokens + (await this.tokenCounter(memoryMessage.content));
const historicalMessages: BaseMessage[] = [];
for (const message of previousMessages.slice(-10).reverse()) {
if (typeof message.content !== "string") {
throw new Error("Non-string message content is not supported.");
}
const messageTokens = await this.tokenCounter(message.content);
if (usedTokensWithMemory + messageTokens > this.sendTokenLimit - 1000) {
break;
}
historicalMessages.unshift(message);
}
const inputMessage = new HumanMessage(user_input);
const messages: BaseMessage[] = [
basePrompt,
timePrompt,
memoryMessage,
...historicalMessages,
inputMessage,
];
return messages;
}
/**
* This method is not implemented in the AutoGPTPrompt class and will
* throw an error if called.
* @param _values Partial values.
* @returns Throws an error.
*/
async partial(_values: PartialValues): Promise<BaseChatPromptTemplate> {
throw new Error("Method not implemented.");
}
serialize(): SerializedBasePromptTemplate {
throw new Error("Method not implemented.");
}
}