Skip to content

Commit 328ba5e

Browse files
committed
formatting
1 parent a0e3c23 commit 328ba5e

40 files changed

+908
-589
lines changed

autogpt/__main__.py

+162-81
Large diffs are not rendered by default.

autogpt/agent.py

+81-37
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
1-
import autogpt.commands as cmd
21
import json
32
import traceback
43
from tkinter.ttk import Style
54

65
from colorama import Fore
76

87
import autogpt.chat
8+
import autogpt.commands as cmd
9+
import autogpt.speak
910
from autogpt.config import Config
1011
from autogpt.logger import logger
11-
import autogpt.speak
1212
from autogpt.spinner import Spinner
1313

1414

@@ -24,13 +24,16 @@ class Agent:
2424
user_input: The user input.
2525
2626
"""
27-
def __init__(self,
28-
ai_name,
29-
memory,
30-
full_message_history,
31-
next_action_count,
32-
prompt,
33-
user_input):
27+
28+
def __init__(
29+
self,
30+
ai_name,
31+
memory,
32+
full_message_history,
33+
next_action_count,
34+
prompt,
35+
user_input,
36+
):
3437
self.ai_name = ai_name
3538
self.memory = memory
3639
self.full_message_history = full_message_history
@@ -43,10 +46,16 @@ def start_interaction_loop(self):
4346
cfg = Config()
4447
loop_count = 0
4548
while True:
46-
# Discontinue if continuous limit is reached
49+
# Discontinue if continuous limit is reached
4750
loop_count += 1
48-
if cfg.continuous_mode and cfg.continuous_limit > 0 and loop_count > cfg.continuous_limit:
49-
logger.typewriter_log("Continuous Limit Reached: ", Fore.YELLOW, f"{cfg.continuous_limit}")
51+
if (
52+
cfg.continuous_mode
53+
and cfg.continuous_limit > 0
54+
and loop_count > cfg.continuous_limit
55+
):
56+
logger.typewriter_log(
57+
"Continuous Limit Reached: ", Fore.YELLOW, f"{cfg.continuous_limit}"
58+
)
5059
break
5160

5261
# Send message to AI, get response
@@ -56,15 +65,17 @@ def start_interaction_loop(self):
5665
self.user_input,
5766
self.full_message_history,
5867
self.memory,
59-
cfg.fast_token_limit) # TODO: This hardcodes the model to use GPT3.5. Make this an argument
68+
cfg.fast_token_limit,
69+
) # TODO: This hardcodes the model to use GPT3.5. Make this an argument
6070

6171
# Print Assistant thoughts
6272
print_assistant_thoughts(assistant_reply)
6373

6474
# Get command name and arguments
6575
try:
6676
command_name, arguments = cmd.get_command(
67-
attempt_to_fix_json_by_finding_outermost_brackets(assistant_reply))
77+
attempt_to_fix_json_by_finding_outermost_brackets(assistant_reply)
78+
)
6879
if cfg.speak_mode:
6980
speak.say_text(f"I want to execute {command_name}")
7081
except Exception as e:
@@ -78,21 +89,29 @@ def start_interaction_loop(self):
7889
logger.typewriter_log(
7990
"NEXT ACTION: ",
8091
Fore.CYAN,
81-
f"COMMAND = {Fore.CYAN}{command_name}{Style.RESET_ALL} ARGUMENTS = {Fore.CYAN}{arguments}{Style.RESET_ALL}")
92+
f"COMMAND = {Fore.CYAN}{command_name}{Style.RESET_ALL} ARGUMENTS = {Fore.CYAN}{arguments}{Style.RESET_ALL}",
93+
)
8294
print(
8395
f"Enter 'y' to authorise command, 'y -N' to run N continuous commands, 'n' to exit program, or enter feedback for {self.ai_name}...",
84-
flush=True)
96+
flush=True,
97+
)
8598
while True:
86-
console_input = utils.clean_input(Fore.MAGENTA + "Input:" + Style.RESET_ALL)
99+
console_input = utils.clean_input(
100+
Fore.MAGENTA + "Input:" + Style.RESET_ALL
101+
)
87102
if console_input.lower().rstrip() == "y":
88103
self.user_input = "GENERATE NEXT COMMAND JSON"
89104
break
90105
elif console_input.lower().startswith("y -"):
91106
try:
92-
self.next_action_count = abs(int(console_input.split(" ")[1]))
107+
self.next_action_count = abs(
108+
int(console_input.split(" ")[1])
109+
)
93110
self.user_input = "GENERATE NEXT COMMAND JSON"
94111
except ValueError:
95-
print("Invalid input format. Please enter 'y -n' where n is the number of continuous tasks.")
112+
print(
113+
"Invalid input format. Please enter 'y -n' where n is the number of continuous tasks."
114+
)
96115
continue
97116
break
98117
elif console_input.lower() == "n":
@@ -107,7 +126,8 @@ def start_interaction_loop(self):
107126
logger.typewriter_log(
108127
"-=-=-=-=-=-=-= COMMAND AUTHORISED BY USER -=-=-=-=-=-=-=",
109128
Fore.MAGENTA,
110-
"")
129+
"",
130+
)
111131
elif self.user_input == "EXIT":
112132
print("Exiting...", flush=True)
113133
break
@@ -116,54 +136,68 @@ def start_interaction_loop(self):
116136
logger.typewriter_log(
117137
"NEXT ACTION: ",
118138
Fore.CYAN,
119-
f"COMMAND = {Fore.CYAN}{command_name}{Style.RESET_ALL} ARGUMENTS = {Fore.CYAN}{arguments}{Style.RESET_ALL}")
139+
f"COMMAND = {Fore.CYAN}{command_name}{Style.RESET_ALL} ARGUMENTS = {Fore.CYAN}{arguments}{Style.RESET_ALL}",
140+
)
120141

121142
# Execute command
122143
if command_name is not None and command_name.lower().startswith("error"):
123-
result = f"Command {command_name} threw the following error: " + arguments
144+
result = (
145+
f"Command {command_name} threw the following error: " + arguments
146+
)
124147
elif command_name == "human_feedback":
125148
result = f"Human feedback: {self.user_input}"
126149
else:
127150
result = f"Command {command_name} returned: {cmd.execute_command(command_name, arguments)}"
128151
if self.next_action_count > 0:
129152
self.next_action_count -= 1
130153

131-
memory_to_add = f"Assistant Reply: {assistant_reply} " \
132-
f"\nResult: {result} " \
133-
f"\nHuman Feedback: {self.user_input} "
154+
memory_to_add = (
155+
f"Assistant Reply: {assistant_reply} "
156+
f"\nResult: {result} "
157+
f"\nHuman Feedback: {self.user_input} "
158+
)
134159

135160
self.memory.add(memory_to_add)
136161

137162
# Check if there's a result from the command append it to the message
138163
# history
139164
if result is not None:
140-
self.full_message_history.append(chat.create_chat_message("system", result))
165+
self.full_message_history.append(
166+
chat.create_chat_message("system", result)
167+
)
141168
logger.typewriter_log("SYSTEM: ", Fore.YELLOW, result)
142169
else:
143170
self.full_message_history.append(
144-
chat.create_chat_message(
145-
"system", "Unable to execute command"))
146-
logger.typewriter_log("SYSTEM: ", Fore.YELLOW, "Unable to execute command")
171+
chat.create_chat_message("system", "Unable to execute command")
172+
)
173+
logger.typewriter_log(
174+
"SYSTEM: ", Fore.YELLOW, "Unable to execute command"
175+
)
147176

148177

149178
def attempt_to_fix_json_by_finding_outermost_brackets(json_string):
150179
cfg = Config()
151180
if cfg.speak_mode and cfg.debug_mode:
152-
speak.say_text("I have received an invalid JSON response from the OpenAI API. Trying to fix it now.")
181+
speak.say_text(
182+
"I have received an invalid JSON response from the OpenAI API. Trying to fix it now."
183+
)
153184
logger.typewriter_log("Attempting to fix JSON by finding outermost brackets\n")
154185

155186
try:
156187
# Use regex to search for JSON objects
157188
import regex
189+
158190
json_pattern = regex.compile(r"\{(?:[^{}]|(?R))*\}")
159191
json_match = json_pattern.search(json_string)
160192

161193
if json_match:
162194
# Extract the valid JSON object from the string
163195
json_string = json_match.group(0)
164-
logger.typewriter_log(title="Apparently json was fixed.", title_color=Fore.GREEN)
196+
logger.typewriter_log(
197+
title="Apparently json was fixed.", title_color=Fore.GREEN
198+
)
165199
if cfg.speak_mode and cfg.debug_mode:
166-
speak.say_text("Apparently json was fixed.")
200+
speak.say_text("Apparently json was fixed.")
167201
else:
168202
raise ValueError("No valid JSON object found")
169203

@@ -187,7 +221,9 @@ def print_assistant_thoughts(assistant_reply):
187221
assistant_reply_json = fix_and_parse_json(assistant_reply)
188222
except json.JSONDecodeError as e:
189223
logger.error("Error: Invalid JSON in assistant thoughts\n", assistant_reply)
190-
assistant_reply_json = attempt_to_fix_json_by_finding_outermost_brackets(assistant_reply)
224+
assistant_reply_json = attempt_to_fix_json_by_finding_outermost_brackets(
225+
assistant_reply
226+
)
191227
assistant_reply_json = fix_and_parse_json(assistant_reply_json)
192228

193229
# Check if assistant_reply_json is a string and attempt to parse it into a JSON object
@@ -196,7 +232,11 @@ def print_assistant_thoughts(assistant_reply):
196232
assistant_reply_json = json.loads(assistant_reply_json)
197233
except json.JSONDecodeError as e:
198234
logger.error("Error: Invalid JSON\n", assistant_reply)
199-
assistant_reply_json = attempt_to_fix_json_by_finding_outermost_brackets(assistant_reply_json)
235+
assistant_reply_json = (
236+
attempt_to_fix_json_by_finding_outermost_brackets(
237+
assistant_reply_json
238+
)
239+
)
200240

201241
assistant_thoughts_reasoning = None
202242
assistant_thoughts_plan = None
@@ -211,7 +251,9 @@ def print_assistant_thoughts(assistant_reply):
211251
assistant_thoughts_criticism = assistant_thoughts.get("criticism")
212252
assistant_thoughts_speak = assistant_thoughts.get("speak")
213253

214-
logger.typewriter_log(f"{ai_name.upper()} THOUGHTS:", Fore.YELLOW, assistant_thoughts_text)
254+
logger.typewriter_log(
255+
f"{ai_name.upper()} THOUGHTS:", Fore.YELLOW, assistant_thoughts_text
256+
)
215257
logger.typewriter_log("REASONING:", Fore.YELLOW, assistant_thoughts_reasoning)
216258

217259
if assistant_thoughts_plan:
@@ -223,7 +265,7 @@ def print_assistant_thoughts(assistant_reply):
223265
assistant_thoughts_plan = str(assistant_thoughts_plan)
224266

225267
# Split the input_string using the newline character and dashes
226-
lines = assistant_thoughts_plan.split('\n')
268+
lines = assistant_thoughts_plan.split("\n")
227269
for line in lines:
228270
line = line.lstrip("- ")
229271
logger.typewriter_log("- ", Fore.GREEN, line.strip())
@@ -237,7 +279,9 @@ def print_assistant_thoughts(assistant_reply):
237279
except json.decoder.JSONDecodeError as e:
238280
logger.error("Error: Invalid JSON\n", assistant_reply)
239281
if cfg.speak_mode:
240-
speak.say_text("I have received an invalid JSON response from the OpenAI API. I cannot ignore this response.")
282+
speak.say_text(
283+
"I have received an invalid JSON response from the OpenAI API. I cannot ignore this response."
284+
)
241285

242286
# All other errors, return "Error: + error message"
243287
except Exception as e:

autogpt/agent_manager.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,9 @@ def create_agent(task, prompt, model):
1212
global next_key
1313
global agents
1414

15-
messages = [{"role": "user", "content": prompt}, ]
15+
messages = [
16+
{"role": "user", "content": prompt},
17+
]
1618

1719
# Start GPT instance
1820
agent_reply = create_chat_completion(

autogpt/ai_config.py

+19-9
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
1-
import yaml
21
import os
2+
3+
import yaml
4+
35
from autogpt.prompt import get_prompt
46

57

@@ -13,7 +15,9 @@ class AIConfig:
1315
ai_goals (list): The list of objectives the AI is supposed to complete.
1416
"""
1517

16-
def __init__(self, ai_name: str="", ai_role: str="", ai_goals: list=[]) -> None:
18+
def __init__(
19+
self, ai_name: str = "", ai_role: str = "", ai_goals: list = []
20+
) -> None:
1721
"""
1822
Initialize a class instance
1923
@@ -30,10 +34,10 @@ def __init__(self, ai_name: str="", ai_role: str="", ai_goals: list=[]) -> None:
3034
self.ai_goals = ai_goals
3135

3236
# Soon this will go in a folder where it remembers more stuff about the run(s)
33-
SAVE_FILE = os.path.join(os.path.dirname(__file__), '..', 'ai_settings.yaml')
37+
SAVE_FILE = os.path.join(os.path.dirname(__file__), "..", "ai_settings.yaml")
3438

3539
@classmethod
36-
def load(cls: object, config_file: str=SAVE_FILE) -> object:
40+
def load(cls: object, config_file: str = SAVE_FILE) -> object:
3741
"""
3842
Returns class object with parameters (ai_name, ai_role, ai_goals) loaded from yaml file if yaml file exists,
3943
else returns class with no parameters.
@@ -47,7 +51,7 @@ def load(cls: object, config_file: str=SAVE_FILE) -> object:
4751
"""
4852

4953
try:
50-
with open(config_file, encoding='utf-8') as file:
54+
with open(config_file, encoding="utf-8") as file:
5155
config_params = yaml.load(file, Loader=yaml.FullLoader)
5256
except FileNotFoundError:
5357
config_params = {}
@@ -58,7 +62,7 @@ def load(cls: object, config_file: str=SAVE_FILE) -> object:
5862

5963
return cls(ai_name, ai_role, ai_goals)
6064

61-
def save(self, config_file: str=SAVE_FILE) -> None:
65+
def save(self, config_file: str = SAVE_FILE) -> None:
6266
"""
6367
Saves the class parameters to the specified file yaml file path as a yaml file.
6468
@@ -69,8 +73,12 @@ def save(self, config_file: str=SAVE_FILE) -> None:
6973
None
7074
"""
7175

72-
config = {"ai_name": self.ai_name, "ai_role": self.ai_role, "ai_goals": self.ai_goals}
73-
with open(config_file, "w", encoding='utf-8') as file:
76+
config = {
77+
"ai_name": self.ai_name,
78+
"ai_role": self.ai_role,
79+
"ai_goals": self.ai_goals,
80+
}
81+
with open(config_file, "w", encoding="utf-8") as file:
7482
yaml.dump(config, file, allow_unicode=True)
7583

7684
def construct_full_prompt(self) -> str:
@@ -87,7 +95,9 @@ def construct_full_prompt(self) -> str:
8795
prompt_start = """Your decisions must always be made independently without seeking user assistance. Play to your strengths as an LLM and pursue simple strategies with no legal complications."""
8896

8997
# Construct full prompt
90-
full_prompt = f"You are {self.ai_name}, {self.ai_role}\n{prompt_start}\n\nGOALS:\n\n"
98+
full_prompt = (
99+
f"You are {self.ai_name}, {self.ai_role}\n{prompt_start}\n\nGOALS:\n\n"
100+
)
91101
for i, goal in enumerate(self.ai_goals):
92102
full_prompt += f"{i+1}. {goal}\n"
93103

autogpt/ai_functions.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
1-
from typing import List
21
import json
3-
from autogpt.config import Config
2+
from typing import List
3+
44
from autogpt.call_ai_function import call_ai_function
5+
from autogpt.config import Config
6+
57
cfg = Config()
68

79

0 commit comments

Comments
 (0)