Bitsak/AutoGPT2
0
1import os, sys2import utils3import uuid4import json5import subprocess, threading6 7FILE_DIR = os.path.dirname(os.path.abspath(__file__))8REPO_DIR = os.path.dirname(FILE_DIR)9STATE_DIR = os.path.join(FILE_DIR, "state") 10sys.path.append(REPO_DIR)11if not os.path.exists(STATE_DIR):12 os.mkdir(STATE_DIR)13import time14 15 16def get_openai_api_key():17 return os.getenv("OPENAI_API_KEY")18 19 20running_apis = []21 22 23def get_state(state_file):24 with open(state_file, "r") as f:25 state = json.load(f)26 return state27 28 29def set_state(state_file, state):30 with open(state_file, "w") as f:31 json.dump(state, f)32 33 34class AutoAPI:35 def __init__(self, openai_key, ai_name, ai_role, top_5_goals):36 self.openai_key = openai_key37 hex = uuid.uuid4().hex38 print(hex)39 self.state_file = os.path.join(STATE_DIR, f"state_{hex}.json")40 self.log_file = os.path.join(STATE_DIR, f"log_{hex}.json")41 42 newline = "\n"43 with open(os.path.join(REPO_DIR, "ai_settings.yaml"), "w") as f:44 f.write(45 f"""ai_goals:46{newline.join([f'- {goal[0]}' for goal in top_5_goals if goal[0]])}47ai_name: {ai_name}48ai_role: {ai_role}49"""50 )51 state = {52 "pending_input": None,53 "awaiting_input": False,54 "messages": [],55 "last_message_read_index": -1,56 }57 set_state(self.state_file, state)58 59 with open(self.log_file, "w") as f:60 subprocess.Popen(61 [62 "python",63 os.path.join(REPO_DIR, "ui", "api.py"),64 openai_key,65 self.state_file,66 ],67 cwd=REPO_DIR,68 stdout=f,69 stderr=f,70 )71 72 def send_message(self, message="Y"):73 state = get_state(self.state_file)74 state["pending_input"] = message75 state["awaiting_input"] = False76 set_state(self.state_file, state)77 78 def get_chatbot_response(self):79 while True:80 state = get_state(self.state_file)81 if (82 state["awaiting_input"]83 and state["last_message_read_index"] >= len(state["messages"]) - 184 ):85 break86 if state["last_message_read_index"] >= len(state["messages"]) - 1:87 time.sleep(1)88 else:89 state["last_message_read_index"] += 190 title, content = state["messages"][state["last_message_read_index"]]91 yield (f"**{title.strip()}** " if title else "") + utils.remove_color(92 content93 ).replace("\n", "<br />")94 set_state(self.state_file, state)95 96 97if __name__ == "__main__":98 print(sys.argv)99 _, openai_key, state_file = sys.argv100 os.environ["OPENAI_API_KEY"] = openai_key101 import autogpt.config.config102 from autogpt.logs import logger103 from autogpt.cli import main104 import autogpt.utils105 from autogpt.spinner import Spinner106 107 def add_message(title, content):108 state = get_state(state_file)109 state["messages"].append((title, content))110 set_state(state_file, state)111 112 def typewriter_log(title="", title_color="", content="", *args, **kwargs):113 add_message(title, content)114 115 def warn(message, title="", *args, **kwargs):116 add_message(title, message)117 118 def error(title, message="", *args, **kwargs):119 add_message(title, message)120 121 def clean_input(prompt=""):122 add_message(None, prompt)123 state = get_state(state_file)124 state["awaiting_input"] = True125 set_state(state_file, state)126 while state["pending_input"] is None:127 state = get_state(state_file)128 print("Waiting for input...")129 time.sleep(1)130 print("Got input")131 pending_input = state["pending_input"]132 state["pending_input"] = None133 set_state(state_file, state)134 return pending_input135 136 def spinner_start():137 add_message(None, "Thinking...")138 139 logger.typewriter_log = typewriter_log140 logger.warn = warn141 logger.error = error142 autogpt.utils.clean_input = clean_input143 Spinner.spin = spinner_start144 145 sys.argv = sys.argv[:1]146 main()147 