forked from yoheinakajima/babyagi
-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbabyagi.py
executable file
·2416 lines (1979 loc) · 88.6 KB
/
babyagi.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
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
from dotenv import load_dotenv
"""
gpt-4o-2024-05-13 Issue: : I attempted to extend the context and enable keyboard control for the snake game, but I was unable to resolve the following error.
No matter how many times I execute it, it results in a build error. It is likely due to version differences, but it did not automatically investigate and resolve this issue.
Error
```
# Command executed most recently
flutter run -d web-server --web-port 8080 --web-hostname 0.0.0.0
# Result of last command executed
The Return Code for the command is 1:
Launching lib/main.dart on Web Server in debug mode...
Waiting for connection from debug service on Web Server... ⣷⣯⣽⣻⣟⡿⢿⣻⣟⣯⣽⣾⣷⣯⣽⣻
[K[31mlib/main.dart:153:16: Error: The argument type 'void Function(RawKeyEvent)' can't be assigned to the parameter type 'KeyEventResult Function(FocusNode, RawKeyEvent)?'.[39m
Waiting for connection from debug service on Web Server... ⣟
[K[31m - 'RawKeyEvent' is from 'package:flutter/src/services/raw_keyboard.dart' ('../flutter/packages/flutter/lib/src/services/raw_keyboard.dart').[39m
Waiting for connection from debug service on Web Server... ⡿
[K[31m - 'KeyEventResult' is from 'package:flutter/src/widgets/focus_manager.dart' ('../flutter/packages/flutter/lib/src/widgets/focus_manager.dart').[39m
Waiting for connection from debug service on Web Server... ⢿
[K[31m - 'FocusNode' is from 'package:flutter/src/widgets/focus_manager.dart' ('../flutter/packages/flutter/lib/src/widgets/focus_manager.dart').[39m
Waiting for connection from debug service on Web Server... ⣻
[K[31m onKey: _onKey,[39m
Waiting for connection from debug service on Web Server... ⣟
[K[31m ^[39m
Waiting for connection from debug service on Web Server... ⣯⣽⣾⣷⣯⣽⣻⣟⡿⢿⣻⣟⣯⣽⣾⣷⣯⣽⣻⣟⡿⢿⣻⣟⣯⣽⣾⣷⣯⣽⣻⣟⡿⢿⣻⣟⣯⣽⣾⣷⣯⣽⣻⣟⡿⢿⣻⣟⣯⣽⣾⣷⣯⣽⣻⣟⡿⢿⣻⣟⣯⣽⣾⣷⣯⣽⣻⣟⡿⢿⣻⣟⣯⣽⣾⣷⣯⣽⣻⣟⡿⢿ 9.8s
[31mFailed to compile application.[39m
```
Source
```
void _onKey(RawKeyEvent event) {
if (event is RawKeyDownEvent) {
switch (event.logicalKey.keyLabel) {
case 'Arrow Up':
if (direction != 'down') direction = 'up';
break;
case 'Arrow Down':
if (direction != 'up') direction = 'down';
break;
case 'Arrow Left':
if (direction != 'right') direction = 'left';
break;
case 'Arrow Right':
if (direction != 'left') direction = 'right';
break;
}
}
}
```
"""
# Load default environment variables (.env)
load_dotenv()
import os
import hashlib
import pickle
import subprocess
import select
import pty
import time
import logging
from collections import deque
from typing import Dict, List
import importlib
import anthropic
from anthropic import Anthropic
import openai
from openai import OpenAI
import google.generativeai as genai
import tiktoken as tiktoken
import re
from task_parser import TaskParser
from executed_task_parser import ExecutedTaskParser
import sys
import threading
import base64
#[Test]
#TaskParser().test()
#while True:
# time.sleep(100)
# Engine configuration
BABY_COMMAND_AGI_FOLDER = "/app"
WORKSPACE_FOLDER = "/workspace"
# Model: GPT, LLAMA, HUMAN, etc.
LLM_MODEL = os.getenv("LLM_MODEL", "claude-3-5-sonnet-20240620").lower()
LLM_VISION_MODEL = os.getenv("LLM_VISION_MODEL", "claude-3-5-sonnet-20240620").lower()
TOKEN_COUNT_MODEL = os.getenv("TOKEN_COUNT_MODEL", "claude-3-5-sonnet-20240620").lower()
# API Keys
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "")
ANTHROPIC_API_KEY= os.getenv("ANTHROPIC_API_KEY", "")
GOOGLE_AI_STUDIO_API_KEY = os.getenv("GOOGLE_AI_STUDIO_API_KEY", "")
OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY", "")
if not (LLM_MODEL.startswith("llama") or LLM_MODEL.startswith("human")):
assert ANTHROPIC_API_KEY, "\033[91m\033[1m" + "ANTHROPIC_API_KEY environment variable is missing from .env" + "\033[0m\033[0m"
# Table config
RESULTS_STORE_NAME = os.getenv("RESULTS_STORE_NAME", "no-name-table") + "-" + os.getenv("RESULTS_SOTRE_NUMBER", "0")
assert RESULTS_STORE_NAME, "\033[91m\033[1m" + "RESULTS_STORE_NAME environment variable is missing from .env" + "\033[0m\033[0m"
# Run configuration
INSTANCE_NAME = os.getenv("INSTANCE_NAME", "BabyCommandAGI")
COOPERATIVE_MODE = "none"
# If LLM_COMMAND_RESPONSE is set to True, the LLM will automatically respond if there is a confirmation when executing a command,
# but be aware that this will increase the number of times the LLM is used and increase the cost of the API, etc.
LLM_COMMAND_RESPONSE = True
JOIN_EXISTING_OBJECTIVE = False
MAX_MARGIN_TOKEN = 200 # Allow enough tokens to avoid being on the edge
MAX_MODEL_OUTPUT_TOKEN = 4 * 1024 # default value
MAX_MODEL_INPUT_TOKEN = 128 * 1024 # default value
# Maximum number of tokens is confirmed below
# https://docsbot.ai/models/compare/o3-mini/claude-3-5-sonnet
MAX_O3_MINI_OUTPUT_TOKEN = 100 * 1024
MAX_O3_MINI_INPUT_TOKEN = 200 * 1024
# Maximum number of tokens is confirmed below
# https://context.ai/compare/o1-preview/gpt-4o
MAX_O1_PREVIEW_OUTPUT_TOKEN = 32 * 1024
MAX_O1_PREVIEW_INPUT_TOKEN = 128 * 1024
# Maximum number of tokens is confirmed below
# https://docsbot.ai/models/compare/o3-mini/claude-3-7-sonnet-extended-thinking
MAX_CLAUDE_3_7_SONNET_THINKING_OUTPUT_TOKEN = 128 * 1000
MAX_CLAUDE_3_7_SONNET_THINKING_INPUT_TOKEN = 200 * 1000
# Maximum number of tokens is confirmed below
# https://docsbot.ai/models/compare/claude-3-7-sonnet/claude-3-7-sonnet-extended-thinking
MAX_CLAUDE_3_7_SONNET_OUTPUT_TOKEN = 128 * 1000
MAX_CLAUDE_3_7_SONNET_INPUT_TOKEN = 200 * 1000
# Maximum number of tokens is confirmed below
# https://context.ai/compare/gpt-4o/claude-3-5-sonnet
MAX_CLAUDE_3_5_SONNET_OUTPUT_TOKEN = 8 * 1024
MAX_CLAUDE_3_5_SONNET_INPUT_TOKEN = 200 * 1024
# Maximum number of tokens is confirmed below
# https://docsbot.ai/models/compare/gpt-4-5/claude-3-7-sonnet
MAX_GPT_4_5_PREVIEW_OUTPUT_TOKEN = 16 * 1024
MAX_GPT_4_5_PREVIEW_INPUT_TOKEN = 128 * 1024
# Maximum number of tokens is confirmed below
# https://platform.openai.com/docs/models/gpt-4o
MAX_CHATGPT_4O_LATEST_OUTPUT_TOKEN = 16 * 1024
MAX_CHATGPT_4O_LATEST_INPUT_TOKEN = 128 * 1024
MAX_COMMAND_RESULT_TOKEN = 8 * 1024
MAX_DUPLICATE_COMMAND_RESULT_TOKEN = 1 * 1024
# Goal configuration
ORIGINAL_OBJECTIVE = os.getenv("OBJECTIVE", "")
INITIAL_TASK = os.getenv("INITIAL_TASK", "")
# Set Variables
hash_object = hashlib.sha1(ORIGINAL_OBJECTIVE.encode())
hex_dig = hash_object.hexdigest()
objective_table_name = f"{hex_dig[:8]}-{RESULTS_STORE_NAME}"
OBJECTIVE_LIST_FILE = f"{BABY_COMMAND_AGI_FOLDER}/data/{objective_table_name}_objectvie_list.pkl"
TASK_LIST_FILE = f"{BABY_COMMAND_AGI_FOLDER}/data/{objective_table_name}_task_list.pkl"
EXECUTED_TASK_LIST_FILE = f"{BABY_COMMAND_AGI_FOLDER}/data/{RESULTS_STORE_NAME}_executed_task_list.pkl"
PWD_FILE = f"{BABY_COMMAND_AGI_FOLDER}/pwd/{RESULTS_STORE_NAME}"
ENV_DUMP_FILE = f"{BABY_COMMAND_AGI_FOLDER}/env_dump/{RESULTS_STORE_NAME}"
# logger
logging.basicConfig(format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
datefmt='%m-%d %H:%M',
filename=f"{BABY_COMMAND_AGI_FOLDER}/log/{objective_table_name}.log",
filemode='a',
level=logging.DEBUG)
def log(message):
print(message)
logging.info(message)
# Save and load functions for task_list and executed_task_list
def save_data(data, filename):
with open(filename, 'wb') as f:
pickle.dump(data, f)
def load_data(filename):
if os.path.exists(filename):
with open(filename, 'rb') as f:
return pickle.load(f)
return deque([])
def parse_objective(objective_list: deque) -> str:
if len(objective_list) == 1:
return objective_list[0]
objective = ""
for idx, objective_item in enumerate(objective_list):
objective += f"""[Objective {idx + 1}]{objective_item} """
return objective
objective_list = load_data(OBJECTIVE_LIST_FILE) #deque([])
if len(objective_list) == 0:
objective_list = deque([ORIGINAL_OBJECTIVE])
OBJECTIVE = parse_objective(objective_list)
# Extensions support begin
def can_import(module_name):
try:
importlib.import_module(module_name)
return True
except ImportError:
return False
DOTENV_EXTENSIONS = os.getenv("DOTENV_EXTENSIONS", "").split(" ")
# Command line arguments extension
# Can override any of the above environment variables
ENABLE_COMMAND_LINE_ARGS = (
os.getenv("ENABLE_COMMAND_LINE_ARGS", "false").lower() == "true"
)
if ENABLE_COMMAND_LINE_ARGS:
if can_import("extensions.argparseext"):
from extensions.argparseext import parse_arguments
OBJECTIVE, INITIAL_TASK, LLM_MODEL, DOTENV_EXTENSIONS, INSTANCE_NAME, COOPERATIVE_MODE, JOIN_EXISTING_OBJECTIVE = parse_arguments()
# Human mode extension
# Gives human input to babyagi
if LLM_MODEL.startswith("human"):
if can_import("extensions.human_mode"):
from extensions.human_mode import user_input_await
# Load additional environment variables for enabled extensions
# TODO: This might override the following command line arguments as well:
# OBJECTIVE, INITIAL_TASK, LLM_MODEL, INSTANCE_NAME, COOPERATIVE_MODE, JOIN_EXISTING_OBJECTIVE
if DOTENV_EXTENSIONS:
if can_import("extensions.dotenvext"):
from extensions.dotenvext import load_dotenv_extensions
load_dotenv_extensions(DOTENV_EXTENSIONS)
# TODO: There's still work to be done here to enable people to get
# defaults from dotenv extensions, but also provide command line
# arguments to override them
# Extensions support end
log("\033[95m\033[1m" + "\n*****CONFIGURATION*****\n" + "\033[0m\033[0m")
log(f"Name : {INSTANCE_NAME}")
log(f"Mode : {'alone' if COOPERATIVE_MODE in ['n', 'none'] else 'local' if COOPERATIVE_MODE in ['l', 'local'] else 'distributed' if COOPERATIVE_MODE in ['d', 'distributed'] else 'undefined'}")
log(f"LLM_MODEL : {LLM_MODEL}")
log(f"LLM_VISION_MODEL : {LLM_VISION_MODEL}")
log(f"TOKEN_COUNT_MODEL : {TOKEN_COUNT_MODEL}")
# Check if we know what we are doing
assert OBJECTIVE, "\033[91m\033[1m" + "OBJECTIVE environment variable is missing from .env" + "\033[0m\033[0m"
assert INITIAL_TASK, "\033[91m\033[1m" + "INITIAL_TASK environment variable is missing from .env" + "\033[0m\033[0m"
LLAMA_MODEL_PATH = os.getenv("LLAMA_MODEL_PATH", "models/llama-13B/ggml-model.bin")
if LLM_MODEL.startswith("llama"):
if can_import("llama_cpp"):
from llama_cpp import Llama
log(f"LLAMA : {LLAMA_MODEL_PATH}" + "\n")
assert os.path.exists(LLAMA_MODEL_PATH), "\033[91m\033[1m" + f"Model can't be found." + "\033[0m\033[0m"
CTX_MAX = 1024
LLAMA_THREADS_NUM = int(os.getenv("LLAMA_THREADS_NUM", 8))
TEMPERATURE = float(os.getenv("OPENAI_TEMPERATURE", "0.0"))
log('Initialize model for evaluation')
llm = Llama(
model_path=LLAMA_MODEL_PATH,
n_ctx=CTX_MAX,
n_threads=LLAMA_THREADS_NUM,
n_batch=512,
use_mlock=False,
)
log(
"\033[91m\033[1m"
+ "\n*****USING LLAMA.CPP. POTENTIALLY SLOW.*****"
+ "\033[0m\033[0m"
)
else:
log(
"\033[91m\033[1m"
+ "\nLlama LLM requires package llama-cpp. Falling back to GPT-3.5-turbo."
+ "\033[0m\033[0m"
)
LLM_MODEL = "gpt-4o"
TEMPERATURE = float(os.getenv("OPENAI_TEMPERATURE", "0.0"))
elif LLM_MODEL.startswith("o3-mini") or LLM_MODEL.startswith("openai/o3-mini"):
MAX_MODEL_OUTPUT_TOKEN = MAX_O3_MINI_OUTPUT_TOKEN
MAX_MODEL_INPUT_TOKEN = MAX_O3_MINI_INPUT_TOKEN
TEMPERATURE = float(os.getenv("OPENAI_TEMPERATURE", "0.0"))
log(
"\033[91m\033[1m"
+ "\n*****USING openrouter openai/o1-preview. POTENTIALLY EXPENSIVE. MONITOR YOUR COSTS*****"
+ "\033[0m\033[0m"
)
elif LLM_MODEL.startswith("openai/o1-preview"):
MAX_MODEL_OUTPUT_TOKEN = MAX_O1_PREVIEW_OUTPUT_TOKEN
MAX_MODEL_INPUT_TOKEN = MAX_O1_PREVIEW_INPUT_TOKEN
TEMPERATURE = float(os.getenv("OPENAI_TEMPERATURE", "0.0"))
log(
"\033[91m\033[1m"
+ "\n*****USING openrouter openai/o1-preview. POTENTIALLY EXPENSIVE. MONITOR YOUR COSTS*****"
+ "\033[0m\033[0m"
)
elif LLM_MODEL.startswith("gpt-4.5") or LLM_MODEL.startswith("openai/gpt-4.5"):
MAX_MODEL_OUTPUT_TOKEN = MAX_GPT_4_5_PREVIEW_OUTPUT_TOKEN
MAX_MODEL_INPUT_TOKEN = MAX_GPT_4_5_PREVIEW_INPUT_TOKEN
TEMPERATURE = float(os.getenv("OPENAI_TEMPERATURE", "0.0"))
log(
"\033[91m\033[1m"
+ "\n*****USING gpt-4.5-preview. POTENTIALLY EXPENSIVE. MONITOR YOUR COSTS*****"
+ "\033[0m\033[0m"
)
elif LLM_MODEL.startswith("gpt-4"):
log(
"\033[91m\033[1m"
+ "\n*****USING GPT-4. POTENTIALLY EXPENSIVE. MONITOR YOUR COSTS*****"
+ "\033[0m\033[0m"
)
TEMPERATURE = float(os.getenv("OPENAI_TEMPERATURE", "0.0"))
elif LLM_MODEL.startswith("chatgpt-4o-latest"):
MAX_MODEL_OUTPUT_TOKEN = MAX_CHATGPT_4O_LATEST_OUTPUT_TOKEN
MAX_MODEL_INPUT_TOKEN = MAX_CHATGPT_4O_LATEST_INPUT_TOKEN
TEMPERATURE = float(os.getenv("OPENAI_TEMPERATURE", "0.0"))
log(
"\033[91m\033[1m"
+ "\n*****USING chatgpt-4o-latest. POTENTIALLY EXPENSIVE. MONITOR YOUR COSTS*****"
+ "\033[0m\033[0m"
)
elif LLM_MODEL.startswith("claude-3-7-sonnet"):
if "-thinking" in LLM_MODEL.lower():
MAX_MODEL_OUTPUT_TOKEN = MAX_CLAUDE_3_7_SONNET_THINKING_OUTPUT_TOKEN
MAX_MODEL_INPUT_TOKEN = MAX_CLAUDE_3_7_SONNET_THINKING_INPUT_TOKEN
else:
# Use regular Claude limits when not in thinking mode
MAX_MODEL_OUTPUT_TOKEN = MAX_CLAUDE_3_7_SONNET_OUTPUT_TOKEN
MAX_MODEL_INPUT_TOKEN = MAX_CLAUDE_3_7_SONNET_INPUT_TOKEN
TEMPERATURE = float(os.getenv("ANTHROPIC_TEMPERATURE", "0.0"))
log(
"\033[91m\033[1m"
+ "\n*****USING Claude 3.5. POTENTIALLY EXPENSIVE. MONITOR YOUR COSTS*****"
+ "\033[0m\033[0m"
)
elif LLM_MODEL.startswith("claude-3-5-sonnet"):
MAX_MODEL_OUTPUT_TOKEN = MAX_CLAUDE_3_5_SONNET_OUTPUT_TOKEN
MAX_MODEL_INPUT_TOKEN = MAX_CLAUDE_3_5_SONNET_INPUT_TOKEN
TEMPERATURE = float(os.getenv("ANTHROPIC_TEMPERATURE", "0.0"))
log(
"\033[91m\033[1m"
+ "\n*****USING Claude 3.5. POTENTIALLY EXPENSIVE. MONITOR YOUR COSTS*****"
+ "\033[0m\033[0m"
)
elif LLM_MODEL.startswith("gemini"):
TEMPERATURE = float(os.getenv("GEMINI_TEMPERATURE", "0.0"))
log(
"\033[91m\033[1m"
+ "\n*****USING Gemini. POTENTIALLY EXPENSIVE. MONITOR YOUR COSTS*****"
+ "\033[0m\033[0m"
)
elif LLM_MODEL.startswith("human"):
log(
"\033[91m\033[1m"
+ "\n*****USING HUMAN INPUT*****"
+ "\033[0m\033[0m"
)
TEMPERATURE = float(os.getenv("OPENAI_TEMPERATURE", "0.0"))
# Max token initialization
MAX_OUTPUT_TOKEN = MAX_MODEL_OUTPUT_TOKEN
MAX_INPUT_TOKEN = MAX_MODEL_INPUT_TOKEN - MAX_OUTPUT_TOKEN - MAX_MARGIN_TOKEN # default value
log(
"\033[91m\033[1m"
+ "\n*****POTENTIALLY EXPENSIVE. MONITOR YOUR COSTS*****"
+ "\033[0m\033[0m"
)
log("\033[94m\033[1m" + "\n*****OBJECTIVE*****\n" + "\033[0m\033[0m")
log(f"{OBJECTIVE}")
# Configure client
anthropic_client = Anthropic(api_key=ANTHROPIC_API_KEY)
openai_client = OpenAI(api_key=OPENAI_API_KEY)
genai.configure(api_key=GOOGLE_AI_STUDIO_API_KEY)
# Task storage supporting only a single instance of BabyAGI
class SingleTaskListStorage:
def __init__(self, task_list: deque):
self.tasks = task_list
def append(self, task: Dict):
self.tasks.append(task)
def appendleft(self, task: Dict):
self.tasks.appendleft(task)
def replace(self, task_list: deque):
self.tasks = task_list
def reference(self, index: int):
return self.tasks[index]
def pop(self):
return self.tasks.pop()
def popleft(self):
return self.tasks.popleft()
def is_empty(self):
return False if self.tasks else True
def get_tasks(self):
return self.tasks
def remove_target_write_dicts(self, path):
"""
Remove dictionaries from the list where "target" key matches path and "type" key is "entire_file_after_writing".
Args:
- path (str): The target path to match against.
"""
self.tasks = deque([d for d in self.tasks if not (d.get("target") == path and d.get("type") == "entire_file_after_writing")])
def remove_target_command_dicts(self, path, command, result):
"""
Remove dictionaries from the list where "target" key matches path and "type" key is "command".
Args:
- path (str): The target path to match against.
"""
self.tasks = deque([d for d in self.tasks if not (d.get("target") == command and d.get("type") == "command" and "path" in d and d.get("path") == path and d.get("content") == result and self.is_big_command_result(result))])
def is_big_command_result(self, string) -> bool:
if TOKEN_COUNT_MODEL.lower().startswith("claude-3"):
# Claude 3 does not support a way to find out the number of tokens in advance
# https://github.com/anthropics/anthropic-sdk-python/issues/375#issuecomment-1999982035
# The count to get OpenAI's tokenizer is often low, as it seems to be about +-15% of OpenAI's tokenizers, so I estimate and calculate at -20% based on gpt-4o.
# https://www.reddit.com/r/ClaudeAI/comments/1bgg5v0/comment/kv9fais/?utm_source=share&utm_medium=web3x&utm_name=web3xcss&utm_term=1&utm_content=share_button
# https://www.reddit.com/r/ClaudeAI/comments/1bgg5v0/comment/l0phtj4/?utm_source=share&utm_medium=web3x&utm_name=web3xcss&utm_term=1&utm_content=share_button
try:
encoding = tiktoken.encoding_for_model('gpt-4o')
except:
encoding = tiktoken.encoding_for_model('gpt-4o') # Fallback for others.
encoded = encoding.encode(string)
length = int(len(encoded) * (1.0 - 0.2))
return MAX_DUPLICATE_COMMAND_RESULT_TOKEN <= length
else:
try:
encoding = tiktoken.encoding_for_model(TOKEN_COUNT_MODEL)
except:
encoding = tiktoken.encoding_for_model('gpt-4o') # Fallback for others.
encoded = encoding.encode(string)
return MAX_DUPLICATE_COMMAND_RESULT_TOKEN <= len(encoded)
# Task list
temp_task_list = load_data(TASK_LIST_FILE)
temp_executed_task_list = load_data(EXECUTED_TASK_LIST_FILE)
# Initialize tasks storage
tasks_storage = SingleTaskListStorage(temp_task_list)
executed_tasks_storage = SingleTaskListStorage(temp_executed_task_list)
if COOPERATIVE_MODE in ['l', 'local']:
if can_import("extensions.ray_tasks"):
import sys
from pathlib import Path
sys.path.append(str(Path(__file__).resolve().parent))
from extensions.ray_tasks import CooperativeTaskListStorage
tasks_storage = CooperativeTaskListStorage(OBJECTIVE, temp_task_list)
log("\nReplacing tasks storage: " + "\033[93m\033[1m" + "Ray" + "\033[0m\033[0m")
executed_tasks_storage = CooperativeTaskListStorage(OBJECTIVE, temp_executed_task_list)
log("\nReplacing executed tasks storage: " + "\033[93m\033[1m" + "Ray" + "\033[0m\033[0m")
elif COOPERATIVE_MODE in ['d', 'distributed']:
pass
if tasks_storage.is_empty() or JOIN_EXISTING_OBJECTIVE:
log("\033[93m\033[1m" + "\nInitial task:" + "\033[0m\033[0m" + f" {INITIAL_TASK}")
else:
log("\033[93m\033[1m" + f"\nContinue task" + "\033[0m\033[0m")
log("\n")
def limit_tokens_from_string(string: str, model: str, limit: int) -> str:
"""Limits the string to a number of tokens (estimated)."""
if model.lower().startswith("claude-3"):
# Claude 3 does not support a way to find out the number of tokens in advance
# https://github.com/anthropics/anthropic-sdk-python/issues/375#issuecomment-1999982035
# The count to get OpenAI's tokenizer is often low, as it seems to be about +-15% of OpenAI's tokenizers, so I estimate and calculate at -20% based on gpt-4o.
# https://www.reddit.com/r/ClaudeAI/comments/1bgg5v0/comment/kv9fais/?utm_source=share&utm_medium=web3x&utm_name=web3xcss&utm_term=1&utm_content=share_button
# https://www.reddit.com/r/ClaudeAI/comments/1bgg5v0/comment/l0phtj4/?utm_source=share&utm_medium=web3x&utm_name=web3xcss&utm_term=1&utm_content=share_button
try:
encoding = tiktoken.encoding_for_model('gpt-4o')
except:
encoding = tiktoken.encoding_for_model('gpt-4o') # Fallback for others.
limit = int(limit * (1.0 - 0.2))
else:
try:
encoding = tiktoken.encoding_for_model(model)
except:
encoding = tiktoken.encoding_for_model('gpt-4o') # Fallback for others.
encoded = encoding.encode(string)
return encoding.decode(encoded[:limit])
def last_tokens_from_string(string: str, model: str, last: int) -> str:
"""Limits the string to a number of tokens (estimated)."""
if model.lower().startswith("claude-3"):
# Claude 3 does not support a way to find out the number of tokens in advance
# https://github.com/anthropics/anthropic-sdk-python/issues/375#issuecomment-1999982035
# The count to get OpenAI's tokenizer is often low, as it seems to be about +-15% of OpenAI's tokenizers, so I estimate and calculate at -20% based on gpt-4o.
# https://www.reddit.com/r/ClaudeAI/comments/1bgg5v0/comment/kv9fais/?utm_source=share&utm_medium=web3x&utm_name=web3xcss&utm_term=1&utm_content=share_button
# https://www.reddit.com/r/ClaudeAI/comments/1bgg5v0/comment/l0phtj4/?utm_source=share&utm_medium=web3x&utm_name=web3xcss&utm_term=1&utm_content=share_button
try:
encoding = tiktoken.encoding_for_model('gpt-4o')
except:
encoding = tiktoken.encoding_for_model('gpt-4o') # Fallback for others.
last = int(last * (1.0 - 0.2))
else:
try:
encoding = tiktoken.encoding_for_model(model)
except:
encoding = tiktoken.encoding_for_model('gpt-4o') # Fallback for others.
encoded = encoding.encode(string)
return encoding.decode(encoded[-last:])
def separate_markdown(markdown):
"""
Separates a markdown string into images and text parts.
Images are identified and categorized as local files or URLs.
Local files are represented with a dictionary containing path and description.
URLs are represented with a dictionary containing URL and description.
Text parts are returned as strings.
Args:
markdown (str): The Markdown string to be processed.
Returns:
list: A list containing separated parts of the Markdown content.
"""
# Regex patterns for identifying images and splitting content
image_pattern = r'!\[(.*?)\]\((.*?)\)'
split_pattern = r'(!\[.*?\]\(.*?\))'
# Split the markdown content
parts = re.split(split_pattern, markdown)
# Process each part to categorize as image or text
result = []
for part in parts:
# Check if the part is an image
match = re.match(image_pattern, part)
if match:
description, path_or_url = match.groups()
# Check if it's a local file or a URL
if path_or_url.startswith('http://') or path_or_url.startswith('https://'):
result.append({'url': path_or_url, 'description': description})
else:
result.append({'path': path_or_url, 'description': description})
else:
# If not an image, it's a text part
if part.strip():
result.append(part)
return result
def encode_image(image_path):
""" Encodes a local image file to base64 """
with open(image_path, 'rb') as image_file:
encoded_string = base64.b64encode(image_file.read()).decode()
return encoded_string
def modify_parts_to_new_format_anthropic(parts):
"""
Modifies the given array of Markdown parts to a new specified format.
Args:
parts (list): A list containing separated parts of Markdown content including images and text.
Returns:
list: A list of parts in the new specified format.
"""
new_format_parts = []
for part in parts:
if isinstance(part, str): # Text part
new_format_parts.append({"type": "text", "text": part})
elif isinstance(part, dict):
if 'url' in part: # Image with URL
raise Exception("Image with URL is not supported in Anthropic API")
elif 'path' in part: # Local image file
# Determine media type based on file extension
extension = part['path'].split('.')[-1].lower()
if extension in ['jpg', 'jpeg']:
media_type = 'image/jpeg'
elif extension == 'png':
media_type = 'image/png'
elif extension == 'gif':
media_type = 'image/gif'
elif extension == 'webp':
media_type = 'image/webp'
else:
media_type = 'application/octet-stream' # Default media type
base64_image = encode_image(part['path'])
new_format_parts.append({
"type": "image",
"source": {
"type": "base64",
"media_type": media_type,
"data": base64_image
}
})
return new_format_parts
def modify_parts_to_new_format_openai(parts):
"""
Modifies the given array of Markdown parts to a new specified format.
Args:
parts (list): A list containing separated parts of Markdown content including images and text.
Returns:
list: A list of parts in the new specified format.
"""
new_format_parts = []
for part in parts:
if isinstance(part, str): # Text part
new_format_parts.append({"type": "text", "text": part})
elif isinstance(part, dict):
if 'url' in part: # Image with URL
new_format_parts.append({"type": "image_url", "image_url": {"url": part['url']}})
elif 'path' in part: # Local image file
extension = part['path'].split('.')[-1].lower()
if extension in ['jpg', 'jpeg']:
media_type = 'image/jpeg'
elif extension == 'png':
media_type = 'image/png'
elif extension == 'gif':
media_type = 'image/gif'
elif extension == 'webp':
media_type = 'image/webp'
else:
media_type = 'application/octet-stream' # Default media type
base64_image = encode_image(part['path'])
new_format_parts.append({"type": "image_url", "image_url": {"url": f"data:{media_type};base64,{base64_image}"}})
return new_format_parts
def llm_call(
prompt: str,
model: str = LLM_MODEL,
temperature: float = TEMPERATURE,
max_tokens: int = MAX_OUTPUT_TOKEN,
):
while True:
try:
if model.lower().startswith("llama"):
result = llm(prompt[:CTX_MAX],
stop=["### Human"],
echo=False,
temperature=0.2,
top_k=40,
top_p=0.95,
repeat_penalty=1.05,
max_tokens=200)
# log('\n*****RESULT JSON DUMP*****\n')
# log(json.dumps(result))
# log('\n')
return result['choices'][0]['text'].strip()
elif model.lower().startswith("human"):
return user_input_await(prompt)
# Comment out for Open Router.
# elif not model.lower().startswith("gpt-"):
# # Use completion API
# response = openai.Completion.create(
# engine=model,
# prompt=prompt,
# temperature=temperature,
# max_tokens=max_tokens,
# top_p=1,
# frequency_penalty=0,
# presence_penalty=0,
# )
# return response.choices[0].text.strip()
elif model.lower().startswith("gemini"):
log(f"【MODEL】:{model}")
system_prompt = prompt
generation_config = {
"temperature" : temperature,
"max_output_tokens": 8192,
"response_mime_type": "text/plain",
}
model = genai.GenerativeModel(
model_name=model,
generation_config=generation_config,
system_instruction=system_prompt,
)
chat_session = model.start_chat(
history=[
]
)
response = chat_session.send_message(prompt)
return response.text.strip()
elif model.lower().startswith("claude"):
anthropic_client = Anthropic(api_key=ANTHROPIC_API_KEY)
separated_content = separate_markdown(prompt) # for Vision API
if len(separated_content) > 1:
log(f"【MODEL】:{LLM_VISION_MODEL}")
messages = [
{
"role": "user",
"content": modify_parts_to_new_format_anthropic(separated_content)
}
]
# log("【MESSAGES】")
# log(json.dumps(messages))
if model.lower().startswith("claude-3-7-sonnet"):
if "-thinking" in model.lower():
# Remove the "-thinking" suffix from the model if present, then call the API with thinking enabled
model_name = model.replace("-thinking", "")
stream_response = anthropic_client.messages.create(
model=model_name,
messages=messages,
max_tokens=max_tokens,
thinking={"type": "enabled", "budget_tokens": 32000},
extra_headers={"anthropic-beta": "output-128k-2025-02-19"}, # For extended-thinking https://docs.anthropic.com/en/docs/about-claude/models/extended-thinking-models
stream=True
)
else:
# Regular API call for non-thinking mode
stream_response = anthropic_client.messages.create(
model=model,
messages=messages,
temperature=temperature,
max_tokens=max_tokens,
extra_headers={"anthropic-beta": "output-128k-2025-02-19"}, # For extended-thinking https://docs.anthropic.com/en/docs/about-claude/models/extended-thinking-models
stream=True
)
full_text = ""
for chunk in stream_response:
if hasattr(chunk, "delta") and getattr(chunk.delta, "text", None):
full_text += chunk.delta.text
log(f"chunk.delta.text: {chunk.delta.text}")
log(f"Chunk received: {chunk}")
return full_text.strip()
elif model.lower().startswith("claude-3-5-sonnet"):
response = anthropic_client.messages.create(
model=LLM_VISION_MODEL,
messages=messages,
temperature=temperature,
max_tokens=max_tokens,
extra_headers={"anthropic-beta": "max-tokens-3-5-sonnet-2024-07-15"}, # For 8K output https://x.com/alexalbert__/status/1812921642143900036
)
log(f"【USAGE】input_tokens :{response.usage.input_tokens}")
log(f"【USAGE】output_tokens :{response.usage.output_tokens}")
return response.content[0].text.strip()
else:
log(f"【MODEL】:{model}")
messages = [{"role": "user", "content": prompt}]
if model.lower().startswith("claude-3-7-sonnet"):
if "-thinking" in model.lower():
# Remove the "-thinking" suffix from the model if present, then call the API with thinking enabled
model_name = model.replace("-thinking", "")
stream_response = anthropic_client.messages.create(
model=model_name,
messages=messages,
max_tokens=max_tokens,
thinking={"type": "enabled", "budget_tokens": 32000},
extra_headers={"anthropic-beta": "output-128k-2025-02-19"}, # For extended-thinking https://docs.anthropic.com/en/docs/about-claude/models/extended-thinking-models
stream=True
)
else:
# Regular API call for non-thinking mode
stream_response = anthropic_client.messages.create(
model=model,
messages=messages,
temperature=temperature,
max_tokens=max_tokens,
extra_headers={"anthropic-beta": "output-128k-2025-02-19"}, # For extended-thinking https://docs.anthropic.com/en/docs/about-claude/models/extended-thinking-models
stream=True
)
full_text = ""
for chunk in stream_response:
if hasattr(chunk, "delta") and getattr(chunk.delta, "text", None):
full_text += chunk.delta.text
log(f"chunk.delta.text: {chunk.delta.text}")
log(f"Chunk received: {chunk}")
return full_text.strip()
elif model.lower().startswith("claude-3-5-sonnet"):
response = anthropic_client.messages.create(
model=model,
messages=messages,
temperature=temperature,
max_tokens=max_tokens,
extra_headers={"anthropic-beta": "max-tokens-3-5-sonnet-2024-07-15"}, # For 8K output https://x.com/alexalbert__/status/1812921642143900036
)
log(f"【USAGE】input_tokens :{response.usage.input_tokens}")
log(f"【USAGE】output_tokens :{response.usage.output_tokens}")
return response.content[0].text.strip()
elif model.lower().startswith("openai/"): # OpenRouter's OpenAI
openai_client = OpenAI(
base_url="https://openrouter.ai/api/v1",
api_key=OPENROUTER_API_KEY)
log(f"【MODEL】: OpenRouter {model}")
messages = [{"role": "system", "content": prompt}]
response = openai_client.chat.completions.create(
extra_headers={
"HTTP-Referer": "https://github.com/saten-private/BabyCommandAGI", # Optional, for including your app on openrouter.ai rankings.
"X-Title": "BabyCommandAGI", # Optional. Shows in rankings on openrouter.ai.
},
model=model,
messages=messages,
temperature=temperature,
max_tokens=max_tokens,
)
return response.choices[0].message.content.strip()
else:
openai_client = OpenAI(api_key=OPENAI_API_KEY)
separated_content = separate_markdown(prompt) # for Vision API
if len(separated_content) > 1:
log(f"【MODEL】:{LLM_VISION_MODEL}")
messages = [
{
"role": "system",
"content": modify_parts_to_new_format_openai(separated_content)
}
]
# log("【MESSAGES】")
# log(json.dumps(messages))
response = openai_client.chat.completions.create(
model=LLM_VISION_MODEL,
messages=messages,
temperature=temperature,
max_tokens=max_tokens,
)
else:
log(f"【MODEL】:{model}")
messages = [{"role": "system", "content": prompt}]
response = openai_client.chat.completions.create(
model=model,
messages=messages,
temperature=temperature,
max_tokens=max_tokens,
)
return response.choices[0].message.content.strip()
# OpenAI
except openai.RateLimitError as e:
log(
f" *** The OpenAI API rate limit has been exceeded. Waiting 300 seconds and trying again. error: {str(e)} ***"
)
time.sleep(300) # Wait seconds and try again
except openai.APITimeoutError as e:
log(
f" *** OpenAI API timeout occurred. Waiting 10 seconds and trying again. error: {str(e)} ***"
)
time.sleep(10) # Wait 10 seconds and try again
except openai.APIError as e:
log(
f" *** OpenAI API error occurred. Waiting 300 seconds and trying again. error: {str(e)} ***"
)
time.sleep(300) # Wait seconds and try again
except openai.APIConnectionError as e:
log(
f" *** OpenAI API connection error occurred. Check your network settings, proxy configuration, SSL certificates, or firewall rules. Waiting 300 seconds and trying again. error: {str(e)} ***"
)
time.sleep(300) # Wait seconds and try again
except openai.BadRequestError as e:
log(
f" *** OpenAI API BadRequestError. Check the documentation for the specific API method you are calling and make sure you are sending valid and complete parameters. Waiting 10 seconds and trying again. error: {str(e)} ***"
)
raise e
except openai.InternalServerError as e:
log(
f" *** OpenAI API InternalServerError. error: {str(e)} ***"
)
raise e
# Anthropic
except anthropic.RateLimitError as e:
log(
f" *** The Anthropic API rate limit has been exceeded. Waiting 300 seconds and trying again. error: {str(e)} ***"
)
time.sleep(300) # Wait seconds and try again
except anthropic.APIConnectionError as e:
log(
f" *** Anthropic API connection error occurred. error: {str(e)} ***"
)
raise e
except anthropic.APIStatusError as e:
log(
f" *** Anthropic API status error occurred. error: {str(e)} ***"
)
raise e
except Exception as e:
log(
f" *** Other error occurred: {str(e)} ***"
)
raise e
# Global variable for flagging input
input_flag = None
def check_input():
global input_flag
while True:
time.sleep(2)
if input_flag == "f" or input_flag == "a":
continue
log("\n" + "\033[33m\033[1m" + 'The system now accepts "f" if you want to send feedback to the AI, or "a" if you want to send the answer to the shell.' + "\033[0m\033[0m" + "\n")
inp = input()
if inp == "f" or inp == "a":
input_flag = inp
# Thread for non-blocking input check
input_thread = threading.Thread(target=check_input, daemon=True)
input_thread.start()
def check_completion_agent(
objective: str, enriched_result: dict, task_list: deque, executed_task_list: deque, current_dir: str
):
prompt = f"""You are the best engineer and manage the tasks to achieve the "{objective}".
Please try to make the tasks you generate as necessary so that they can be executed by writing a single file or in a terminal. If that's difficult, generate "plan" tasks with reduced granularity.
Follow the format in "Example X of tasks output" below to output next tasks. Please never output anything other than a "Example X of tasks output" format that always includes "type:" before ``` blocks. Please never output 'sudo' commands.
Below is the result of the last execution."""
if enriched_result["type"].startswith("entire_file_after_writing"):
prompt += f"""