Skip to content

Commit

Permalink
feat(python/sdk): Add info about HTTP response status code (#7653)
Browse files Browse the repository at this point in the history
GitOrigin-RevId: c6fc606f037f04da42872e72797fe66ca441b19e
  • Loading branch information
ploeber committed Dec 20, 2024
1 parent 22690b5 commit 8fb9523
Show file tree
Hide file tree
Showing 7 changed files with 249 additions and 70 deletions.
26 changes: 26 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -937,6 +937,32 @@ The asynchronous approach allows the application to continue running while the t

You can identify those two approaches by the `_async` suffix in the `Transcriber`'s method name (e.g. `transcribe` vs `transcribe_async`).

## Getting the HTTP status code

There are two ways of accessing the HTTP status code:

- All custom AssemblyAI Error classes have a `status_code` attribute.
- The latest HTTP response is stored in `aai.Client.get_default().latest_response` after every API call. This approach works also if no Exception is thrown.

```python
transcriber = aai.Transcriber()

# Option 1: Catch the error
try:
transcript = transcriber.submit("./example.mp3")
except aai.AssemblyAIError as e:
print(e.status_code)

# Option 2: Access the latest response through the client
client = aai.Client.get_default()

try:
transcript = transcriber.submit("./example.mp3")
except:
print(client.last_response)
print(client.last_response.status_code)
```

## Polling Intervals

By default we poll the `Transcript`'s status each `3s`. In case you would like to adjust that interval:
Expand Down
2 changes: 1 addition & 1 deletion assemblyai/__version__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = "0.35.1"
__version__ = "0.36.0"
56 changes: 38 additions & 18 deletions assemblyai/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,8 @@ def create_transcript(
)
if response.status_code != httpx.codes.OK:
raise types.TranscriptError(
f"failed to transcribe url {request.audio_url}: {_get_error_message(response)}"
f"failed to transcribe url {request.audio_url}: {_get_error_message(response)}",
response.status_code,
)

return types.TranscriptResponse.parse_obj(response.json())
Expand All @@ -60,6 +61,7 @@ def get_transcript(
if response.status_code != httpx.codes.OK:
raise types.TranscriptError(
f"failed to retrieve transcript {transcript_id}: {_get_error_message(response)}",
response.status_code,
)

return types.TranscriptResponse.parse_obj(response.json())
Expand All @@ -76,6 +78,7 @@ def delete_transcript(
if response.status_code != httpx.codes.OK:
raise types.TranscriptError(
f"failed to delete transcript {transcript_id}: {_get_error_message(response)}",
response.status_code,
)

return types.TranscriptResponse.parse_obj(response.json())
Expand All @@ -102,7 +105,8 @@ def upload_file(

if response.status_code != httpx.codes.OK:
raise types.TranscriptError(
f"Failed to upload audio file: {_get_error_message(response)}"
f"Failed to upload audio file: {_get_error_message(response)}",
response.status_code,
)

return response.json()["upload_url"]
Expand All @@ -127,7 +131,8 @@ def export_subtitles_srt(

if response.status_code != httpx.codes.OK:
raise types.TranscriptError(
f"failed to export SRT for transcript {transcript_id}: {_get_error_message(response)}"
f"failed to export SRT for transcript {transcript_id}: {_get_error_message(response)}",
response.status_code,
)

return response.text
Expand All @@ -152,7 +157,8 @@ def export_subtitles_vtt(

if response.status_code != httpx.codes.OK:
raise types.TranscriptError(
f"failed to export VTT for transcript {transcript_id}: {_get_error_message(response)}"
f"failed to export VTT for transcript {transcript_id}: {_get_error_message(response)}",
response.status_code,
)

return response.text
Expand All @@ -174,7 +180,8 @@ def word_search(

if response.status_code != httpx.codes.OK:
raise types.TranscriptError(
f"failed to search words in transcript {transcript_id}: {_get_error_message(response)}"
f"failed to search words in transcript {transcript_id}: {_get_error_message(response)}",
response.status_code,
)

return types.WordSearchMatchResponse.parse_obj(response.json())
Expand All @@ -199,17 +206,20 @@ def get_redacted_audio(

if response.status_code == httpx.codes.ACCEPTED:
raise types.RedactedAudioIncompleteError(
f"redacted audio for transcript {transcript_id} is not ready yet"
f"redacted audio for transcript {transcript_id} is not ready yet",
response.status_code,
)

if response.status_code == httpx.codes.BAD_REQUEST:
raise types.RedactedAudioExpiredError(
f"redacted audio for transcript {transcript_id} is no longer available"
f"redacted audio for transcript {transcript_id} is no longer available",
response.status_code,
)

if response.status_code != httpx.codes.OK:
raise types.TranscriptError(
f"failed to retrieve redacted audio for transcript {transcript_id}: {_get_error_message(response)}"
f"failed to retrieve redacted audio for transcript {transcript_id}: {_get_error_message(response)}",
response.status_code,
)

return types.RedactedAudioResponse.parse_obj(response.json())
Expand All @@ -225,7 +235,8 @@ def get_sentences(

if response.status_code != httpx.codes.OK:
raise types.TranscriptError(
f"failed to retrieve sentences for transcript {transcript_id}: {_get_error_message(response)}"
f"failed to retrieve sentences for transcript {transcript_id}: {_get_error_message(response)}",
response.status_code,
)

return types.SentencesResponse.parse_obj(response.json())
Expand All @@ -241,7 +252,8 @@ def get_paragraphs(

if response.status_code != httpx.codes.OK:
raise types.TranscriptError(
f"failed to retrieve paragraphs for transcript {transcript_id}: {_get_error_message(response)}"
f"failed to retrieve paragraphs for transcript {transcript_id}: {_get_error_message(response)}",
response.status_code,
)

return types.ParagraphsResponse.parse_obj(response.json())
Expand All @@ -264,7 +276,8 @@ def list_transcripts(

if response.status_code != httpx.codes.OK:
raise types.AssemblyAIError(
f"failed to retrieve transcripts: {_get_error_message(response)}"
f"failed to retrieve transcripts: {_get_error_message(response)}",
response.status_code,
)

return types.ListTranscriptResponse.parse_obj(response.json())
Expand All @@ -285,7 +298,8 @@ def lemur_question(

if response.status_code != httpx.codes.OK:
raise types.LemurError(
f"failed to call Lemur questions: {_get_error_message(response)}"
f"failed to call Lemur questions: {_get_error_message(response)}",
response.status_code,
)

return types.LemurQuestionResponse.parse_obj(response.json())
Expand All @@ -306,7 +320,8 @@ def lemur_summarize(

if response.status_code != httpx.codes.OK:
raise types.LemurError(
f"failed to call Lemur summary: {_get_error_message(response)}"
f"failed to call Lemur summary: {_get_error_message(response)}",
response.status_code,
)

return types.LemurSummaryResponse.parse_obj(response.json())
Expand All @@ -327,7 +342,8 @@ def lemur_action_items(

if response.status_code != httpx.codes.OK:
raise types.LemurError(
f"failed to call Lemur action items: {_get_error_message(response)}"
f"failed to call Lemur action items: {_get_error_message(response)}",
response.status_code,
)

return types.LemurActionItemsResponse.parse_obj(response.json())
Expand All @@ -348,7 +364,8 @@ def lemur_task(

if response.status_code != httpx.codes.OK:
raise types.LemurError(
f"failed to call Lemur task: {_get_error_message(response)}"
f"failed to call Lemur task: {_get_error_message(response)}",
response.status_code,
)

return types.LemurTaskResponse.parse_obj(response.json())
Expand All @@ -366,7 +383,8 @@ def lemur_purge_request_data(

if response.status_code != httpx.codes.OK:
raise types.LemurError(
f"Failed to purge LeMUR request data for provided request ID: {request.request_id}. Error: {_get_error_message(response)}"
f"Failed to purge LeMUR request data for provided request ID: {request.request_id}. Error: {_get_error_message(response)}",
response.status_code,
)

return types.LemurPurgeResponse.parse_obj(response.json())
Expand All @@ -387,7 +405,8 @@ def lemur_get_response_data(

if response.status_code != httpx.codes.OK:
raise types.LemurError(
f"Failed to get LeMUR response data for provided request ID: {request_id}. Error: {_get_error_message(response)}"
f"Failed to get LeMUR response data for provided request ID: {request_id}. Error: {_get_error_message(response)}",
response.status_code,
)

json_data = response.json()
Expand All @@ -411,7 +430,8 @@ def create_temporary_token(

if response.status_code != httpx.codes.OK:
raise types.AssemblyAIError(
f"Failed to create temporary token: {_get_error_message(response)}"
f"Failed to create temporary token: {_get_error_message(response)}",
response.status_code,
)

data = types.RealtimeCreateTemporaryTokenResponse.parse_obj(response.json())
Expand Down
21 changes: 18 additions & 3 deletions assemblyai/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
from typing import ClassVar, Optional

import httpx
from typing_extensions import Self

from . import types
from .__version__ import __version__
Expand Down Expand Up @@ -41,14 +40,30 @@ def __init__(

headers = {"user-agent": user_agent}
if self._settings.api_key:
headers["authorization"] = self.settings.api_key
headers["authorization"] = self._settings.api_key

self._last_response: Optional[httpx.Response] = None

def _store_response(response):
self._last_response = response

self._http_client = httpx.Client(
base_url=self.settings.base_url,
headers=headers,
timeout=self.settings.http_timeout,
event_hooks={"response": [_store_response]},
)

@property
def last_response(self) -> Optional[httpx.Response]:
"""
Get the last HTTP response, corresponding to the last request sent from this client.
Returns:
The last HTTP response.
"""
return self._last_response

@property
def settings(self) -> types.Settings:
"""
Expand All @@ -72,7 +87,7 @@ def http_client(self) -> httpx.Client:
return self._http_client

@classmethod
def get_default(cls, api_key_required: bool = True) -> Self:
def get_default(cls, api_key_required: bool = True):
"""
Return the default client.
Expand Down
Loading

0 comments on commit 8fb9523

Please sign in to comment.