jarvis-server-v2/jarvis/utils/chatgpt_utils.py
2023-03-26 12:01:41 +02:00

69 lines
2.2 KiB
Python

import json
import logging
import time
import openai
chat_messages = {}
def chatgpt_recognise(text, uuid):
if len(chat_messages) == 0:
chatgpt_init(uuid)
chat_messages[uuid].append({"role": "user", "content": text})
# Call ChatGPT API
start_time = time.time()
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=chat_messages[uuid],
)
end_time = time.time()
logging.info("GPT-3 response in " + str(end_time - start_time) + " seconds")
# Check if the response is a "valid" JSON
try:
response = json.loads(str(response.choices[0].message.content))
if 'action' in response:
chat_messages[uuid].append({"role": "assistant", "content": get_answer_from_response(response)})
return response
except Exception as e:
logging.error("Error while parsing ChatGPT response, probably not JSON: " + str(response.choices))
logging.error(str(e))
return {"action": "answer", "answer": get_answer_from_response(response)}
def clear_chat(uuid):
logging.info("Cleared chat for uuid " + uuid)
chat_messages[uuid] = []
def get_answer_from_response(response):
if 'action' not in response:
# Fix for when it responds in plaintext to follow-up questions
# In that case the response is an OpenAIObject not a JSON
return response.choices[0].message.content
else:
if response['action'] == 'clarify':
return response['question']
elif response['action'] == 'command':
return response['comment']
elif response['action'] == 'query':
return response['device_description']
elif response['action'] == 'answer':
return response['answer']
else:
return "I don't know how to respond to that..."
def chatgpt_init(uuid):
prompt = open("utils/chatgpt_prompt_2_smaller.txt", "r").read()
prompt.replace("{{timestamp}}", time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
prompt.replace("{{location}}", "Lausanne in the canton Vaud of Switzerland")
chat_messages[uuid] = []
chat_messages[uuid].append({"role": "system", "content": prompt})