75 lines
2.0 KiB
Python
75 lines
2.0 KiB
Python
import os
|
|
import sys
|
|
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
|
import json
|
|
import ast
|
|
|
|
import openai
|
|
|
|
from commander.commands import CommandHandler
|
|
from settings.config import settings
|
|
|
|
|
|
|
|
class CloudSTTBrain:
|
|
def __init__(self):
|
|
print("not implemented")
|
|
|
|
|
|
class CloudChatBrain:
|
|
def __init__(self):
|
|
openai.api_key = settings.OPENAI_API_KEY
|
|
self.command_handler = CommandHandler()
|
|
|
|
@property
|
|
def sys_prompt(self):
|
|
return self._read_prompt()
|
|
|
|
def _read_prompt(self):
|
|
prompt_file_name = "prompt.txt"
|
|
for root, dirs, files in os.walk("./"):
|
|
if prompt_file_name in files:
|
|
prompt_filepath = os.path.join(root, prompt_file_name)
|
|
with open(prompt_filepath, "r") as f:
|
|
return f.read()
|
|
|
|
def _is_valid_json(self, answer):
|
|
try:
|
|
response_json = json.loads(answer)
|
|
return True
|
|
except ValueError as e:
|
|
print(f"chatgpt failed to return json obj: {answer}")
|
|
return False
|
|
|
|
def _gc(self):
|
|
self.cmd_prompt = None
|
|
self.response = None
|
|
|
|
def listen(self):
|
|
self.cmd_prompt = input("\n\nwhat should I do now?\n\t")
|
|
|
|
def understand(self):
|
|
self.response = openai.ChatCompletion.create(
|
|
model="gpt-3.5-turbo",
|
|
temperature=0.2,
|
|
messages=[
|
|
{"role": "system", "content": self.sys_prompt},
|
|
{"role": "user", "content": self.cmd_prompt}
|
|
])
|
|
|
|
def command(self):
|
|
answer = self.response.choices[0].message.content
|
|
if self._is_valid_json(answer):
|
|
command = ast.literal_eval(answer)
|
|
if command == {}:
|
|
print(f"I failed to understand: {command}")
|
|
else:
|
|
print(f"I will send this command: {command}")
|
|
self.command_handler.handle(command)
|
|
else:
|
|
print(f"\tI will skip this:\n {command}")
|
|
self._gc()
|
|
|
|
|
|
|