wrap infinite loop in class agent

This commit is contained in:
Merwane Hamadi
2023-04-13 15:19:41 -07:00
parent a3024ca80d
commit c59b6b5543

View File

@@ -351,110 +351,148 @@ def main():
# this is particularly important for indexing and referencing pinecone memory # this is particularly important for indexing and referencing pinecone memory
memory = get_memory(cfg, init=True) memory = get_memory(cfg, init=True)
print('Using memory of type: ' + memory.__class__.__name__) print('Using memory of type: ' + memory.__class__.__name__)
# Interaction Loop agent = Agent(
loop_count = 0 ai_name=ai_name,
while True: memory=memory,
# Discontinue if continuous limit is reached full_message_history=full_message_history,
loop_count += 1 next_action_count=next_action_count,
if cfg.continuous_mode and cfg.continuous_limit > 0 and loop_count > cfg.continuous_limit: prompt=prompt,
logger.typewriter_log("Continuous Limit Reached: ", Fore.YELLOW, f"{cfg.continuous_limit}") user_input=user_input
break )
agent.start_interaction_loop()
# Send message to AI, get response
with Spinner("Thinking... "):
assistant_reply = chat.chat_with_ai(
prompt,
user_input,
full_message_history,
memory,
cfg.fast_token_limit) # TODO: This hardcodes the model to use GPT3.5. Make this an argument
# Print Assistant thoughts class Agent:
print_assistant_thoughts(assistant_reply) """Agent class for interacting with Auto-GPT.
# Get command name and arguments Attributes:
try: ai_name: The name of the agent.
command_name, arguments = cmd.get_command( memory: The memory object to use.
attempt_to_fix_json_by_finding_outermost_brackets(assistant_reply)) full_message_history: The full message history.
if cfg.speak_mode: next_action_count: The number of actions to execute.
speak.say_text(f"I want to execute {command_name}") prompt: The prompt to use.
except Exception as e: user_input: The user input.
logger.error("Error: \n", str(e))
if not cfg.continuous_mode and next_action_count == 0: """
### GET USER AUTHORIZATION TO EXECUTE COMMAND ### def __init__(self,
# Get key press: Prompt the user to press enter to continue or escape ai_name,
# to exit memory,
user_input = "" full_message_history,
logger.typewriter_log( next_action_count,
"NEXT ACTION: ", prompt,
Fore.CYAN, user_input):
f"COMMAND = {Fore.CYAN}{command_name}{Style.RESET_ALL} ARGUMENTS = {Fore.CYAN}{arguments}{Style.RESET_ALL}") self.ai_name = ai_name
print( self.memory = memory
f"Enter 'y' to authorise command, 'y -N' to run N continuous commands, 'n' to exit program, or enter feedback for {ai_name}...", self.full_message_history = full_message_history
flush=True) self.next_action_count = next_action_count
while True: self.prompt = prompt
console_input = utils.clean_input(Fore.MAGENTA + "Input:" + Style.RESET_ALL) self.user_input = user_input
if console_input.lower().rstrip() == "y":
user_input = "GENERATE NEXT COMMAND JSON"
break
elif console_input.lower().startswith("y -"):
try:
next_action_count = abs(int(console_input.split(" ")[1]))
user_input = "GENERATE NEXT COMMAND JSON"
except ValueError:
print("Invalid input format. Please enter 'y -n' where n is the number of continuous tasks.")
continue
break
elif console_input.lower() == "n":
user_input = "EXIT"
break
else:
user_input = console_input
command_name = "human_feedback"
break
if user_input == "GENERATE NEXT COMMAND JSON": def start_interaction_loop(self):
logger.typewriter_log( # Interaction Loop
"-=-=-=-=-=-=-= COMMAND AUTHORISED BY USER -=-=-=-=-=-=-=", loop_count = 0
Fore.MAGENTA, while True:
"") # Discontinue if continuous limit is reached
elif user_input == "EXIT": loop_count += 1
print("Exiting...", flush=True) if cfg.continuous_mode and cfg.continuous_limit > 0 and loop_count > cfg.continuous_limit:
logger.typewriter_log("Continuous Limit Reached: ", Fore.YELLOW, f"{cfg.continuous_limit}")
break break
else:
# Print command
logger.typewriter_log(
"NEXT ACTION: ",
Fore.CYAN,
f"COMMAND = {Fore.CYAN}{command_name}{Style.RESET_ALL} ARGUMENTS = {Fore.CYAN}{arguments}{Style.RESET_ALL}")
# Execute command # Send message to AI, get response
if command_name is not None and command_name.lower().startswith("error"): with Spinner("Thinking... "):
result = f"Command {command_name} threw the following error: " + arguments assistant_reply = chat.chat_with_ai(
elif command_name == "human_feedback": self.prompt,
result = f"Human feedback: {user_input}" self.user_input,
else: self.full_message_history,
result = f"Command {command_name} returned: {cmd.execute_command(command_name, arguments)}" self.memory,
if next_action_count > 0: cfg.fast_token_limit) # TODO: This hardcodes the model to use GPT3.5. Make this an argument
next_action_count -= 1
memory_to_add = f"Assistant Reply: {assistant_reply} " \ # Print Assistant thoughts
f"\nResult: {result} " \ print_assistant_thoughts(assistant_reply)
f"\nHuman Feedback: {user_input} "
memory.add(memory_to_add) # Get command name and arguments
try:
command_name, arguments = cmd.get_command(
attempt_to_fix_json_by_finding_outermost_brackets(assistant_reply))
if cfg.speak_mode:
speak.say_text(f"I want to execute {command_name}")
except Exception as e:
logger.error("Error: \n", str(e))
# Check if there's a result from the command append it to the message if not cfg.continuous_mode and self.next_action_count == 0:
# history ### GET USER AUTHORIZATION TO EXECUTE COMMAND ###
if result is not None: # Get key press: Prompt the user to press enter to continue or escape
full_message_history.append(chat.create_chat_message("system", result)) # to exit
logger.typewriter_log("SYSTEM: ", Fore.YELLOW, result) self.user_input = ""
else: logger.typewriter_log(
full_message_history.append( "NEXT ACTION: ",
chat.create_chat_message( Fore.CYAN,
"system", "Unable to execute command")) f"COMMAND = {Fore.CYAN}{command_name}{Style.RESET_ALL} ARGUMENTS = {Fore.CYAN}{arguments}{Style.RESET_ALL}")
logger.typewriter_log("SYSTEM: ", Fore.YELLOW, "Unable to execute command") print(
f"Enter 'y' to authorise command, 'y -N' to run N continuous commands, 'n' to exit program, or enter feedback for {self.ai_name}...",
flush=True)
while True:
console_input = utils.clean_input(Fore.MAGENTA + "Input:" + Style.RESET_ALL)
if console_input.lower().rstrip() == "y":
self.user_input = "GENERATE NEXT COMMAND JSON"
break
elif console_input.lower().startswith("y -"):
try:
self.next_action_count = abs(int(console_input.split(" ")[1]))
self.user_input = "GENERATE NEXT COMMAND JSON"
except ValueError:
print("Invalid input format. Please enter 'y -n' where n is the number of continuous tasks.")
continue
break
elif console_input.lower() == "n":
self.user_input = "EXIT"
break
else:
self.user_input = console_input
command_name = "human_feedback"
break
if self.user_input == "GENERATE NEXT COMMAND JSON":
logger.typewriter_log(
"-=-=-=-=-=-=-= COMMAND AUTHORISED BY USER -=-=-=-=-=-=-=",
Fore.MAGENTA,
"")
elif self.user_input == "EXIT":
print("Exiting...", flush=True)
break
else:
# Print command
logger.typewriter_log(
"NEXT ACTION: ",
Fore.CYAN,
f"COMMAND = {Fore.CYAN}{command_name}{Style.RESET_ALL} ARGUMENTS = {Fore.CYAN}{arguments}{Style.RESET_ALL}")
# Execute command
if command_name is not None and command_name.lower().startswith("error"):
result = f"Command {command_name} threw the following error: " + arguments
elif command_name == "human_feedback":
result = f"Human feedback: {self.user_input}"
else:
result = f"Command {command_name} returned: {cmd.execute_command(command_name, arguments)}"
if self.next_action_count > 0:
self.next_action_count -= 1
memory_to_add = f"Assistant Reply: {assistant_reply} " \
f"\nResult: {result} " \
f"\nHuman Feedback: {self.user_input} "
self.memory.add(memory_to_add)
# Check if there's a result from the command append it to the message
# history
if result is not None:
self.full_message_history.append(chat.create_chat_message("system", result))
logger.typewriter_log("SYSTEM: ", Fore.YELLOW, result)
else:
self.full_message_history.append(
chat.create_chat_message(
"system", "Unable to execute command"))
logger.typewriter_log("SYSTEM: ", Fore.YELLOW, "Unable to execute command")
if __name__ == "__main__": if __name__ == "__main__":