Merge pull request #20 from Gadzhi07/master

chat-gpt-3.5-turbo fix
This commit is contained in:
Abraham Tugalov 2023-04-17 21:07:13 +05:00 committed by GitHub
commit a0c1a1f0d1
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

21
main.py
View file

@ -10,6 +10,7 @@ import time
from ctypes import POINTER, cast from ctypes import POINTER, cast
import openai import openai
from openai import error
import pvporcupine import pvporcupine
import simpleaudio as sa import simpleaudio as sa
import vosk import vosk
@ -33,11 +34,8 @@ VA_CMD_LIST = yaml.safe_load(
) )
# ChatGPT vars # ChatGPT vars
message_log = [ system_message = {"role": "system", "content": "Ты голосовой ассистент из железного человека."}
{"role": "system", "content": "Ты голосовой ассистент из железного человека."} message_log = [system_message]
]
# Set a flag to keep track of whether this is the first request in the conversation
first_request = True
# init openai # init openai
openai.api_key = config.OPENAI_TOKEN openai.api_key = config.OPENAI_TOKEN
@ -63,6 +61,7 @@ def gpt_answer():
model_engine = "gpt-3.5-turbo" model_engine = "gpt-3.5-turbo"
max_tokens = 256 # default 1024 max_tokens = 256 # default 1024
try:
response = openai.ChatCompletion.create( response = openai.ChatCompletion.create(
model=model_engine, model=model_engine,
messages=message_log, messages=message_log,
@ -71,6 +70,15 @@ def gpt_answer():
top_p=1, top_p=1,
stop=None stop=None
) )
except (error.TryAgain, error.ServiceUnavailableError):
return "ChatGPT перегружен!"
except openai.OpenAIError as ex:
# если ошибка - это макс длина контекста, то возвращаем ответ с очищенным контекстом
if ex.code == "context_length_exceeded":
message_log = [system_message, message_log[-1]]
return gpt_answer()
else:
return "OpenAI токен не рабочий."
# Find the first response from the chatbot that has text in it (some responses may not have text) # Find the first response from the chatbot that has text in it (some responses may not have text)
for choice in response.choices: for choice in response.choices:
@ -138,10 +146,7 @@ def va_respond(voice: str):
# tts.va_speak("Что?") # tts.va_speak("Что?")
if fuzz.ratio(voice.join(voice.split()[:1]).strip(), "скажи") > 75: if fuzz.ratio(voice.join(voice.split()[:1]).strip(), "скажи") > 75:
if first_request:
message_log.append({"role": "user", "content": voice}) message_log.append({"role": "user", "content": voice})
first_request = False
response = gpt_answer() response = gpt_answer()
message_log.append({"role": "assistant", "content": response}) message_log.append({"role": "assistant", "content": response})