ecoute/GPTResponder.py

51 lines
1.7 KiB
Python
Raw Normal View History

2023-05-08 02:10:48 +00:00
import openai
from keys import OPENAI_API_KEY
2023-05-09 23:06:49 +00:00
from prompts import create_prompt, INITIAL_RESPONSE
import time
2023-05-08 02:10:48 +00:00
openai.api_key = OPENAI_API_KEY
2023-05-09 21:07:51 +00:00
def generate_response_from_transcript(transcript):
2023-05-13 20:04:35 +00:00
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo-0301",
messages=[{"role": "system", "content": create_prompt(transcript)}],
temperature = 0.0
)
except openai.OpenAIError:
print("An error occurred while calling OpenAI ChatCompletion.")
return ''
2023-05-09 21:07:51 +00:00
full_response = response.choices[0].message.content
try:
return full_response.split('[')[1].split(']')[0]
except:
2023-05-09 23:06:49 +00:00
return ''
class GPTResponder:
def __init__(self):
self.response = INITIAL_RESPONSE
self.response_interval = 2
def respond_to_transcriber(self, transcriber):
while True:
if transcriber.transcript_changed_event.is_set():
2023-05-13 15:41:10 +00:00
start_time = time.time()
2023-05-09 23:06:49 +00:00
transcriber.transcript_changed_event.clear()
transcript_string = transcriber.get_transcript()
response = generate_response_from_transcript(transcript_string)
2023-05-13 15:41:10 +00:00
end_time = time.time() # Measure end time
execution_time = end_time - start_time # Calculate the time it took to execute the function
2023-05-09 23:06:49 +00:00
if response != '':
self.response = response
2023-05-13 15:41:10 +00:00
remaining_time = self.response_interval - execution_time
if remaining_time > 0:
time.sleep(remaining_time)
2023-05-09 23:33:15 +00:00
else:
time.sleep(0.3)
2023-05-09 23:06:49 +00:00
def update_response_interval(self, interval):
self.response_interval = interval