Files
tello-commander/brain/brain_openai.py

61 lines
1.5 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 brain_base import BaseBrain
from settings.config import settings
class CloudSTTBrain:
def __init__(self):
print("not implemented")
class CloudChatBrain(BaseBrain):
def __init__(self):
super().__init__()
openai.api_key = settings.OPENAI_API_KEY
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 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()