Skip to content
This repository has been archived by the owner on Dec 7, 2023. It is now read-only.

Commit

Permalink
Simplify error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
terry3041 committed Dec 6, 2022
1 parent c9606e4 commit 2978ec9
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 32 deletions.
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"

[project]
name = "pyChatGPT"
version = "0.0.6"
version = "0.0.7"
authors = [
{ name="terry3041", email="[email protected]" },
]
Expand Down
46 changes: 15 additions & 31 deletions src/pyChatGPT/pyChatGPT.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,19 +33,12 @@ def refresh_auth(self) -> None:
headers=self.headers,
)
if resp.status_code != 200:
raise ValueError(f'Status code {resp.status_code}')
try:
data = resp.json()
except Exception:
print(resp.text)
raise ValueError('Unknown error')
raise ValueError(f'Status code {resp.status_code}')

data = resp.json()
if not data:
raise ValueError('Invalid session token')
if 'error' in data:
if data['error'] == 'RefreshAccessTokenError':
raise ValueError('Token expired')
raise ValueError(data['error'])
access_token = data['accessToken']
self.headers['Authorization'] = f'Bearer {access_token}'

Expand Down Expand Up @@ -82,27 +75,18 @@ def send_message(self, message: str) -> dict:
'parent_message_id': self.parent_id,
'model': 'text-davinci-002-render',
},
stream=True,
)
try:
data = list(resp.iter_lines())[-4].decode('utf-8').lstrip('data: ')
data = json.loads(data)
self.conversation_id = data['conversation_id']
self.parent_id = data['message']['id']
return {
'message': data['message']['content']['parts'][0],
'conversation_id': self.conversation_id,
'parent_id': self.parent_id,
}
except IndexError:
data = resp.json()
if 'detail' in data:
if (
'code' in data['detail']
and data['detail']['code'] == 'token_expired'
):
raise ValueError('Token expired')
print(data)
raise ValueError('Unknown error')
except Exception:
if resp.status_code != 200:
print(resp.text)
raise ValueError('Unknown error')
raise ValueError(f'Status code {resp.status_code}')

data = list(resp.iter_lines())[-4].decode('utf-8').lstrip('data: ')
data = json.loads(data)
self.conversation_id = data['conversation_id']
self.parent_id = data['message']['id']
return {
'message': data['message']['content']['parts'][0],
'conversation_id': self.conversation_id,
'parent_id': self.parent_id,
}

0 comments on commit 2978ec9

Please sign in to comment.