Skip to content

Commit

Permalink
Add exception
Browse files Browse the repository at this point in the history
  • Loading branch information
TheExplainthis committed Mar 19, 2023
1 parent f039a0d commit 69809c9
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 21 deletions.
4 changes: 2 additions & 2 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ def handle_audio_message(event):

transciption, error_message = model_management[user_id].audio_transcriptions(input_audio_path, 'whisper-1')
if error_message:
os.remove(input_audio_path)
os.remove(input_audio_path)
line_bot_api.reply_message(event.reply_token, TextSendMessage(text=error_message))
return
memory.append(user_id, {
Expand All @@ -134,7 +134,7 @@ def handle_audio_message(event):

role, response, error_message = model_management[user_id].chat_completions(memory.get(user_id), 'gpt-3.5-turbo')
if error_message:
os.remove(input_audio_path)
os.remove(input_audio_path)
line_bot_api.reply_message(event.reply_token, TextSendMessage(text=error_message))
memory.remove(user_id)
return
Expand Down
54 changes: 35 additions & 19 deletions src/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,29 +28,45 @@ def __init__(self, api_key: str):
self.base_url = 'https://api.openai.com/v1'

def check_token_valid(self):
r = requests.get('https://api.openai.com/v1/models', headers=self.headers)
if r.json().get('error'):
return False
return True
try:
r = requests.get('https://api.openai.com/v1/models', headers=self.headers)
r = r.json()
if r.get('error'):
return False, r.get('error', {}).get('message')
except Exception:
return False, 'OpenAI API 系統不穩定,請稍後再試'
return True, None

def _request(self, endpoint, body):
self.headers['Content-Type'] = 'application/json'
r = requests.post(f'{self.base_url}{endpoint}', headers=self.headers, json=body)
return r.json()
try:
self.headers['Content-Type'] = 'application/json'
r = requests.post(f'{self.base_url}{endpoint}', headers=self.headers, json=body)
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 _request_with_file(self, endpoint, files):
self.headers.pop('Content-Type', None)
r = requests.post(f'{self.base_url}{endpoint}', headers=self.headers, files=files)
return r.json()
try:
self.headers.pop('Content-Type', None)
r = requests.post(f'{self.base_url}{endpoint}', headers=self.headers, 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 chat_completions(self, messages, model_engine) -> str:
json_body = {
'model': model_engine,
'messages': messages
}
r = self._request('/chat/completions', body=json_body)
if r.get('error'):
return None, None, r.get('error', {}).get('message', '')
is_successful, r, error_message = self._request('/chat/completions', body=json_body)
if not is_successful:
return None, None, error_message
role = r['choices'][0]['message']['role']
content = r['choices'][0]['message']['content'].strip()
response = s2t_converter.convert(content)
Expand All @@ -61,9 +77,9 @@ def audio_transcriptions(self, file_path, model_engine) -> str:
'file': open(file_path, 'rb'),
'model': (None, 'whisper-1'),
}
r = self._request_with_file('/audio/transcriptions', files)
if r.get('error'):
return None, r.get('error', {}).get('message', '')
is_successful, r, error_message = self._request_with_file('/audio/transcriptions', files)
if not is_successful:
return None, error_message
return r['text'], None

def image_generations(self, prompt: str) -> str:
Expand All @@ -72,7 +88,7 @@ def image_generations(self, prompt: str) -> str:
"n": 1,
"size": "512x512"
}
r = self._request('/images/generations', json_body)
if r.get('error'):
return None, r.get('error', {}).get('message', '')
is_successful, r, error_message = self._request('/images/generations', json_body)
if not is_successful:
return None, error_message
return r['data'][0]['url'], None

0 comments on commit 69809c9

Please sign in to comment.