Sub topic 3
Transcribing audio with an API call
This chapter covers how to send one audio file to a hosted transcription endpoint and read the result. It assumes you can write basic Python, have called an LLM chat API through an SDK, keep API keys in environment variables, and know that MP3 and WAV are audio file formats. Tuning options, long recordings and evaluation come in later chapters.
What a transcription request does
A transcription endpoint takes audio and returns text. It is a different call from a chat completion. A chat call sends JSON messages. A transcription call sends a file as a multipart upload, and the model that reads it is a speech recognition model, not a chat model.
The request has two required parts:
file: the audio, as an open binary file object.model: the speech-to-text model name, for examplewhisper-1.
The response is a small object. In the default format it holds one field, text. That text is the whole recording as one string.
The request does not keep state. Each call is independent, so the model does not remember earlier files. If you want continuity across files, you have to carry it yourself (the next chapter shows how a prompt can do that).
Setting up
Install the SDK and set your key. The client reads OPENAI_API_KEY from the environment, so the key never appears in your code.
# shell: pip install openai
# shell: export OPENAI_API_KEY="your-key-here"
import os
print("key is set:", "OPENAI_API_KEY" in os.environ)If this prints False, the client will raise an authentication error on the first call. Fix the environment before you debug anything else.
The minimal call
This example sends one file and prints the text.
from openai import OpenAI
client = OpenAI() # reads OPENAI_API_KEY from the environment
with open("meeting.mp3", "rb") as audio_file:
transcript = client.audio.transcriptions.create(
model="whisper-1",
file=audio_file,
)
print(transcript.text)Points to notice:
- The file is opened in binary mode (
"rb"). Text mode corrupts the bytes and the call fails or returns nonsense. - The
withblock closes the file after the upload finishes. The SDK reads the file during the call, so keep the call inside the block. - The result is an object, not a string. Read the text from
transcript.text.
What happens between your code and the text
The SDK builds a multipart HTTP request and uploads the audio. The service decodes the container and codec, resamples the audio to the rate the model expects, and runs recognition. It then returns the text in the response format you asked for.
The time you wait is the sum of upload, decoding and recognition. Upload time grows with file size, so a compressed format such as MP3 usually gives a faster call than the same recording as WAV. The latency chapter returns to this.
Accepted inputs and limits
Hosted services accept a fixed list of formats and a maximum file size. For OpenAI's transcription endpoint at the time of writing, the accepted formats include mp3, mp4, mpeg, mpga, m4a, wav and webm, and the upload limit is 25 MB per file. Check the provider's current documentation, because both lists change.
| Problem | Typical symptom | What to do |
|---|---|---|
| Unsupported extension or corrupt file | 400 error about an invalid file format | Convert to MP3 or WAV with a tool such as ffmpeg |
| File over the size limit | 413 error or a 400 error mentioning size | Compress or split the file (see the chunking chapter) |
| Wrong file mode | Garbled upload or decode error | Open with `"rb"` |
| Silence or noise only | Empty text or invented phrases | Check the recording before sending |
A file extension is only a label. If you rename a WAV file to .mp3, the service may still reject it or decode it wrongly. Make sure the real format matches the name.
Checking the file before you send it
A cheap local check saves a failed network round trip. This helper confirms that the file exists, is not empty, and is under the limit.
import os
MAX_BYTES = 25 * 1024 * 1024 # 25 MB, check your provider's current limit
ALLOWED = {".mp3", ".mp4", ".mpeg", ".mpga", ".m4a", ".wav", ".webm"}
def check_audio_file(path):
if not os.path.isfile(path):
raise FileNotFoundError(path)
extension = os.path.splitext(path)[1].lower()
if extension not in ALLOWED:
raise ValueError(f"Unsupported extension: {extension}")
size = os.path.getsize(path)
if size == 0:
raise ValueError("File is empty")
if size > MAX_BYTES:
raise ValueError(f"File is {size} bytes, over the {MAX_BYTES} byte limit")
return size
print(check_audio_file("meeting.mp3"), "bytes, OK")This check cannot verify that the audio decodes. It only catches the common mistakes early.
Reading the response object
With the default response format, the object exposes text. Other formats return more. The same call can return plain text or subtitles, and a richer JSON form adds segments and timestamps. The next chapter covers those. For now, handle the default result carefully.
text = transcript.text.strip()
if not text:
print("No speech detected")
else:
print(f"{len(text.split())} words transcribed")An empty string is a valid result. It usually means the file held silence or sound the model could not read as speech. Treat it as a case your app must handle, not as an exception.
Why the transcript can be wrong
Recognition models predict the most likely words, so they make characteristic errors:
- Homophones. Words that sound alike, such as "mourning" and "morning," can be swapped. Context usually fixes these, but not always.
- Proper names and jargon. Product names, people's names and technical terms are often misspelled because they are rare in training data. A prompt with the right vocabulary helps, as the next chapter shows.
- Silence and noise. On long quiet stretches, some models produce repeated or invented phrases. This is a known failure mode, so check outputs for text that does not match what was said.
- Accents and overlapping speakers. Accuracy drops with strong background noise, cross-talk and low-quality microphones.
- No speaker labels. The basic endpoint returns one stream of words. It does not tell you who said what.
Because of this, do not treat a transcript as ground truth. Later chapters show how to measure error with word error rate and how to treat the text as untrusted input to an LLM.
Running the call from a function
Wrap the call in a function so the rest of your app does not deal with files and SDK details. This version validates the file first and returns a plain string.
from openai import OpenAI
client = OpenAI()
def transcribe(path, model="whisper-1"):
check_audio_file(path) # defined in the previous section
with open(path, "rb") as audio_file:
result = client.audio.transcriptions.create(
model=model,
file=audio_file,
)
return result.text.strip()
if __name__ == "__main__":
print(transcribe("meeting.mp3"))Passing model as an argument lets you switch models later without editing every call site. This function is the building block for the voice loop chapter.
Handling errors at the call site
The SDK raises typed exceptions. For a first version, catch the ones you can act on and let the rest surface.
import openai
from openai import OpenAI
client = OpenAI()
try:
with open("meeting.mp3", "rb") as audio_file:
result = client.audio.transcriptions.create(
model="whisper-1",
file=audio_file,
)
print(result.text)
except openai.AuthenticationError:
print("Check OPENAI_API_KEY")
except openai.BadRequestError as error:
print("The service rejected the file:", error)
except openai.RateLimitError:
print("Rate limited, retry later")AuthenticationError means a missing or wrong key. BadRequestError means the request itself was invalid, such as a bad format or an oversized file, so retrying the same file will fail again. RateLimitError is temporary and is worth retrying with a delay. The errors chapter builds a full retry policy.
Cost and privacy in brief
Hosted transcription is usually billed per minute of audio, not per word. Cost therefore follows recording length, including silence. Trimming dead air before upload lowers the bill and the upload time. Also remember that you are sending the recording to a third party. Confirm that you have consent to process the speech and read the provider's data retention terms before you send anything sensitive. The privacy chapter covers this properly.
Common mistakes
- Opening the file in text mode.
- Closing the file before the call runs, for example by calling
createoutside thewithblock. - Assuming the extension matches the content.
- Treating an empty string as an error, or treating any string as correct.
- Retrying a
BadRequestError, which never succeeds without a change to the input.
Exercise
Your code calls client.audio.transcriptions.create(model="whisper-1", file=open("clip.wav")) and fails with a decode error, even though clip.wav plays fine locally. What is the most likely cause and the fix?
Show answer
The file was opened in text mode, so Python tried to decode the bytes as text and the upload was corrupted. Open it in binary mode with open("clip.wav", "rb"), ideally inside a with block so the file is closed after the call.
Exercise
A user uploads a 40 MB WAV recording and the API returns an error about file size. Name two ways to get it under a 25 MB limit and say which loses no audio content.
Show answer
You can convert the WAV to a compressed format such as MP3, or split the recording into shorter chunks and transcribe each one. Splitting keeps every second of the original audio, while compression discards some detail, though speech recognition usually handles moderate compression well.
Exercise
The call succeeds but transcript.text is an empty string. Should your app raise an exception? Explain.
Show answer
No. An empty string is a valid response when the file contains silence or no recognizable speech. The app should check for it and handle it, for example by telling the user that no speech was detected.