-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathapis.py
804 lines (667 loc) · 27.4 KB
/
apis.py
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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
import os
import time
import json
import base64
import traceback
import io
import easyocr
import ollama
from PIL import Image
from ultralytics import YOLO
from operate.config import Config
from operate.exceptions import ModelNotRecognizedException
from operate.utils.screenshot import (
capture_screen_with_cursor,
)
from operate.models.prompts import (
get_user_first_message_prompt,
get_user_prompt,
get_system_prompt,
)
from operate.utils.ocr import get_text_element, get_text_coordinates
from operate.utils.label import (
add_labels,
get_click_position_in_percent,
get_label_coordinates,
)
from operate.utils.style import ANSI_GREEN, ANSI_RED, ANSI_RESET, ANSI_BRIGHT_MAGENTA
import pkg_resources
# Load configuration
config = Config()
async def get_next_action(model, messages, objective, session_id):
if config.verbose:
print("[Self-Operating Computer][get_next_action]")
print("[Self-Operating Computer][get_next_action] model", model)
if model == "gpt-4":
return call_gpt_4o(messages), None
if model == "gpt-4-with-som":
operation = await call_gpt_4o_labeled(messages, objective, model)
return operation, None
if model == "gpt-4-with-ocr":
operation = await call_gpt_4o_with_ocr(messages, objective, model)
return operation, None
if model == "agent-1":
return "coming soon"
if model == "gemini-pro-vision":
return call_gemini_pro_vision(messages, objective), None
if model == "llava":
operation = call_ollama_llava(messages)
return operation, None
if model == "claude-3":
operation = await call_claude_3_with_ocr(messages, objective, model)
return operation, None
raise ModelNotRecognizedException(model)
def call_gpt_4o(messages):
if config.verbose:
print("[call_gpt_4_v]")
time.sleep(1)
client = config.initialize_openai()
try:
screenshots_dir = "screenshots"
if not os.path.exists(screenshots_dir):
os.makedirs(screenshots_dir)
screenshot_filename = os.path.join(screenshots_dir, "screenshot.png")
# Call the function to capture the screen with the cursor
capture_screen_with_cursor(screenshot_filename)
with open(screenshot_filename, "rb") as img_file:
img_base64 = base64.b64encode(img_file.read()).decode("utf-8")
if len(messages) == 1:
user_prompt = get_user_first_message_prompt()
else:
user_prompt = get_user_prompt()
if config.verbose:
print(
"[call_gpt_4_v] user_prompt",
user_prompt,
)
vision_message = {
"role": "user",
"content": [
{"type": "text", "text": user_prompt},
{
"type": "image_url",
"image_url": {"url": f"data:image/jpeg;base64,{img_base64}"},
},
],
}
messages.append(vision_message)
response = client.chat.completions.create(
model="gpt-4o",
messages=messages,
presence_penalty=1,
frequency_penalty=1,
temperature=0.7,
max_tokens=3000,
)
content = response.choices[0].message.content
content = clean_json(content)
assistant_message = {"role": "assistant", "content": content}
if config.verbose:
print(
"[call_gpt_4_v] content",
content,
)
content = json.loads(content)
messages.append(assistant_message)
return content
except Exception as e:
print(
f"{ANSI_GREEN}[Self-Operating Computer]{ANSI_BRIGHT_MAGENTA}[Operate] That did not work. Trying again {ANSI_RESET}",
e,
)
print(
f"{ANSI_GREEN}[Self-Operating Computer]{ANSI_RED}[Error] AI response was {ANSI_RESET}",
content,
)
if config.verbose:
traceback.print_exc()
return call_gpt_4o(messages)
def call_gemini_pro_vision(messages, objective):
"""
Get the next action for Self-Operating Computer using Gemini Pro Vision
"""
if config.verbose:
print(
"[Self Operating Computer][call_gemini_pro_vision]",
)
# sleep for a second
time.sleep(1)
try:
screenshots_dir = "screenshots"
if not os.path.exists(screenshots_dir):
os.makedirs(screenshots_dir)
screenshot_filename = os.path.join(screenshots_dir, "screenshot.png")
# Call the function to capture the screen with the cursor
capture_screen_with_cursor(screenshot_filename)
# sleep for a second
time.sleep(1)
prompt = get_system_prompt("gemini-pro-vision", objective)
model = config.initialize_google()
if config.verbose:
print("[call_gemini_pro_vision] model", model)
response = model.generate_content([prompt, Image.open(screenshot_filename)])
content = response.text[1:]
if config.verbose:
print("[call_gemini_pro_vision] response", response)
print("[call_gemini_pro_vision] content", content)
content = json.loads(content)
if config.verbose:
print(
"[get_next_action][call_gemini_pro_vision] content",
content,
)
return content
except Exception as e:
print(
f"{ANSI_GREEN}[Self-Operating Computer]{ANSI_BRIGHT_MAGENTA}[Operate] That did not work. Trying another method {ANSI_RESET}"
)
if config.verbose:
print("[Self-Operating Computer][Operate] error", e)
traceback.print_exc()
return call_gpt_4o(messages)
async def call_gpt_4o_with_ocr(messages, objective, model):
if config.verbose:
print("[call_gpt_4o_with_ocr]")
# Construct the path to the file within the package
try:
time.sleep(1)
client = config.initialize_openai()
confirm_system_prompt(messages, objective, model)
screenshots_dir = "screenshots"
if not os.path.exists(screenshots_dir):
os.makedirs(screenshots_dir)
screenshot_filename = os.path.join(screenshots_dir, "screenshot.png")
# Call the function to capture the screen with the cursor
capture_screen_with_cursor(screenshot_filename)
with open(screenshot_filename, "rb") as img_file:
img_base64 = base64.b64encode(img_file.read()).decode("utf-8")
if len(messages) == 1:
user_prompt = get_user_first_message_prompt()
else:
user_prompt = get_user_prompt()
vision_message = {
"role": "user",
"content": [
{"type": "text", "text": user_prompt},
{
"type": "image_url",
"image_url": {"url": f"data:image/jpeg;base64,{img_base64}"},
},
],
}
messages.append(vision_message)
response = client.chat.completions.create(
model="gpt-4o",
messages=messages,
temperature=0.7,
max_tokens=3000,
)
content = response.choices[0].message.content
content = clean_json(content)
# used later for the messages
content_str = content
content = json.loads(content)
processed_content = []
for operation in content:
if operation.get("operation") == "click":
text_to_click = operation.get("text")
if config.verbose:
print(
"[call_gpt_4o_with_ocr][click] text_to_click",
text_to_click,
)
# Initialize EasyOCR Reader
reader = easyocr.Reader(["en"])
# Read the screenshot
result = reader.readtext(screenshot_filename)
text_element_index = get_text_element(
result, text_to_click, screenshot_filename
)
coordinates = get_text_coordinates(
result, text_element_index, screenshot_filename
)
# add `coordinates`` to `content`
operation["x"] = coordinates["x"]
operation["y"] = coordinates["y"]
if config.verbose:
print(
"[call_gpt_4o_with_ocr][click] text_element_index",
text_element_index,
)
print(
"[call_gpt_4o_with_ocr][click] coordinates",
coordinates,
)
print(
"[call_gpt_4o_with_ocr][click] final operation",
operation,
)
processed_content.append(operation)
else:
processed_content.append(operation)
# wait to append the assistant message so that if the `processed_content` step fails we don't append a message and mess up message history
assistant_message = {"role": "assistant", "content": content_str}
messages.append(assistant_message)
return processed_content
except Exception as e:
print(
f"{ANSI_GREEN}[Self-Operating Computer]{ANSI_BRIGHT_MAGENTA}[{model}] That did not work. Trying another method {ANSI_RESET}"
)
if config.verbose:
print("[Self-Operating Computer][Operate] error", e)
traceback.print_exc()
return gpt_4_fallback(messages, objective, model)
async def call_gpt_4o_labeled(messages, objective, model):
time.sleep(1)
try:
client = config.initialize_openai()
confirm_system_prompt(messages, objective, model)
file_path = pkg_resources.resource_filename("operate.models.weights", "best.pt")
yolo_model = YOLO(file_path) # Load your trained model
screenshots_dir = "screenshots"
if not os.path.exists(screenshots_dir):
os.makedirs(screenshots_dir)
screenshot_filename = os.path.join(screenshots_dir, "screenshot.png")
# Call the function to capture the screen with the cursor
capture_screen_with_cursor(screenshot_filename)
with open(screenshot_filename, "rb") as img_file:
img_base64 = base64.b64encode(img_file.read()).decode("utf-8")
img_base64_labeled, label_coordinates = add_labels(img_base64, yolo_model)
if len(messages) == 1:
user_prompt = get_user_first_message_prompt()
else:
user_prompt = get_user_prompt()
if config.verbose:
print(
"[call_gpt_4_vision_preview_labeled] user_prompt",
user_prompt,
)
vision_message = {
"role": "user",
"content": [
{"type": "text", "text": user_prompt},
{
"type": "image_url",
"image_url": {
"url": f"data:image/jpeg;base64,{img_base64_labeled}"
},
},
],
}
messages.append(vision_message)
response = client.chat.completions.create(
model="gpt-4o",
messages=messages,
presence_penalty=1,
frequency_penalty=1,
temperature=0.7,
max_tokens=3000,
)
content = response.choices[0].message.content
content = clean_json(content)
assistant_message = {"role": "assistant", "content": content}
messages.append(assistant_message)
content = json.loads(content)
if config.verbose:
print(
"[call_gpt_4_vision_preview_labeled] content",
content,
)
processed_content = []
for operation in content:
print(
"[call_gpt_4_vision_preview_labeled] for operation in content",
operation,
)
if operation.get("operation") == "click":
label = operation.get("label")
if config.verbose:
print(
"[Self Operating Computer][call_gpt_4_vision_preview_labeled] label",
label,
)
coordinates = get_label_coordinates(label, label_coordinates)
if config.verbose:
print(
"[Self Operating Computer][call_gpt_4_vision_preview_labeled] coordinates",
coordinates,
)
image = Image.open(
io.BytesIO(base64.b64decode(img_base64))
) # Load the image to get its size
image_size = image.size # Get the size of the image (width, height)
click_position_percent = get_click_position_in_percent(
coordinates, image_size
)
if config.verbose:
print(
"[Self Operating Computer][call_gpt_4_vision_preview_labeled] click_position_percent",
click_position_percent,
)
if not click_position_percent:
print(
f"{ANSI_GREEN}[Self-Operating Computer]{ANSI_RED}[Error] Failed to get click position in percent. Trying another method {ANSI_RESET}"
)
return call_gpt_4o(messages)
x_percent = f"{click_position_percent[0]:.2f}"
y_percent = f"{click_position_percent[1]:.2f}"
operation["x"] = x_percent
operation["y"] = y_percent
if config.verbose:
print(
"[Self Operating Computer][call_gpt_4_vision_preview_labeled] new click operation",
operation,
)
processed_content.append(operation)
else:
if config.verbose:
print(
"[Self Operating Computer][call_gpt_4_vision_preview_labeled] .append none click operation",
operation,
)
processed_content.append(operation)
if config.verbose:
print(
"[Self Operating Computer][call_gpt_4_vision_preview_labeled] new processed_content",
processed_content,
)
return processed_content
except Exception as e:
print(
f"{ANSI_GREEN}[Self-Operating Computer]{ANSI_BRIGHT_MAGENTA}[{model}] That did not work. Trying another method {ANSI_RESET}"
)
if config.verbose:
print("[Self-Operating Computer][Operate] error", e)
traceback.print_exc()
return call_gpt_4o(messages)
def call_ollama_llava(messages):
if config.verbose:
print("[call_ollama_llava]")
time.sleep(1)
try:
screenshots_dir = "screenshots"
if not os.path.exists(screenshots_dir):
os.makedirs(screenshots_dir)
screenshot_filename = os.path.join(screenshots_dir, "screenshot.png")
# Call the function to capture the screen with the cursor
capture_screen_with_cursor(screenshot_filename)
if len(messages) == 1:
user_prompt = get_user_first_message_prompt()
else:
user_prompt = get_user_prompt()
if config.verbose:
print(
"[call_ollama_llava] user_prompt",
user_prompt,
)
vision_message = {
"role": "user",
"content": user_prompt,
"images": [screenshot_filename],
}
messages.append(vision_message)
response = ollama.chat(
model="llava",
messages=messages,
)
# Important: Remove the image path from the message history.
# Ollama will attempt to load each image reference and will
# eventually timeout.
messages[-1]["images"] = None
content = response["message"]["content"].strip()
content = clean_json(content)
assistant_message = {"role": "assistant", "content": content}
if config.verbose:
print(
"[call_ollama_llava] content",
content,
)
content = json.loads(content)
messages.append(assistant_message)
return content
except ollama.ResponseError as e:
print(
f"{ANSI_GREEN}[Self-Operating Computer]{ANSI_RED}[Operate] Couldn't connect to Ollama. With Ollama installed, run `ollama pull llava` then `ollama serve`{ANSI_RESET}",
e,
)
except Exception as e:
print(
f"{ANSI_GREEN}[Self-Operating Computer]{ANSI_BRIGHT_MAGENTA}[llava] That did not work. Trying again {ANSI_RESET}",
e,
)
print(
f"{ANSI_GREEN}[Self-Operating Computer]{ANSI_RED}[Error] AI response was {ANSI_RESET}",
content,
)
if config.verbose:
traceback.print_exc()
return call_ollama_llava(messages)
async def call_claude_3_with_ocr(messages, objective, model):
if config.verbose:
print("[call_claude_3_with_ocr]")
try:
time.sleep(1)
client = config.initialize_anthropic()
confirm_system_prompt(messages, objective, model)
screenshots_dir = "screenshots"
if not os.path.exists(screenshots_dir):
os.makedirs(screenshots_dir)
screenshot_filename = os.path.join(screenshots_dir, "screenshot.png")
capture_screen_with_cursor(screenshot_filename)
# downsize screenshot due to 5MB size limit
with open(screenshot_filename, "rb") as img_file:
img = Image.open(img_file)
# Convert RGBA to RGB
if img.mode == "RGBA":
img = img.convert("RGB")
# Calculate the new dimensions while maintaining the aspect ratio
original_width, original_height = img.size
aspect_ratio = original_width / original_height
new_width = 2560 # Adjust this value to achieve the desired file size
new_height = int(new_width / aspect_ratio)
if config.verbose:
print("[call_claude_3_with_ocr] resizing claude")
# Resize the image
img_resized = img.resize((new_width, new_height), Image.Resampling.LANCZOS)
# Save the resized and converted image to a BytesIO object for JPEG format
img_buffer = io.BytesIO()
img_resized.save(
img_buffer, format="JPEG", quality=85
) # Adjust the quality parameter as needed
img_buffer.seek(0)
# Encode the resized image as base64
img_data = base64.b64encode(img_buffer.getvalue()).decode("utf-8")
if len(messages) == 1:
user_prompt = get_user_first_message_prompt()
else:
user_prompt = get_user_prompt()
vision_message = {
"role": "user",
"content": [
{
"type": "image",
"source": {
"type": "base64",
"media_type": "image/jpeg",
"data": img_data,
},
},
{
"type": "text",
"text": user_prompt
+ "**REMEMBER** Only output json format, do not append any other text.",
},
],
}
messages.append(vision_message)
# anthropic api expect system prompt as an separate argument
response = client.messages.create(
model="claude-3-opus-20240229",
max_tokens=3000,
system=messages[0]["content"],
messages=messages[1:],
)
content = response.content[0].text
content = clean_json(content)
content_str = content
try:
content = json.loads(content)
# rework for json mode output
except json.JSONDecodeError as e:
if config.verbose:
print(
f"{ANSI_GREEN}[Self-Operating Computer]{ANSI_RED}[Error] JSONDecodeError: {e} {ANSI_RESET}"
)
response = client.messages.create(
model="claude-3-opus-20240229",
max_tokens=3000,
system=f"This json string is not valid, when using with json.loads(content) \
it throws the following error: {e}, return correct json string. \
**REMEMBER** Only output json format, do not append any other text.",
messages=[{"role": "user", "content": content}],
)
content = response.content[0].text
content = clean_json(content)
content_str = content
content = json.loads(content)
if config.verbose:
print(
f"{ANSI_GREEN}[Self-Operating Computer]{ANSI_BRIGHT_MAGENTA}[{model}] content: {content} {ANSI_RESET}"
)
processed_content = []
for operation in content:
if operation.get("operation") == "click":
text_to_click = operation.get("text")
if config.verbose:
print(
"[call_claude_3_ocr][click] text_to_click",
text_to_click,
)
# Initialize EasyOCR Reader
reader = easyocr.Reader(["en"])
# Read the screenshot
result = reader.readtext(screenshot_filename)
# limit the text to extract has a higher success rate
text_element_index = get_text_element(
result, text_to_click[:3], screenshot_filename
)
coordinates = get_text_coordinates(
result, text_element_index, screenshot_filename
)
# add `coordinates`` to `content`
operation["x"] = coordinates["x"]
operation["y"] = coordinates["y"]
if config.verbose:
print(
"[call_claude_3_ocr][click] text_element_index",
text_element_index,
)
print(
"[call_claude_3_ocr][click] coordinates",
coordinates,
)
print(
"[call_claude_3_ocr][click] final operation",
operation,
)
processed_content.append(operation)
else:
processed_content.append(operation)
assistant_message = {"role": "assistant", "content": content_str}
messages.append(assistant_message)
return processed_content
except Exception as e:
print(
f"{ANSI_GREEN}[Self-Operating Computer]{ANSI_BRIGHT_MAGENTA}[{model}] That did not work. Trying another method {ANSI_RESET}"
)
if config.verbose:
print("[Self-Operating Computer][Operate] error", e)
traceback.print_exc()
print("message before convertion ", messages)
# Convert the messages to the GPT-4 format
gpt4_messages = [messages[0]] # Include the system message
for message in messages[1:]:
if message["role"] == "user":
# Update the image type format from "source" to "url"
updated_content = []
for item in message["content"]:
if isinstance(item, dict) and "type" in item:
if item["type"] == "image":
updated_content.append(
{
"type": "image_url",
"image_url": {
"url": f"data:image/png;base64,{item['source']['data']}"
},
}
)
else:
updated_content.append(item)
gpt4_messages.append({"role": "user", "content": updated_content})
elif message["role"] == "assistant":
gpt4_messages.append(
{"role": "assistant", "content": message["content"]}
)
return gpt_4_fallback(gpt4_messages, objective, model)
def get_last_assistant_message(messages):
"""
Retrieve the last message from the assistant in the messages array.
If the last assistant message is the first message in the array, return None.
"""
for index in reversed(range(len(messages))):
if messages[index]["role"] == "assistant":
if index == 0: # Check if the assistant message is the first in the array
return None
else:
return messages[index]
return None # Return None if no assistant message is found
def gpt_4_fallback(messages, objective, model):
if config.verbose:
print("[gpt_4_fallback]")
system_prompt = get_system_prompt("gpt-4o", objective)
new_system_message = {"role": "system", "content": system_prompt}
# remove and replace the first message in `messages` with `new_system_message`
messages[0] = new_system_message
if config.verbose:
print("[gpt_4_fallback][updated]")
print("[gpt_4_fallback][updated] len(messages)", len(messages))
return call_gpt_4o(messages)
def confirm_system_prompt(messages, objective, model):
"""
On `Exception` we default to `call_gpt_4_vision_preview` so we have this function to reassign system prompt in case of a previous failure
"""
if config.verbose:
print("[confirm_system_prompt] model", model)
system_prompt = get_system_prompt(model, objective)
new_system_message = {"role": "system", "content": system_prompt}
# remove and replace the first message in `messages` with `new_system_message`
messages[0] = new_system_message
if config.verbose:
print("[confirm_system_prompt]")
print("[confirm_system_prompt] len(messages)", len(messages))
for m in messages:
if m["role"] != "user":
print("--------------------[message]--------------------")
print("[confirm_system_prompt][message] role", m["role"])
print("[confirm_system_prompt][message] content", m["content"])
print("------------------[end message]------------------")
def clean_json(content):
if config.verbose:
print("\n\n[clean_json] content before cleaning", content)
if content.startswith("```json"):
content = content[
len("```json") :
].strip() # Remove starting ```json and trim whitespace
elif content.startswith("```"):
content = content[
len("```") :
].strip() # Remove starting ``` and trim whitespace
if content.endswith("```"):
content = content[
: -len("```")
].strip() # Remove ending ``` and trim whitespace
# Normalize line breaks and remove any unwanted characters
content = "\n".join(line.strip() for line in content.splitlines())
if config.verbose:
print("\n\n[clean_json] content after cleaning", content)
return content