Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 3 additions & 8 deletions src/together/abstract/api_requestor.py
Original file line number Diff line number Diff line change
Expand Up @@ -335,19 +335,14 @@ def handle_error_response(
rcode: int,
stream_error: bool = False,
) -> Exception:
try:
assert isinstance(resp.data, dict)
error_resp = resp.data.get("error")
assert isinstance(
error_resp, dict
), f"Unexpected error response {error_resp}"
error_data = TogetherErrorResponse(**(error_resp))
except (KeyError, TypeError):
error_resp = resp.data.get("error") if isinstance(resp.data, dict) else None
if not isinstance(error_resp, dict):
raise error.JSONError(
"Invalid response object from API: %r (HTTP response code "
"was %d)" % (resp.data, rcode),
http_status=rcode,
)
error_data = TogetherErrorResponse(**error_resp)

utils.log_info(
"Together API error received",
Expand Down
40 changes: 40 additions & 0 deletions tests/unit/test_error_response_handling.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import pytest

from together.abstract.api_requestor import APIRequestor
from together.error import InvalidRequestError, JSONError, RateLimitError
from together.together_response import TogetherResponse


class TestHandleErrorResponse:
def test_detail_style_body_raises_json_error(self):
"""
FastAPI-style error bodies ({"detail": ...}) have no "error" object.
The SDK must raise JSONError, not a raw AssertionError.
"""
resp = TogetherResponse({"detail": "Not Found"}, {})

with pytest.raises(JSONError):
APIRequestor.handle_error_response(resp, 404)

def test_non_dict_error_field_raises_json_error(self):
resp = TogetherResponse({"error": "bad request"}, {})

with pytest.raises(JSONError):
APIRequestor.handle_error_response(resp, 400)

def test_non_dict_body_raises_json_error(self):
resp = TogetherResponse(["unexpected", "list"], {})

with pytest.raises(JSONError):
APIRequestor.handle_error_response(resp, 500)

def test_valid_error_body_maps_status_codes(self):
body = {"error": {"message": "rate limited", "type": "rate_limit"}}
resp = TogetherResponse(body, {})

assert isinstance(
APIRequestor.handle_error_response(resp, 429), RateLimitError
)
assert isinstance(
APIRequestor.handle_error_response(resp, 400), InvalidRequestError
)