-
Notifications
You must be signed in to change notification settings - Fork 0
/
llm.ts
280 lines (263 loc) · 7.93 KB
/
llm.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
import { state, nodes } from "membrane";
import { Tool, toToolName } from "./schemaUtils";
import { extractParams, transformJSON } from "./utils";
const TEMPERATURE: number = 0.4;
interface ChatMessage {
role: string;
content: string;
name?: string;
tool_call_id?: string;
tool_calls?: any[];
}
export type OpenAITool = {
type: string;
function: {
name: string;
description: string;
parameters: Record<string, any>;
};
};
export const BUILT_IN_TOOLS: OpenAITool[] = [
{
type: "function",
function: {
name: "completeSubtasks",
description:
"This tool must be used to mark subtasks as done. If refreshTools is true, the available tools list will be refreshed based on the next subtask.",
parameters: {
type: "object",
properties: {
subtaskIds: {
type: "array",
items: { type: "number" },
},
refreshTools: {
type: "boolean",
},
},
required: ["subtaskIds", "refreshTools"],
},
},
},
{
type: "function",
function: {
name: "completeTask",
description:
'This tool must be used when the task is done or no more progress can be made. The result argument is the final message to the user in markdown. Any relevant grefs should be passed to the user in the message using markdown link syntax. e.g. "This is [the final result](gref here)" so that they can see what was done',
parameters: {
type: "object",
properties: {
result: {
type: "string",
},
error: {
type: "string",
},
},
required: ["result"],
},
},
},
{
type: "function",
function: {
name: "addSubtasks",
description: "This tool must be used to add subtasks to the current task",
parameters: {
type: "object",
properties: {
subtasks: {
type: "array",
items: { type: "string" },
},
},
required: ["subtasks"],
},
},
},
{
type: "function",
function: {
name: "ask",
description:
'Ask the user a question. Can be used to clarify tool arguments, subtasks or the main task. The question argument must use markdown format. Relevant gref to nodes can be passed if needed using markdown link syntax. e.g. "Is [this thing](gref here) what you were referring to? I need to know to complete the task".',
parameters: {
type: "object",
properties: {
question: {
type: "string",
},
},
required: ["question"],
},
},
},
{
type: "function",
function: {
name: "tell",
description:
'Tell the user something without expecting a response. Can be used to indicate nodes to the user using their gref. The message argument must use markdown format. Relevant gref to nodes can be passed if needed using markdown link syntax. e.g. "I tried using [the record](gref here) but it did not work. I\'ll continue with...".',
parameters: {
type: "object",
properties: {
message: {
type: "string",
},
},
required: ["message"],
},
},
},
{
type: "function",
function: {
name: "sleep",
description:
"Wait for a number of seconds before continuing. Only one sleep can be invoked at a time.",
parameters: {
type: "object",
properties: {
seconds: {
type: "number",
},
},
required: ["seconds"],
},
},
},
{
type: "function",
function: {
name: "requestTools",
description:
"Request different tools than the ones provided. The description argument try to match the description of the desired tool. Examples: get values from a github repository, list calendars from Google Calendar, get weather by location.",
parameters: {
type: "object",
properties: {
description: {
type: "string",
},
},
required: ["description"],
},
},
},
{
type: "function",
function: {
name: "fetch",
description:
"Perform an HTTP GET request. Generally you should try to use more specific tools and use this as a last resort",
parameters: {
type: "object",
properties: {
url: {
type: "string",
},
},
required: ["url"],
},
},
},
];
export class LLM {
tools: OpenAITool[];
messages: ChatMessage[];
constructor(systemPrompt: string, availableTools: Tool[] = []) {
this.messages = [];
if (systemPrompt) {
this.messages.push({ role: "system", content: systemPrompt });
}
this.updateTools(availableTools);
}
updateTools(availableTools: Tool[]) {
// Pre-defined system tools are always available
this.tools = [...BUILT_IN_TOOLS];
// Convert tools to OpenAI format
for (const tool of availableTools) {
const ref = tool.metadata.ref;
let id = tool.id;
const actionObj = {
type: "function",
function: {
name: toToolName(id),
description: tool.metadata.description,
parameters: transformJSON(extractParams(ref), tool.metadata),
},
};
this.tools.push(actionObj);
}
}
async execute(ignoreTools: boolean): Promise<any> {
const result = await nodes.openai.models
.one({ id: state.modelName ?? "gpt-4-1106-preview" })
.completeChat({
temperature: TEMPERATURE,
messages: this.messages,
tools: ignoreTools ? undefined : this.tools,
max_tokens: 3500,
});
// HACK: sometimes OpenAI will incorrectly return incorrect tool invocations so here we try to catch and fix them
if (result.tool_calls) {
for (let tool_call of result.tool_calls) {
// Sometimes it will incorrectly return a "functions." prefix
if (tool_call.function?.name.startsWith("function.")) {
tool_call.function.name = tool_call.function.name.replace(
"function.",
""
);
}
// Sometimes it incorrectly returns dots instead of underscores
if (tool_call.function?.name.includes(".")) {
tool_call.function.name = tool_call.function.name.replace(".", "_");
}
}
}
this.messages.push(result);
return result;
}
appendUserMessage(message: string) {
this.messages.push({ role: "user", content: message });
}
appendToolResult(message: string, name: string, tool_call_id: string) {
this.messages.push({ role: "tool", content: message, name, tool_call_id });
}
appendAssistantMesssage(message: string, tool_calls: any[]) {
this.messages.push({ role: "assistant", content: message, tool_calls });
}
lastMessage(): ChatMessage {
return this.messages[this.messages.length - 1];
}
// Checks if the last two tool calls are equal
isRepeatingTools(): boolean {
let lastTool: ChatMessage | undefined;
for (let i = this.messages.length - 1; i >= 0; i--) {
const message = this.messages[i];
if (message.role === "assistant" && message.tool_calls) {
if (!lastTool) {
lastTool = message;
} else {
const names1 = message.tool_calls?.map(
(tool_call) => tool_call.function.name
);
const arguments1 = message.tool_calls?.map(
(tool_call) => tool_call.function.arguments
);
const names2 = lastTool.tool_calls!.map(
(tool_call) => tool_call.function.name
);
const arguments2 = lastTool.tool_calls!.map(
(tool_call) => tool_call.function.arguments
);
return (
names1?.every((name, index) => name === names2![index]) &&
arguments1?.every((arg, index) => arg === arguments2![index])
);
}
}
}
return false;
}
}