Spaces:
Sleeping
Sleeping
File size: 1,394 Bytes
478965d 4831f4c 478965d 4831f4c |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
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
|