parse json error

This commit is contained in:
Michael Yang 2024-01-10 17:02:49 -08:00
parent 7c2ec01d2f
commit 64127ee821
2 changed files with 23 additions and 0 deletions

View File

@ -68,3 +68,18 @@ async def chat():
asyncio.run(chat())
```
## Handling Errors
Errors are raised if requests return an error status or if an error is detected while streaming.
```python
model = 'does-not-yet-exist'
try:
ollama.chat(model)
except ollama.ResponseError as e:
print('Error:', e.content)
if e.status_code == 404:
ollama.pull(model)
```

View File

@ -1,3 +1,4 @@
import json
from typing import Any, TypedDict, Sequence, Literal
import sys
@ -145,6 +146,13 @@ class ResponseError(Exception):
"""
def __init__(self, content: str, status_code: int = -1):
try:
# try to parse content as JSON and extract 'error'
# fallback to raw content if JSON parsing fails
content = json.loads(content).get('error', content)
except json.JSONDecodeError:
...
super().__init__(content)
self.content = content
"Reason for the error."