Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 6 · Worked example · 25 min · revision 3

First Calls: Parameters, Usage, Images and Audio

Call a model through the Anthropic and OpenAI Python SDKs: a multi-turn request with a system prompt, an output limit and a stop sequence, then an image, a PDF and a voice note, reading the stop reason and token usage each time. Runs against a local stand-in, so no API key is needed.

Contentsand lesson path

What you will learn

  • Send multi-turn requests with system instructions and generation parameters (temperature, top-p, maximum output tokens, stop sequences), and read content, stop reason and token usage from the response.
  • Send image and PDF inputs to a multimodal model and transcribe audio with a speech-to-text model, accounting for their token cost and size limits.

Prerequisites: Python Foundations, HTTP & APIs

01. The problem

A support team wants an assistant for follow-up questions about incidents, sometimes with a screenshot, a PDF from the customer or a voice note attached. Before anyone builds an interface, you need scripts that prove the calls work and show what they cost:

  • send a multi-turn conversation with a system prompt and an output limit, and print the answer, the stop reason and the token usage;
  • notice when an answer was cut off, and stop an answer early with a stop sequence;
  • send the same conversation through an OpenAI-compatible endpoint;
  • attach a screenshot and a PDF, sized so that you know their cost before you send them;
  • transcribe a voice note, with a hosted service or on your own machine.

You need no API key: a local stand-in, fake_provider.py, accepts the same requests and answers in the same JSON shapes. It has no model; its reply describes the request it received, which is handy for checking what your code sends. With real keys, the same scripts call the real APIs after a change of environment variables, and the response shapes are the same.

02. Step 1: Set up the project and the stand-in provider

Create the folder for the whole skill. Tested with Python 3.12, anthropic 2.9, openai 3.52, FastAPI 0.163 and faster-whisper 1.2.1, which fails with PyAV 19, its audio library, so the command pins an earlier PyAV. The two SDK ranges stop below the next major version, so that an upgrade with breaking changes happens on purpose, after you read its migration guide. The current anthropic major, 2.x (October 2026), sends API version 2026-10-21, which rejects temperature on every Claude model; no script in this skill sets it.

Terminal 1
mkdir llm-client && cd llm-client
python3 -m venv .venv
source .venv/bin/activate      # Windows: .venv\Scripts\activate
python -m pip install 'anthropic>=2.9,<3' 'openai>=3.52,<4' fastapi \
  'uvicorn[standard]' python-multipart pillow faster-whisper 'av<19'
python -c "import anthropic, openai; print(anthropic.__version__, openai.__version__)"
Expected output (your minor versions may be newer)
2.9.0 3.52.0

Now save the stand-in as fake_provider.py. It is long because it imitates two APIs; you need not study it. Part 1 builds the reply. It counts one "token" per word or punctuation mark, charges images by 28-pixel patches as Claude does and PDFs at a flat 2,000 tokens a page, and applies max_tokens and stop sequences as a real model would. Real tokenizers and prices differ.

Python · fake_provider.py (part 1 of 4)
"""A local stand-in for a model provider. For learning and tests only.

It accepts Anthropic Messages and OpenAI-style chat completion requests and
answers in the same JSON and SSE shapes, but there is no model behind it: the
reply only describes the request it received.
"""
import asyncio
import base64
import io
import json
import math
import re
import time
import wave

from fastapi import FastAPI, Request, UploadFile
from fastapi.responses import JSONResponse, StreamingResponse
from PIL import Image

# --- Part 1: read the request, shape the reply -------------------------------
app = FastAPI(title='Fake LLM provider')
TOKEN = re.compile(r'\w+|[^\w\s]')  # one "token" per word or punctuation mark
TOKEN_DELAY = 0.05  # seconds between streamed tokens


def count(text: str) -> int:
    return len(TOKEN.findall(text))


def media_tokens(kind: str, data_b64: str) -> int:
    data = base64.b64decode(data_b64.split(',')[-1])  # also accepts data: URLs
    if kind in ('image', 'image_url'):
        width, height = Image.open(io.BytesIO(data)).size
        return math.ceil(width / 28) * math.ceil(height / 28)  # 28 x 28 px patches
    pages = len(re.findall(rb'/Type\s*/Page[^s]', data))
    return 2000 * pages  # a flat guess per PDF page


def read_content(content) -> tuple[str, int, int, int]:
    """Return the text, image count, document count and tokens of one message."""
    if isinstance(content, str):
        return content, 0, 0, count(content)
    text, images, docs, tokens = '', 0, 0, 0
    for part in content:
        kind = part['type']
        if kind == 'text':
            text, tokens = part['text'], tokens + count(part['text'])
        elif kind in ('image', 'document'):  # Anthropic shape
            tokens += media_tokens(kind, part['source']['data'])
            images, docs = images + (kind == 'image'), docs + (kind == 'document')
        elif kind == 'image_url':  # OpenAI shape
            tokens += media_tokens(kind, part['image_url']['url'])
            images += 1
        elif kind == 'file':
            tokens += media_tokens(kind, part['file']['file_data'])
            docs += 1
    return text, images, docs, tokens


def make_reply(system: str, messages: list, max_tokens: int, stops: list) -> dict:
    tokens, images, docs, last = count(system), 0, 0, ''
    for message in messages:
        text, i, d, t = read_content(message['content'])
        tokens, images, docs = tokens + t, images + i, docs + d
        if message['role'] == 'user':
            last = text
    seen = f'{len(messages)} message(s), {images} image(s), {docs} document(s)'
    text = (f'Fake reply to: {last}\nReceived {seen}.\n'
            'There is no model here; a real provider would answer the question.')
    reason, stop_sequence = 'end_turn', None
    found = sorted((text.find(s), s) for s in stops if s in text)
    if found:
        cut, stop_sequence = found[0]
        text, reason = text[:cut], 'stop_sequence'
    spans = list(TOKEN.finditer(text))
    if len(spans) > max_tokens:
        text = text[:spans[max_tokens - 1].end()]
        reason, stop_sequence = 'max_tokens', None
    return {'text': text, 'reason': reason, 'stop_sequence': stop_sequence,
            'input': tokens, 'output': min(len(spans), max_tokens)}

Part 2 lets you script failures and slow responses. Lesson 3 uses it to test retries.

Python · fake_provider.py (part 2 of 4)
# --- Part 2: failures on demand ----------------------------------------------
PLAN = {'fail': [], 'retry_after': None, 'delay': 0.0}


@app.post('/_fake/plan')
async def set_plan(plan: dict) -> dict:
    """Script what comes next, e.g. {"fail": [429, 503], "retry_after": 2}."""
    PLAN.update({'fail': [], 'retry_after': None, 'delay': 0.0}, **plan)
    return PLAN


async def planned_failure(api: str) -> JSONResponse | None:
    await asyncio.sleep(PLAN['delay'])  # a slow provider
    if not PLAN['fail']:
        return None
    status = PLAN['fail'].pop(0)
    kind = {429: 'rate_limit_error', 529: 'overloaded_error'}.get(status, 'api_error')
    if api == 'anthropic':
        body = {'type': 'error', 'error': {'type': kind, 'message': f'fake {status}'}}
    else:
        body = {'error': {'type': kind, 'message': f'fake {status}', 'code': None}}
    headers = {'retry-after': str(PLAN['retry_after'])} if PLAN['retry_after'] else {}
    return JSONResponse(body, status_code=status, headers=headers)

Part 3 is the Messages endpoint. It returns one JSON message, or a stream of server-sent events when the request asks for one; lesson 4 explains the stream.

Python · fake_provider.py (part 3 of 4)
# --- Part 3: the Messages endpoint, with and without streaming ---------------
def sse(event: str | None, data: dict | str) -> str:
    payload = data if isinstance(data, str) else json.dumps(data, separators=(',', ':'))
    return (f'event: {event}\n' if event else '') + f'data: {payload}\n\n'


async def trickle(text: str):
    """Yield the reply a token at a time, and report if the client hangs up."""
    spans = list(TOKEN.finditer(text))
    sent = 0
    try:
        for span in spans:
            await asyncio.sleep(TOKEN_DELAY)
            start = spans[sent - 1].end() if sent else 0
            sent += 1
            yield text[start:span.end()]
    finally:
        if sent < len(spans):
            print(f'fake: client left after {sent} of {len(spans)} tokens', flush=True)


@app.post('/v1/messages')
async def messages(request: Request):
    body = await request.json()
    if (failure := await planned_failure('anthropic')) is not None:
        return failure
    if 'max_tokens' not in body:
        error = {'type': 'invalid_request_error', 'message': 'max_tokens: required'}
        return JSONResponse({'type': 'error', 'error': error}, status_code=400)
    system = body.get('system') or ''
    if isinstance(system, list):
        system = ' '.join(block['text'] for block in system)
    r = make_reply(system, body['messages'], body['max_tokens'],
                   body.get('stop_sequences') or [])
    usage = {'input_tokens': r['input'], 'output_tokens': r['output']}
    message = {'id': 'msg_fake_1', 'type': 'message', 'role': 'assistant',
               'model': body['model'], 'content': [{'type': 'text', 'text': r['text']}],
               'stop_reason': r['reason'], 'stop_sequence': r['stop_sequence'],
               'usage': usage}
    if not body.get('stream'):
        return message

    async def events():
        start = {**message, 'content': [], 'stop_reason': None, 'stop_sequence': None,
                 'usage': {**usage, 'output_tokens': 0}}
        yield sse('message_start', {'type': 'message_start', 'message': start})
        block = {'type': 'text', 'text': ''}
        yield sse('content_block_start',
                  {'type': 'content_block_start', 'index': 0, 'content_block': block})
        async for piece in trickle(r['text']):
            delta = {'type': 'text_delta', 'text': piece}
            yield sse('content_block_delta',
                      {'type': 'content_block_delta', 'index': 0, 'delta': delta})
        yield sse('content_block_stop', {'type': 'content_block_stop', 'index': 0})
        delta = {'stop_reason': r['reason'], 'stop_sequence': r['stop_sequence']}
        yield sse('message_delta', {'type': 'message_delta', 'delta': delta,
                                    'usage': {'output_tokens': r['output']}})
        yield sse('message_stop', {'type': 'message_stop'})

    return StreamingResponse(events(), media_type='text/event-stream')

Part 4 adds the OpenAI-style chat completions endpoint and a transcription endpoint that accepts WAV files.

Python · fake_provider.py (part 4 of 4)
# --- Part 4: chat completions and transcriptions -----------------------------
@app.post('/v1/chat/completions')
async def chat_completions(request: Request):
    body = await request.json()
    if (failure := await planned_failure('openai')) is not None:
        return failure
    limit = body.get('max_completion_tokens') or body.get('max_tokens') or 4096
    stops = body.get('stop') or []
    stops = [stops] if isinstance(stops, str) else stops
    r = make_reply('', body['messages'], limit, stops)
    finish = {'end_turn': 'stop', 'stop_sequence': 'stop', 'max_tokens': 'length'}
    usage = {'prompt_tokens': r['input'], 'completion_tokens': r['output'],
             'total_tokens': r['input'] + r['output']}
    base = {'id': 'chatcmpl-fake-1', 'created': int(time.time()),
            'model': body['model']}
    if not body.get('stream'):
        choice = {'index': 0, 'finish_reason': finish[r['reason']],
                  'message': {'role': 'assistant', 'content': r['text']}}
        return {**base, 'object': 'chat.completion', 'choices': [choice],
                'usage': usage}

    def chunk(choices: list, **extra) -> str:
        return sse(None, {**base, 'object': 'chat.completion.chunk',
                          'choices': choices, **extra})

    async def events():
        yield chunk([{'index': 0, 'delta': {'role': 'assistant', 'content': ''},
                      'finish_reason': None}])
        async for piece in trickle(r['text']):
            yield chunk([{'index': 0, 'delta': {'content': piece},
                          'finish_reason': None}])
        yield chunk([{'index': 0, 'delta': {}, 'finish_reason': finish[r['reason']]}])
        if (body.get('stream_options') or {}).get('include_usage'):
            yield chunk([], usage=usage)
        yield sse(None, '[DONE]')

    return StreamingResponse(events(), media_type='text/event-stream')


@app.post('/v1/audio/transcriptions')
async def transcriptions(file: UploadFile):
    if (failure := await planned_failure('openai')) is not None:
        return failure
    with wave.open(io.BytesIO(await file.read())) as clip:  # WAV files only
        seconds = round(clip.getnframes() / clip.getframerate(), 1)
    return {'text': f'(fake transcript of {seconds:g} s of audio from {file.filename})',
            'usage': {'type': 'duration', 'seconds': seconds}}

Start it in terminal 1 and leave it running:

Terminal 1
uvicorn fake_provider:app --port 8100
Expected output (the process id differs)
INFO:     Started server process [3958043]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on http://127.0.0.1:8100 (Press CTRL+C to quit)

In terminal 2, activate the virtual environment and set the variables the scripts read. Both SDKs take the key and the base URL from the environment, so the scripts never mention the stand-in. The model names are current examples.

Terminal 2
cd llm-client && source .venv/bin/activate
export ANTHROPIC_API_KEY=not-a-real-key ANTHROPIC_BASE_URL=http://127.0.0.1:8100
export OPENAI_API_KEY=not-a-real-key OPENAI_BASE_URL=http://127.0.0.1:8100/v1
export ANTHROPIC_MODEL=claude-sonnet-5-5 OPENAI_MODEL=gpt-6-luna
export OPENAI_STT_MODEL=gpt-transcribe

In PowerShell, set each variable with $env:NAME = 'value'. To use real providers later, set your real keys and remove the two _BASE_URL variables, so that the SDKs fall back to the providers' own addresses.

03. Step 2: Send a multi-turn request

Save ask_claude.py. The conversation is a list of turns your code keeps; the system prompt is a separate argument.

Python · ask_claude.py
import os
import sys

import anthropic

client = anthropic.Anthropic()  # reads ANTHROPIC_API_KEY and ANTHROPIC_BASE_URL
MODEL = os.environ['ANTHROPIC_MODEL']
SYSTEM = 'You help a support team. Answer in at most two sentences.'

history = [
    {'role': 'user', 'content': 'Our nightly export failed with HTTP 413.'},
    {'role': 'assistant', 'content': 'A 413 means the request body was too large.'},
    {'role': 'user', 'content': 'What should we change first?'},
]


def ask(max_tokens: int, stop: list[str] | None = None) -> str:
    extra = {'stop_sequences': stop} if stop else {}
    response = client.messages.create(
        model=MODEL,
        max_tokens=max_tokens,
        system=SYSTEM,
        messages=history,
        output_config={'effort': 'low'},  # reasoning effort; see the note below
        **extra,
    )
    text = ''.join(block.text for block in response.content if block.type == 'text')
    usage = response.usage
    print(f'stop_reason={response.stop_reason}, '
          f'stop_sequence={response.stop_sequence!r}')
    print(f'usage: input_tokens={usage.input_tokens}, '
          f'output_tokens={usage.output_tokens}')
    if response.stop_reason == 'max_tokens':
        print('warning: the answer was cut off; raise max_tokens or ask for less')
    elif response.stop_reason == 'refusal':
        print('warning: the model declined; do not treat the text as an answer')
    return text


if __name__ == '__main__':
    limit = int(sys.argv[1]) if len(sys.argv) > 1 else 300
    # --stop TEXT sends TEXT as a stop sequence, for example: --stop Received
    stop = sys.argv[3:4] if sys.argv[2:3] == ['--stop'] else None
    print(ask(limit, stop).rstrip())
Terminal 2
python ask_claude.py
Expected output
stop_reason=end_turn, stop_sequence=None
usage: input_tokens=37, output_tokens=43
Fake reply to: What should we change first?
Received 3 message(s), 0 image(s), 0 document(s).
There is no model here; a real provider would answer the question.
  • anthropic.Anthropic() finds the key and base URL in the environment. Create one client and reuse it; it keeps connections open.
  • output_config sets the reasoning effort; low suits short support answers. Models without effort support reject the field, another reason to keep such settings with the model configuration.
  • The answer joins the blocks whose type is text, so a reasoning or tool block is never printed by mistake.
  • usage gives the billed input and output tokens. A real model words its answer differently on every run; the shape stays the same.

04. Step 3: Detect cut-offs and stop early on purpose

Run the script with a limit of 8 output tokens, and then with --stop Received, which sends the word Received as a stop sequence. The stand-in always starts the second line of its reply with that word, so here it plays the part of a marker:

Terminal 2
python ask_claude.py 8
python ask_claude.py 300 --stop Received
Expected output
stop_reason=max_tokens, stop_sequence=None
usage: input_tokens=37, output_tokens=8
warning: the answer was cut off; raise max_tokens or ask for less
Fake reply to: What should we change
stop_reason=stop_sequence, stop_sequence='Received'
usage: input_tokens=37, output_tokens=10
Fake reply to: What should we change first?

The first answer stopped mid-sentence, and only stop_reason says so; the text itself gives no warning. That is why the script checks it on every call. What to do next depends on the feature: raise the limit, ask for less, or mark the answer as incomplete.

The second answer ended just before the marker: stop_reason is stop_sequence, stop_sequence names the string, and the string is not in the text (the script strips the line break left before it). With a real model you ask for a marker in the prompt, such as "end your answer with ###", and stop on ###. Prefer a visible marker to a bare newline: some providers reject stop sequences made only of whitespace. Stop sequences beat trimming afterwards, because the rest is never generated or billed.

05. Step 4: The same request through an OpenAI-compatible endpoint

Save ask_compatible.py, which reuses the conversation from step 2:

Python · ask_compatible.py
import os

import openai

from ask_claude import SYSTEM, history

client = openai.OpenAI()  # reads OPENAI_API_KEY and OPENAI_BASE_URL
response = client.chat.completions.create(
    model=os.environ['OPENAI_MODEL'],
    messages=[{'role': 'system', 'content': SYSTEM}, *history],
    max_completion_tokens=300,  # includes reasoning tokens on reasoning models
)
choice = response.choices[0]
usage = response.usage
print(f'finish_reason={choice.finish_reason}')
print(f'usage: prompt_tokens={usage.prompt_tokens}, '
      f'completion_tokens={usage.completion_tokens}')
print(choice.message.content)
Terminal 2
python ask_compatible.py
Expected output
finish_reason=stop
usage: prompt_tokens=37, completion_tokens=43
Fake reply to: What should we change first?
Received 4 message(s), 0 image(s), 0 document(s).
There is no model here; a real provider would answer the question.

The stand-in counted four messages, because the system prompt travels as the first one. The answer is in choices[0].message.content, the stop reason in finish_reason, and usage counts prompt and completion tokens. The script sets no temperature or seed: OpenAI's reasoning models restrict sampling settings, and OpenAI documents seed on Chat Completions only as a best-effort Beta feature (the Responses API has no seed), while local servers honour both (lesson 5). Ollama, vLLM and other servers that implement this API work with the same script once OPENAI_BASE_URL and OPENAI_MODEL point at them.

06. Step 5: Attach a screenshot and a PDF

Use your own files, or create two with this script: a 2880 × 1800 "screenshot", the size of a full-screen capture on a high-density laptop display, and a two-page invoice.

Python · make_samples.py
"""Create a large 'screenshot' and a two-page PDF to practise with."""
from PIL import Image, ImageDraw

shot = Image.new('RGB', (2880, 1800), 'white')
ImageDraw.Draw(shot).text((100, 100), 'Export failed: HTTP 413', fill='black')
shot.save('screenshot.png')

pages = [Image.new('RGB', (1240, 1754), 'white') for _ in range(2)]  # A4, 150 dpi
for number, page in enumerate(pages, start=1):
    ImageDraw.Draw(page).text((100, 100), f'Invoice 118, page {number}', fill='black')
pages[0].save('invoice.pdf', save_all=True, append_images=pages[1:])

Save attach.py. It shrinks the image before sending it and estimates its cost with the patch formula from lesson 1, and it checks the size of the PDF. The two limits at the top are the values when this lesson was written; check the provider docs for your model's current ones:

Python · attach.py
import base64
import io
import math
import os
from pathlib import Path

import anthropic
from PIL import Image

MAX_EDGE = 1568  # px: enough detail for a screenshot; check your model's limit
MAX_PDF_BYTES = 32_000_000  # 128 MB per request on the Claude API, 32 MB on some clouds


def b64(data: bytes) -> str:
    return base64.standard_b64encode(data).decode('ascii')


def image_block(path: str) -> dict:
    image = Image.open(path)
    original = image.size
    image.thumbnail((MAX_EDGE, MAX_EDGE))  # shrinks to fit, keeps the aspect ratio
    buffer = io.BytesIO()
    image.save(buffer, format='PNG')
    width, height = image.size
    estimate = math.ceil(width / 28) * math.ceil(height / 28)
    print(f'{path}: {original} -> {image.size}, about {estimate} input tokens')
    data = b64(buffer.getvalue())
    return {'type': 'image',
            'source': {'type': 'base64', 'media_type': 'image/png', 'data': data}}


def pdf_block(path: str) -> dict:
    data = Path(path).read_bytes()
    if len(data) > MAX_PDF_BYTES:
        raise ValueError(f'{path} is too large: split it or send only some pages')
    source = {'type': 'base64', 'media_type': 'application/pdf', 'data': b64(data)}
    return {'type': 'document', 'source': source}


def main() -> None:
    client = anthropic.Anthropic()
    content = [
        image_block('screenshot.png'),
        pdf_block('invoice.pdf'),
        {'type': 'text', 'text': 'Does the error in the screenshot match the invoice?'},
    ]
    response = client.messages.create(
        model=os.environ['ANTHROPIC_MODEL'],
        max_tokens=500,
        messages=[{'role': 'user', 'content': content}],
    )
    usage = response.usage
    print(f'usage: input_tokens={usage.input_tokens}, '
          f'output_tokens={usage.output_tokens}')
    print(''.join(block.text for block in response.content if block.type == 'text'))


if __name__ == '__main__':
    main()
Terminal 2
python make_samples.py
python attach.py
Expected output
screenshot.png: (2880, 1800) -> (1568, 980), about 1960 input tokens
usage: input_tokens=5970, output_tokens=47
Fake reply to: Does the error in the screenshot match the invoice?
Received 1 message(s), 1 image(s), 1 document(s).
There is no model here; a real provider would answer the question.

At full size the screenshot would be ⌈2880 / 28⌉ × ⌈1800 / 28⌉ = 103 × 65 = 6,695 patches. Claude would scale it down to its limit anyway, but you would upload the whole file and could not predict the cost. At 1568 × 980 it costs 1,960 tokens and its text stays readable. The input total is 1,960 for the image, 4,000 for two PDF pages at the stand-in's flat rate and 10 for the question. With a real model, compare input_tokens with your estimate on a few files before trusting the formula.

In the OpenAI shape the image becomes a data URL and the PDF a file part:

Python · attach_compatible.py
import os
from pathlib import Path

import openai

from attach import b64, image_block

png = image_block('screenshot.png')['source']['data']  # resized, base64
pdf = b64(Path('invoice.pdf').read_bytes())
content = [
    {'type': 'image_url', 'image_url': {'url': f'data:image/png;base64,{png}'}},
    {'type': 'file', 'file': {'filename': 'invoice.pdf',
                              'file_data': f'data:application/pdf;base64,{pdf}'}},
    {'type': 'text', 'text': 'Does the error in the screenshot match the invoice?'},
]
response = openai.OpenAI().chat.completions.create(
    model=os.environ['OPENAI_MODEL'],
    max_completion_tokens=500,
    messages=[{'role': 'user', 'content': content}],
)
print(f'usage: prompt_tokens={response.usage.prompt_tokens}')
Terminal 2
python attach_compatible.py
Expected output
screenshot.png: (2880, 1800) -> (1568, 980), about 1960 input tokens
usage: prompt_tokens=5970

07. Step 6: Transcribe a voice note, hosted or local

Speech goes to a transcription endpoint as a file upload; the text that comes back can join the conversation. As a sample, download the 11-second public-domain Kennedy recording from the tests of OpenAI's Whisper project. The recording is a FLAC file. The OpenAI transcription API accepts FLAC, but the offline stand-in reads only WAV (it opens the upload with wave.open), so prepare_audio.py converts the file to 16 kHz mono WAV, the rate speech models use anyway, which also keeps uploads small.

Python · prepare_audio.py
import sys
import wave

from faster_whisper import decode_audio

RATE = 16_000  # speech models work at 16 kHz, so a higher rate only adds bytes

source, target = sys.argv[1], sys.argv[2]
samples = decode_audio(source, sampling_rate=RATE)  # mono float32, any input format
with wave.open(target, 'wb') as out:
    out.setnchannels(1)
    out.setsampwidth(2)  # 16-bit
    out.setframerate(RATE)
    out.writeframes((samples * 32767).astype('<i2').tobytes())
seconds = len(samples) / RATE
print(f'{target}: {len(samples):,} samples ({seconds:.0f} s), '
      f'{seconds * RATE * 2 / 1e6:.2f} MB; '
      f'25 MB holds about {25e6 / (RATE * 2) / 60:.0f} minutes at this rate')
Terminal 2
curl -sL -o jfk.flac \
  https://raw.githubusercontent.com/openai/whisper/main/tests/jfk.flac
python prepare_audio.py jfk.flac jfk.wav
Expected output
jfk.wav: 176,000 samples (11 s), 0.35 MB; 25 MB holds about 13 minutes at this rate

The hosted route checks the upload limit first, so an oversized file fails before it is sent. As with images and PDFs, take the limit and the list of formats from the provider docs, not from memory:

Python · transcribe.py
import os
import sys
from pathlib import Path

import openai

MAX_UPLOAD = 25_000_000  # bytes, the upload limit at the time of writing


def transcribe(path: Path) -> str:
    size = path.stat().st_size
    if size > MAX_UPLOAD:
        raise ValueError(f'{path} is {size:,} bytes: split or compress it first')
    with path.open('rb') as audio:
        result = openai.OpenAI().audio.transcriptions.create(
            model=os.environ['OPENAI_STT_MODEL'], file=audio)
    print(f'{path.name}: {size:,} bytes sent; usage: {result.usage or "not reported"}')
    return result.text


if __name__ == '__main__':
    print(transcribe(Path(sys.argv[1])))
Terminal 2
python transcribe.py jfk.wav
Expected output
jfk.wav: 352,044 bytes sent; usage: UsageDuration(seconds=11.0, type='duration')
(fake transcript of 11 s of audio from jfk.wav)

The stand-in reports usage in seconds of audio, as duration-priced models such as whisper-1 do (whisper-1 is deprecated and shuts down on 26 February 2027; gpt-transcribe, used here, is the current model); token-priced models report audio and text tokens, and the SDK has a type for each. To keep audio on your own machine, run an open-weight Whisper model with faster-whisper. The first run downloads the model; after that it works offline, at the cost of your own CPU or GPU time:

Python · local_transcribe.py
import sys
import textwrap

from faster_whisper import WhisperModel

# Downloads the model on first use (base.en is about 140 MB), then runs offline.
model = WhisperModel('base.en', device='cpu', compute_type='int8')
segments, info = model.transcribe(sys.argv[1])


def clock(seconds: float) -> str:  # 71.5 -> 1:11.5
    return f'{int(seconds // 60)}:{seconds % 60:04.1f}'


print(f'audio length {clock(info.duration)}, language: {info.language}')
for segment in segments:  # a generator: decoding happens as you iterate
    print(f'[{clock(segment.start)} to {clock(segment.end)}]')
    print(textwrap.fill(segment.text.strip(), width=72))
Terminal 2
python local_transcribe.py jfk.wav
Expected output (after the download messages)
audio length 0:11.0, language: en
[0:00.0 to 0:11.0]
And so my fellow Americans, ask not what your country can do for you,
ask what you can do for your country.

This is a real transcription, made on a laptop CPU in under half a minute, model loading included. Larger Whisper models are more accurate and slower; on a GPU, pass device="cuda".

08. Common mistakes

09. Check your understanding

Practice check · 3 questions

Read what your first calls did

Questions about the scripts you have just run.

Q1. Why does attach.py encode the image and the PDF as base64 before sending them?
Q2. With --stop Received, the response has stop_reason stop_sequence and stop_sequence "Received". Which statement is true?
Q3. What do you gain and give up by transcribing with faster-whisper instead of a hosted endpoint?
Practice only: not graded, not saved, not evidence.

10. Apply it

Start the practice project's client module from these scripts:

  1. Combine ask_claude.py and attach.py into one function that takes optional image and PDF paths, checks them against the limits in docs/providers.md, and returns the text, the stop reason and the usage.
  2. Log one line per call: model, stop reason, input and output tokens, and an estimated cost at current prices. Never log the attachments.
  3. With a real key, run each script once against the real provider, and note in docs/providers.md how the reported input_tokens for the screenshot compares with your estimate.

11. Review prompt

Without looking back, write an anthropic SDK call with a three-turn conversation, a system prompt, an output limit and a stop sequence, and the code that reads the text, the stop reason and both token counts. Then write the content list for one image and one PDF, and work out the patch cost of a 1920 × 1080 screenshot before and after resizing it to a long edge of 1280 pixels.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check