diff --git a/README.md b/README.md index f5357ec..12b6a1d 100644 --- a/README.md +++ b/README.md @@ -338,6 +338,19 @@ except FishAudioError as e: print(f"API error: {e}") ``` +Every `APIError` carries the headers of the error response. When you contact support, include the trace id and the error code. Either can be absent. + +```python +from fishaudio.exceptions import APIError + +try: + audio = client.tts.convert(text="Hello!") +except APIError as e: + print(e.headers.get("x-fish-trace-id"), e.headers.get("x-fish-error-code")) +``` + +A `tts.stream_websocket` handshake that the server refuses raises `httpx_ws.WebSocketUpgradeError`; read the same headers from `e.response.headers`. + ### Trace IDs Responses to speech and transcription requests carry an `x-fish-trace-id` header. Include it when you contact support about a request, also one that succeeded but sounds wrong. The stream that `tts.stream()` returns has the response headers: @@ -352,6 +365,7 @@ finally: The same `headers` attribute is on the streams of `tts.stream_with_timestamps()` and `asr.stream_websocket()` (empty until the connection opens on the first iteration), and on the results of `tts.convert_with_timestamps()` and `asr.transcribe()` (the latter also has `request_id`). `tts.convert()` returns only the audio; use `tts.stream()` as above when you need the headers. `tts.stream_websocket()` does not expose them yet. + ## Resources - **Documentation:** [SDK Guide](https://docs.fish.audio/developer-guide/sdk-guide/python/) | [API Reference](https://docs.fish.audio/api-reference/sdk/python/) diff --git a/src/fishaudio/core/client_wrapper.py b/src/fishaudio/core/client_wrapper.py index 4bda311..c98d432 100644 --- a/src/fishaudio/core/client_wrapper.py +++ b/src/fishaudio/core/client_wrapper.py @@ -21,19 +21,25 @@ from .request_options import RequestOptions -def _api_error(status: int, message: str, body: Optional[str] = None) -> APIError: +def _api_error( + status: int, + message: str, + body: Optional[str] = None, + headers: Optional[httpx.Headers] = None, +) -> APIError: """Build the exception that matches an HTTP error status.""" + error_class = APIError if status == 401: - return AuthenticationError(status, message, body) - if status == 403: - return PermissionError(status, message, body) - if status == 404: - return NotFoundError(status, message, body) - if status == 429: - return RateLimitError(status, message, body) - if status >= 500: - return ServerError(status, message, body) - return APIError(status, message, body) + error_class = AuthenticationError + elif status == 403: + error_class = PermissionError + elif status == 404: + error_class = NotFoundError + elif status == 429: + error_class = RateLimitError + elif status >= 500: + error_class = ServerError + return error_class(status, message, body, headers) def _read_error_body(response: httpx.Response) -> tuple[Any, str]: @@ -76,7 +82,10 @@ def _raise_for_status(response: httpx.Response) -> None: message = data.get("message") or data.get("detail") raise _api_error( - status, message or text or httpx.codes.get_reason_phrase(status), text + status, + message or text or httpx.codes.get_reason_phrase(status), + text, + response.headers, ) diff --git a/src/fishaudio/exceptions.py b/src/fishaudio/exceptions.py index e8ac4ac..ae8521b 100644 --- a/src/fishaudio/exceptions.py +++ b/src/fishaudio/exceptions.py @@ -1,7 +1,10 @@ """Custom exceptions for the Fish Audio SDK.""" +from collections.abc import Mapping from typing import Optional +import httpx + class FishAudioError(Exception): """Base exception for all Fish Audio SDK errors.""" @@ -10,12 +13,31 @@ class FishAudioError(Exception): class APIError(FishAudioError): - """Raised when the API returns an error response.""" + """Raised when the API returns an error response. + + Attributes: + status: HTTP status code + message: Error message from the response, or the HTTP reason phrase + for a refused WebSocket handshake + body: Response body, if it was read + headers: Headers of the error response (empty if there are none) + """ - def __init__(self, status: int, message: str, body: Optional[str] = None): + def __init__( + self, + status: int, + message: str, + body: Optional[str] = None, + headers: Optional[Mapping[str, str]] = None, + ): self.status = status self.message = message self.body = body + if isinstance(headers, httpx.Headers): + self.headers = headers.copy() + else: + # httpx encodes str values as ASCII unless told otherwise. + self.headers = httpx.Headers(headers, encoding="utf-8") super().__init__(f"HTTP {status}: {message}") diff --git a/src/fishaudio/resources/asr_realtime.py b/src/fishaudio/resources/asr_realtime.py index cf7b6f3..eea64ef 100644 --- a/src/fishaudio/resources/asr_realtime.py +++ b/src/fishaudio/resources/asr_realtime.py @@ -133,7 +133,11 @@ def _upgrade_error(response: httpx.Response) -> Exception: """The WebSocket upgrade was refused (401, 402, 429, ...): map the HTTP status.""" status = response.status_code # httpx-ws closes the response before the body can be read. - return _api_error(status, httpx.codes.get_reason_phrase(status) or "Upgrade failed") + return _api_error( + status, + httpx.codes.get_reason_phrase(status) or "Upgrade failed", + headers=response.headers, + ) def _handshake_headers( diff --git a/tests/unit/realtime_server.py b/tests/unit/realtime_server.py index cf1c48b..2a77bf5 100644 --- a/tests/unit/realtime_server.py +++ b/tests/unit/realtime_server.py @@ -34,6 +34,13 @@ } +# Test values, sent with every handshake this server refuses. +REJECT_HEADERS = [ + (b"x-fish-trace-id", b"trace-123"), + (b"x-fish-error-code", b"invalid_api_key"), +] + + class ClientGone(Exception): """The client closed the connection.""" @@ -74,7 +81,11 @@ def _read(self) -> None: self.path = event.target self.headers = {k.decode(): v.decode() for k, v in event.extra_headers} if self._reject_status is not None: - self._write(RejectConnection(status_code=self._reject_status)) + self._write( + RejectConnection( + status_code=self._reject_status, headers=REJECT_HEADERS + ) + ) raise ClientGone self._write(AcceptConnection(extra_headers=ACCEPT_HEADERS)) elif isinstance(event, BytesMessage): diff --git a/tests/unit/test_asr_realtime.py b/tests/unit/test_asr_realtime.py index f068acb..065b68e 100644 --- a/tests/unit/test_asr_realtime.py +++ b/tests/unit/test_asr_realtime.py @@ -700,6 +700,8 @@ def test_refused_upgrade_raises_api_error(self, status, error_class): ): list(client.asr.stream_websocket(iter([CHUNK]))) assert exc_info.value.status == status + assert exc_info.value.headers["x-fish-trace-id"] == "trace-123" + assert exc_info.value.headers["x-fish-error-code"] == "invalid_api_key" def test_leaving_the_loop_early_closes_the_connection(self): with serving(open_ended_script) as (server, client): @@ -1082,6 +1084,8 @@ async def test_refused_upgrade_raises_api_error(self, status, error_class): async for _ in client.asr.stream_websocket(aiter_chunks(CHUNK)): pass assert exc_info.value.status == status + assert exc_info.value.headers["x-fish-trace-id"] == "trace-123" + assert exc_info.value.headers["x-fish-error-code"] == "invalid_api_key" async def test_leaving_the_loop_early_closes_the_connection(self): async with aserving(open_ended_script) as (server, client): diff --git a/tests/unit/test_error_headers.py b/tests/unit/test_error_headers.py new file mode 100644 index 0000000..785a86f --- /dev/null +++ b/tests/unit/test_error_headers.py @@ -0,0 +1,181 @@ +"""An APIError carries the headers of the error response. + +The tests run the real client against a local HTTP server, and a refused +WebSocket handshake against the scripted server in realtime_server.py. +""" + +import contextlib +import threading +from http.server import BaseHTTPRequestHandler, HTTPServer + +import httpx +import pytest +from httpx_ws import WebSocketUpgradeError + +from fishaudio import APIError, AsyncFishAudio, AuthenticationError, FishAudio +from fishaudio.core.client_wrapper import _raise_for_status +from fishaudio.exceptions import ( + NotFoundError, + PermissionError, + RateLimitError, + ServerError, +) + +from .realtime_server import RealtimeServer + + +class _Refuse(BaseHTTPRequestHandler): + """401 with the API's diagnostic headers on /v1, a bare 404 elsewhere.""" + + def _respond(self): + self.rfile.read(int(self.headers.get("content-length", 0))) + if self.path.startswith("/v1/"): + body = b'{"status":401,"message":"Invalid Token"}' + self.send_response(401) + self.send_header("x-fish-trace-id", "trace-123") + self.send_header("x-fish-error-code", "invalid_api_key") + else: + body = b'{"status":404,"message":"Not found"}' + self.send_response(404) + self.send_header("x-detail", "café") + self.send_header("content-type", "application/json") + self.send_header("content-length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + do_GET = do_POST = _respond + + def log_message(self, *args): + pass + + +@contextlib.contextmanager +def refusing_server(): + server = HTTPServer(("127.0.0.1", 0), _Refuse) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + yield f"http://127.0.0.1:{server.server_port}" + finally: + server.shutdown() + server.server_close() + thread.join() + + +def test_http_error_carries_the_response_headers(): + with ( + refusing_server() as url, + FishAudio(api_key="k", base_url=url) as client, + pytest.raises(AuthenticationError) as exc_info, + ): + client.tts.convert(text="hi") + error = exc_info.value + assert error.status == 401 + assert error.message == "Invalid Token" + assert error.headers["x-fish-trace-id"] == "trace-123" + assert error.headers["X-Fish-Error-Code"] == "invalid_api_key" # any casing + + +async def test_http_error_carries_the_response_headers_async(): + with refusing_server() as url: + async with AsyncFishAudio(api_key="k", base_url=url) as client: + with pytest.raises(AuthenticationError) as exc_info: + await client.tts.convert(text="hi") + assert exc_info.value.headers["x-fish-trace-id"] == "trace-123" + + +def test_headers_the_response_does_not_have_are_absent(): + with ( + refusing_server() as url, + FishAudio(api_key="k", base_url=url) as client, + pytest.raises(APIError) as exc_info, + ): + client.account.get_credits() + assert exc_info.value.status == 404 + assert exc_info.value.headers["content-type"] == "application/json" + assert exc_info.value.headers.get("x-fish-trace-id") is None + + +async def test_headers_the_response_does_not_have_are_absent_async(): + with refusing_server() as url: + async with AsyncFishAudio(api_key="k", base_url=url) as client: + with pytest.raises(APIError) as exc_info: + await client.account.get_credits() + assert exc_info.value.status == 404 + assert exc_info.value.headers["content-type"] == "application/json" + assert exc_info.value.headers.get("x-fish-trace-id") is None + + +def test_a_header_value_outside_ascii_arrives_as_sent(): + with ( + refusing_server() as url, + FishAudio(api_key="k", base_url=url) as client, + pytest.raises(APIError) as exc_info, + ): + client.account.get_credits() + assert exc_info.value.headers["x-detail"] == "café" + + +def test_error_built_by_hand_takes_a_header_value_outside_ascii(): + error = APIError(400, "Bad Request", headers={"x-detail": "café"}) + assert error.headers["x-detail"] == "café" + + +def test_error_built_without_headers_has_empty_headers(): + error = APIError(400, "Bad Request") + assert error.headers.get("x-fish-trace-id") is None + assert len(error.headers) == 0 + + +def test_refused_tts_websocket_exposes_the_headers_on_the_upgrade_error(): + """The README's second path: tts.stream_websocket is not wrapped.""" + server = RealtimeServer(lambda conn: None, reject_status=401) + try: + with ( + FishAudio(api_key="k", base_url=server.url) as client, + pytest.raises(WebSocketUpgradeError) as exc_info, + ): + list(client.tts.stream_websocket(iter(["hi"]))) + finally: + server.close() + assert exc_info.value.response.status_code == 401 + assert exc_info.value.response.headers["x-fish-trace-id"] == "trace-123" + + +@pytest.mark.parametrize( + ("status", "error_class"), + [ + (400, APIError), + (401, AuthenticationError), + (403, PermissionError), + (404, NotFoundError), + (429, RateLimitError), + (503, ServerError), + ], +) +def test_every_error_class_carries_the_headers(status, error_class): + response = httpx.Response( + status, + headers={"x-fish-trace-id": "trace-123"}, + json={"message": "refused"}, + request=httpx.Request("GET", "https://api.fish.audio/v1/tts"), + ) + + with pytest.raises(APIError) as caught: + _raise_for_status(response) + + assert type(caught.value) is error_class + assert caught.value.headers["x-fish-trace-id"] == "trace-123" + + +@pytest.mark.parametrize("body", [b"null", b"[]", b"not json"]) +def test_an_error_whose_body_is_not_an_object_carries_the_headers(body): + response = httpx.Response( + 500, + headers={"x-fish-trace-id": "trace-123"}, + content=body, + request=httpx.Request("POST", "https://api.fish.audio/v1/tts"), + ) + with pytest.raises(APIError) as caught: + _raise_for_status(response) + assert caught.value.headers["x-fish-trace-id"] == "trace-123"