forked from unconv/gpt4v-browsing
-
Notifications
You must be signed in to change notification settings - Fork 123
/
web_agent.js
316 lines (254 loc) · 10.1 KB
/
web_agent.js
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
const puppeteer = require('puppeteer-extra');
const StealthPlugin = require('puppeteer-extra-plugin-stealth');
const OpenAI = require('openai');
const readline = require('readline');
const fs = require('fs');
require('dotenv/config');
puppeteer.use(StealthPlugin());
const openai = new OpenAI();
const timeout = 5000;
async function image_to_base64(image_file) {
return await new Promise((resolve, reject) => {
fs.readFile(image_file, (err, data) => {
if (err) {
console.error('Error reading the file:', err);
reject();
return;
}
const base64Data = data.toString('base64');
const dataURI = `data:image/jpeg;base64,${base64Data}`;
resolve(dataURI);
});
});
}
async function input( text ) {
let the_prompt;
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
await (async () => {
return new Promise( resolve => {
rl.question( text, (prompt) => {
the_prompt = prompt;
rl.close();
resolve();
} );
} );
})();
return the_prompt;
}
async function sleep( milliseconds ) {
return await new Promise((r, _) => {
setTimeout( () => {
r();
}, milliseconds );
});
}
async function highlight_links( page ) {
await page.evaluate(() => {
document.querySelectorAll('[gpt-link-text]').forEach(e => {
e.removeAttribute("gpt-link-text");
});
});
const elements = await page.$$(
"a, button, input, textarea, [role=button], [role=treeitem]"
);
elements.forEach( async e => {
await page.evaluate(e => {
function isElementVisible(el) {
if (!el) return false; // Element does not exist
function isStyleVisible(el) {
const style = window.getComputedStyle(el);
return style.width !== '0' &&
style.height !== '0' &&
style.opacity !== '0' &&
style.display !== 'none' &&
style.visibility !== 'hidden';
}
function isElementInViewport(el) {
const rect = el.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
rect.right <= (window.innerWidth || document.documentElement.clientWidth)
);
}
// Check if the element is visible style-wise
if (!isStyleVisible(el)) {
return false;
}
// Traverse up the DOM and check if any ancestor element is hidden
let parent = el;
while (parent) {
if (!isStyleVisible(parent)) {
return false;
}
parent = parent.parentElement;
}
// Finally, check if the element is within the viewport
return isElementInViewport(el);
}
e.style.border = "1px solid red";
const position = e.getBoundingClientRect();
if( position.width > 5 && position.height > 5 && isElementVisible(e) ) {
const link_text = e.textContent.replace(/[^a-zA-Z0-9 ]/g, '');
e.setAttribute( "gpt-link-text", link_text );
}
}, e);
} );
}
async function waitForEvent(page, event) {
return page.evaluate(event => {
return new Promise((r, _) => {
document.addEventListener(event, function(e) {
r();
});
});
}, event)
}
(async () => {
console.log( "###########################################" );
console.log( "# GPT4V-Browsing by Unconventional Coding #" );
console.log( "###########################################\n" );
const browser = await puppeteer.launch( {
headless: "false",
executablePath: '/Applications/Google\ Chrome\ Canary.app/Contents/MacOS/Google\ Chrome\ Canary',
userDataDir: '/Users/jasonzhou/Library/Application\ Support/Google/Chrome\ Canary/Default',
} );
const page = await browser.newPage();
await page.setViewport( {
width: 1200,
height: 1200,
deviceScaleFactor: 1,
} );
const messages = [
{
"role": "system",
"content": `You are a website crawler. You will be given instructions on what to do by browsing. You are connected to a web browser and you will be given the screenshot of the website you are on. The links on the website will be highlighted in red in the screenshot. Always read what is in the screenshot. Don't guess link names.
You can go to a specific URL by answering with the following JSON format:
{"url": "url goes here"}
You can click links on the website by referencing the text inside of the link/button, by answering in the following JSON format:
{"click": "Text in link"}
Once you are on a URL and you have found the answer to the user's question, you can answer with a regular message.
Use google search by set a sub-page like 'https://google.com/search?q=search' if applicable. Prefer to use Google for simple queries. If the user provides a direct URL, go to that one. Do not make up links`,
}
];
console.log("GPT: How can I assist you today?")
const prompt = await input("You: ");
console.log();
messages.push({
"role": "user",
"content": prompt,
});
let url;
let screenshot_taken = false;
while( true ) {
if( url ) {
console.log("Crawling " + url);
await page.goto( url, {
waitUntil: "domcontentloaded",
timeout: timeout,
} );
await Promise.race( [
waitForEvent(page, 'load'),
sleep(timeout)
] );
await highlight_links( page );
await page.screenshot( {
path: "screenshot.jpg",
fullPage: true,
} );
screenshot_taken = true;
url = null;
}
if( screenshot_taken ) {
const base64_image = await image_to_base64("screenshot.jpg");
messages.push({
"role": "user",
"content": [
{
"type": "image_url",
"image_url": base64_image,
},
{
"type": "text",
"text": "Here's the screenshot of the website you are on right now. You can click on links with {\"click\": \"Link text\"} or you can crawl to another URL if this one is incorrect. If you find the answer to the user's question, you can respond normally.",
}
]
});
screenshot_taken = false;
}
const response = await openai.chat.completions.create({
model: "gpt-4-vision-preview",
max_tokens: 1024,
messages: messages,
});
const message = response.choices[0].message;
const message_text = message.content;
messages.push({
"role": "assistant",
"content": message_text,
});
console.log( "GPT: " + message_text );
if (message_text.indexOf('{"click": "') !== -1) {
let parts = message_text.split('{"click": "');
parts = parts[1].split('"}');
const link_text = parts[0].replace(/[^a-zA-Z0-9 ]/g, '');
console.log("Clicking on " + link_text)
try {
const elements = await page.$$('[gpt-link-text]');
let partial;
let exact;
for (const element of elements) {
const attributeValue = await element.evaluate(el => el.getAttribute('gpt-link-text'));
if (attributeValue.includes(link_text)) {
partial = element;
}
if (attributeValue === link_text) {
exact = element;
}
}
if (exact || partial) {
const [response] = await Promise.all([
page.waitForNavigation({ waitUntil: 'domcontentloaded' }).catch(e => console.log("Navigation timeout/error:", e.message)),
(exact || partial).click()
]);
// Additional checks can be done here, like validating the response or URL
await Promise.race( [
waitForEvent(page, 'load'),
sleep(timeout)
] );
await highlight_links(page);
await page.screenshot({
path: "screenshot.jpg",
quality: 100,
fullpage: true
});
screenshot_taken = true;
} else {
throw new Error("Can't find link");
}
} catch (error) {
console.log("ERROR: Clicking failed", error);
messages.push({
"role": "user",
"content": "ERROR: I was unable to click that element",
});
}
continue;
} else if (message_text.indexOf('{"url": "') !== -1) {
let parts = message_text.split('{"url": "');
parts = parts[1].split('"}');
url = parts[0];
continue;
}
const prompt = await input("You: ");
console.log();
messages.push({
"role": "user",
"content": prompt,
});
}
})();