-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathchat.ts
More file actions
258 lines (237 loc) · 6.66 KB
/
chat.ts
File metadata and controls
258 lines (237 loc) · 6.66 KB
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
import fs from 'fs'
import { isInArray, round } from './utils'
import { StartResearchContext, StartResearchOptions } from './type'
import { getTotalTokenCost } from './token'
export function makeRedactedMessages(messages: Record<string, any>[], debug) {
const redacted_messages = []
const currentUrl = messages[messages.length - 1].url
messages.forEach((message) => {
let msg = JSON.parse(JSON.stringify(message))
if (msg.url != currentUrl) {
// msg.content = msg.redacted ?? msg.content ?? "";
}
delete msg.redacted
delete msg.url
redacted_messages.push(msg)
})
if (debug) {
fs.writeFileSync(
'context_redacted' + redacted_messages.length + '.json',
JSON.stringify(redacted_messages, null, 2)
)
}
return redacted_messages
}
export async function sendChatMessage({
message,
aiContext,
functionCall = 'auto',
functions = null,
options,
context
}: {
message: {
role: string
content: string
}
aiContext: Record<string, any>[]
functionCall?:
| string
| {
name: string
arguments: string[]
}
functions?: any
options: StartResearchOptions
context: StartResearchContext
}) {
let messages = [...aiContext]
messages.push(message)
if (options.debug) {
fs.writeFileSync('context.json', JSON.stringify(messages, null, 2))
}
let definitions = [
{
name: 'make_plan',
description:
"Create a plan to accomplish the given task. Summarize what the user's task is in a step by step manner. How would you browse the internet to accomplish the task. Start with 'I will'",
parameters: {
type: 'object',
properties: {
plan: {
type: 'string',
description:
'The step by step plan on how you will navigate the internet and what you will do'
}
}
},
required: ['plan']
},
{
name: 'read_file',
description:
'Read the contents of a file that the user has provided to you',
parameters: {
type: 'object',
properties: {
filename: {
type: 'string',
description:
'The filename to read, e.g. file.txt or path/to/file.txt'
}
}
},
required: ['filename']
},
{
name: 'goto_url',
description: 'Goes to a specific URL and gets the content',
parameters: {
type: 'object',
properties: {
url: {
type: 'string',
description: 'The URL to go to (including protocol)'
}
}
},
required: ['url']
},
{
name: 'click_link',
description:
'Clicks a link with the given pgpt_id on the page. Note that pgpt_id is required and you must use the corresponding pgpt-id attribute from the page content. Add the text of the link to confirm that you are clicking the right link.',
parameters: {
type: 'object',
properties: {
text: {
type: 'string',
description: 'The text on the link you want to click'
},
pgpt_id: {
type: 'number',
description:
'The pgpt-id of the link to click (from the page content)'
}
}
},
required: ['reason', 'pgpt_id']
},
{
name: 'type_text',
description: 'Types text to input fields and optionally submit the form',
parameters: {
type: 'object',
properties: {
form_data: {
type: 'array',
items: {
type: 'object',
properties: {
pgpt_id: {
type: 'number',
description:
'The pgpt-id attribute of the input to type into (from the page content)'
},
text: {
type: 'string',
description: 'The text to type'
}
}
}
},
submit: {
type: 'boolean',
description: 'Whether to submit the form after filling the fields'
}
}
},
required: ['form_data', 'submit']
},
{
name: 'answer_user',
description:
'Give an answer to the user and end the navigation. Use when the given task has been completed. Summarize the relevant parts of the page content first and give an answer to the user based on that.',
parameters: {
type: 'object',
properties: {
summary: {
type: 'string',
description:
'A summary of the relevant parts of the page content that you base the answer on'
},
answer: {
type: 'string',
description: 'The response to the user'
}
}
},
required: ['summary', 'answer']
}
]
if (functions !== null) {
definitions = definitions.filter((definition) => {
return isInArray(definition.name, functions)
})
}
options.logger(options.taskPrefix + 'Sending ChatGPT request...')
const response = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${options.openaiApiKey}`
},
body: JSON.stringify({
model: options.model,
messages: makeRedactedMessages(messages, options.debug),
functions: definitions,
function_call: functionCall ?? 'auto'
})
}).catch(function (e) {
options.logger(e)
})
if (!response) {
options.logger('ERROR: No response from OpenAI API')
process.exit(1)
}
const data = await response.json()
if (data.choices === undefined) {
options.logger(data)
}
// * Fix JSON arguments
if (data.choices[0].message.hasOwnProperty('function_call')) {
data.choices[0].message.function_call.arguments =
data.choices[0].message.function_call.arguments.replace(
'"\n "',
'",\n "'
)
}
context.tokenUsage.completion_tokens += data.usage.completion_tokens
context.tokenUsage.prompt_tokens += data.usage.prompt_tokens
context.tokenUsage.total_tokens += data.usage.total_tokens
let cost = getTotalTokenCost(
data.usage.prompt_tokens,
data.usage.completion_tokens,
options.model
)
if (cost > 0.09) {
options.logger(
'Cost: +' +
round(cost, 2) +
' USD (+' +
data.usage.total_tokens +
' tokens)'
)
}
if (options.autopilot) {
options.logger(
'<!_TOKENS_!>' +
data.usage.prompt_tokens +
' ' +
data.usage.completion_tokens +
' ' +
data.usage.total_tokens
)
}
return data.choices[0].message
}