DAN_AI / openai.py
oliverwang15's picture
updates on the submit button
772f8cb
import requests
class OpenAI:
def __init__(self, init_prompt = None):
self.history = []
if init_prompt is not None:
self.history.append({'role': 'system', 'content': init_prompt})
def clear_history(self):
self.history = []
def show_history(self):
for message in self.history:
print(f"{message['role']}: {message['content']}")
def get_raw_history(self):
return self.history
def __call__(self, prompt, with_history = False, model = 'gpt-3.5-turbo', temperature = 0, api_key = None):
URL = 'https://api.openai.com/v1/chat/completions'
new_message = {'role': 'user', 'content': prompt}
if with_history:
self.history.append(new_message)
messages = self.history
else:
messages = [new_message]
resp = requests.post(URL, json={
'model': model,
'messages': messages,
'temperature': temperature,
}, headers={
'Authorization': f"Bearer {api_key}"
})
self.history.append(resp.json()['choices'][0]['message'])
res = resp.json()['choices'][0]['message']['content']
# with open("tmp_res.txt", 'w') as f:
# f.write(res)
# with open("tmp_res.txt", 'r') as f:
# res = f.read()
return res