forked from TheExplainthis/ChatGPT-Line-Bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
models.py
65 lines (53 loc) · 2.08 KB
/
models.py
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
from typing import List, Dict
import requests
class ModelInterface:
def check_token_valid(self) -> bool:
pass
def chat_completions(self, messages: List[Dict], model_engine: str) -> str:
pass
def audio_transcriptions(self, file, model_engine: str) -> str:
pass
def image_generations(self, prompt: str) -> str:
pass
class OpenAIModel(ModelInterface):
def __init__(self, api_key: str):
self.api_key = api_key
self.base_url = 'https://api.openai.com/v1'
def _request(self, method, endpoint, body=None, files=None):
self.headers = {
'Authorization': f'Bearer {self.api_key}'
}
try:
if method == 'GET':
r = requests.get(f'{self.base_url}{endpoint}', headers=self.headers)
elif method == 'POST':
if body:
self.headers['Content-Type'] = 'application/json'
r = requests.post(f'{self.base_url}{endpoint}', headers=self.headers, json=body, files=files)
r = r.json()
if r.get('error'):
return False, None, r.get('error', {}).get('message')
except Exception:
return False, None, 'OpenAI API 系統不穩定,請稍後再試'
return True, r, None
def check_token_valid(self):
return self._request('GET', '/models')
def chat_completions(self, messages, model_engine) -> str:
json_body = {
'model': model_engine,
'messages': messages
}
return self._request('POST', '/chat/completions', body=json_body)
def audio_transcriptions(self, file_path, model_engine) -> str:
files = {
'file': open(file_path, 'rb'),
'model': (None, model_engine),
}
return self._request('POST', '/audio/transcriptions', files=files)
def image_generations(self, prompt: str) -> str:
json_body = {
"prompt": prompt,
"n": 1,
"size": "512x512"
}
return self._request('POST', '/images/generations', body=json_body)