Anatomy of a Request: Messages, Parameters and Media
Read a model API request and response part by part: roles and system instructions, the generation parameters each provider accepts, stop reasons, token usage, and how images, PDFs and audio enter a request and what they cost.
Contentsand lesson path
On this page
- Why it matters
- Anatomy of a request
- Generation parameters: what you can set, and where
- Reading the response: content, stop reason and usage
- Images, PDFs and audio
- Check your understanding
- Apply it
- Review prompt
Lessons of LLM API Integration
- Anatomy of a Request: Messages, Parameters and Media Concept · 15 min
- First Calls: Parameters, Usage, Images and Audio Worked example · 25 min
- Lab: Retries, Backoff and Timeouts Lab · 25 min
- Streaming and Cancellation Worked example · 20 min
- Lab: One Client for Hosted, Local and Mock Models Lab · 30 min
- Check: Diagnose Failing API Calls Knowledge check · 10 questions
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. Why it matters
A model API is a JSON API like those in the HTTP skill: a POST request with a JSON body, and JSON or a stream of events back. The request carries a conversation and settings that shape the answer; the response says why the model stopped and how many tokens you pay for.
Mistakes here are quiet and expensive. A cut-off answer looks like a short one unless you check the stop reason. A full-resolution screenshot can cost more than the rest of the prompt. A setting one model accepts makes the next reject the request. This lesson takes apart both common shapes: the Anthropic Messages API, and the OpenAI-style chat completions API that many providers and local servers copy.
02. Anatomy of a request
Here is the body of a request to the Messages API, sent as POST https://api.anthropic.com/v1/messages:
{
"model": "claude-sonnet-5-5",
"max_tokens": 300,
"system": "You help a support team. Answer in at most two sentences.",
"messages": [
{"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?"}
]
}modelnames the model. Models are replaced every few months, so read the name from configuration, such as anANTHROPIC_MODELenvironment variable.systemholds the standing instructions, kept apart from what the user typed.messagesis the conversation so far, ending with the user turn to answer. The assistant turns are the model's earlier replies, which your code kept and sends back.max_tokenscaps the length of the answer; the Messages API requires it.
Over raw HTTP the key goes in an Authorization: Bearer header, or in the older x-api-key header, which the API still accepts as a fallback, next to an anthropic-version header. The SDKs read the key from ANTHROPIC_API_KEY, so it never appears in your source, and set the version for you; the current majors (Python anthropic 2.x and TypeScript 1.x, released on 21 October 2026) send Authorization: Bearer, while older releases send x-api-key. In the OpenAI-style shape the same conversation goes to POST /v1/chat/completions:
{
"model": "gpt-6-luna",
"max_completion_tokens": 300,
"messages": [
{"role": "system",
"content": "You help a support team. Answer in at most two sentences."},
{"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?"}
]
}Two things differ. The instructions are the first message, with the role system (or developer on OpenAI's newer models). And the output limit is max_completion_tokens, which replaced max_tokens on OpenAI; some compatible servers still read only max_tokens, as lesson 5 shows. The key goes in an Authorization: Bearer header, which the current Anthropic SDKs now use as well, so only hand-written Claude calls with x-api-key still differ there. Ollama, vLLM and most model gateways accept this shape, so it is worth knowing whichever provider you use.
OpenAI itself now recommends its newer Responses API (POST /v1/responses) for new projects, and some newer platform features, such as built-in tools and server-side conversation state, are Responses-first. Chat completions stays supported, and it is the shape that local servers and gateways copy, which is why this skill teaches it. If you build only on hosted OpenAI models, read the Responses migration guide before you start.
03. Generation parameters: what you can set, and where
The tokens and context skill explains what sampling does inside the model; the question here is which model accepts which setting.
- Maximum output tokens is a hard cap: generation stops there, mid-sentence if need be. On reasoning models the hidden reasoning counts towards it and is billed as output.
- Stop sequences (
stop_sequences, orstopon chat completions) end generation when the model writes one; the stop string is left out of the text. Some OpenAI reasoning models do not acceptstop. - Temperature, top-p and top-k control sampling, and support depends on the provider and model. From API version 2026-10-21, which the anthropic 2.x SDKs send, Claude no longer accepts
temperature,top_portop_kat all, even at their default values; version 1 of theanthropicPython SDK had already dropped these arguments. Only raw requests that still send the olderanthropic-version: 2023-06-01can set them, and there Opus 4.7 and later, including the Claude 5 family, accept only the default values. OpenAI documents temperature (0 to 2) and top-p, advising you to change one, not both; many reasoning models restrict them. Ollama and vLLM accept them, and vLLM takes extras such astop_kandrepetition_penaltythrough the SDK argumentextra_body. - Frequency and presence penalties (chat completions, -2.0 to 2.0) discourage repeating tokens; the Messages API has neither.
- Seed asks for repeatable sampling, best effort only: batching and hardware still change outputs, so tests must never depend on the exact wording of a live model. OpenAI documents
seedon Chat Completions as a best-effort Beta feature, and the Responses API has noseed; local servers such as Ollama honour it. - Reasoning effort (
output_config.efforton Claude,reasoning_efforton chat completions) sets how much a reasoning model thinks first: lower is faster and cheaper, higher helps on hard problems. On current Claude models, effort and the prompt replace temperature as the levers.
So treat these settings as part of each model's configuration, next to its name, not as constants spread through your code:
[support-hosted] # Claude through the Messages API
model = "claude-sonnet-5-5"
effort = "low"
[support-local] # an open-weight model served by Ollama
model = "qwen2.5:1.5b"
temperature = 0
seed = 704. Reading the response: content, stop reason and usage
An answer from the Messages API looks like this (some usage fields left out):
{
"id": "msg_01...",
"type": "message",
"role": "assistant",
"model": "claude-sonnet-5-5",
"content": [
{"type": "text", "text": "Send the export in smaller batches, then ..."}
],
"stop_reason": "end_turn",
"stop_sequence": null,
"usage": {"input_tokens": 52, "output_tokens": 31}
}content is a list of blocks, because an answer can mix text with tool calls or reasoning. Join the blocks whose type is text; do not assume the first block is text. A chat completion puts the answer in choices, one per requested sample:
{
"id": "chatcmpl-...",
"object": "chat.completion",
"model": "gpt-6-luna",
"choices": [
{"index": 0,
"message": {"role": "assistant", "content": "Send the export in ..."},
"finish_reason": "stop"}
],
"usage": {"prompt_tokens": 52, "completion_tokens": 31, "total_tokens": 83,
"completion_tokens_details": {"reasoning_tokens": 0}}
}A 200 status only means the call worked; the stop reason says whether the text is the whole answer. The common values line up like this:
What happened Messages stop_reason Chat finish_reason
The answer is complete end_turn stop
It reached your output limit max_tokens length
It wrote one of your stop strings stop_sequence stop
It wants to call a tool tool_use tool_calls
It declined, or was filtered refusal content_filterChat completions report stop for a natural ending and for a stop string alike. The Messages API has a few more values, such as pause_turn and model_context_window_exceeded; treat any value you do not handle as a reason to stop and log.
usage is what you are billed for: input tokens, output tokens (reasoning included) at a higher price, and cached input, in extra fields, for less. Log it for every call with the model name and the request id (the request-id response header on Anthropic, x-request-id on OpenAI), so that cost and failures can be traced.
05. Images, PDFs and audio
Images and documents are content blocks in a user message, usually placed before the question about them:
{
"role": "user",
"content": [
{"type": "image", "source": {"type": "base64", "media_type": "image/png",
"data": "iVBORw0KGgoAAAANSUhEUg..."}},
{"type": "document", "source": {"type": "base64",
"media_type": "application/pdf",
"data": "JVBERi0xLjQKJ..."}},
{"type": "text", "text": "Does the error in the screenshot match the invoice?"}
]
}Chat completions use image_url parts holding a data:image/png;base64,... URL, and file parts with base64 file_data for PDFs. JSON carries only text, so files travel base64-encoded, a third larger than the raw bytes. These figures were current in October 2026; check the provider docs, as they change.
- Images cost input tokens by pixel dimensions, not file size. Claude counts one token per 28 × 28-pixel patch,
⌈width / 28⌉ × ⌈height / 28⌉. Images larger than a per-model limit are scaled down first (2576 pixels and 4,784 tokens for Claude 4.7 and later, 1568 pixels and 1,568 tokens before), which caps the cost but can blur small text. So a 1568 × 980 screenshot costs 56 × 35 = 1,960 tokens on Claude 4.7 and later; on older models it exceeds the 1,568-token cap, so it is scaled down and costs at most 1,568. The Claude API takes up to 10 MB per image, measured after base64 encoding. OpenAI counts patches or tiles, depending on the model. - PDFs are sent as the text of each page plus an image of it, so a page costs text tokens (about 1,500 to 3,000 on Claude) and image tokens. The Claude API accepts requests up to 128 MB (32 MB on some cloud platforms) and 600 pages (100 on models with a context window below a million tokens); OpenAI accepts PDF files under 50 MB.
- Audio usually goes to a separate speech-to-text endpoint. OpenAI's
POST /v1/audio/transcriptionstakes uploads of up to 25 MB in flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav or webm, billed by duration or by audio tokens depending on the model. Open-weight Whisper models run locally with faster-whisper. Text-to-speech, the reverse service, has its own endpoint and prices.
06. Check your understanding
07. Apply it
The practice project is a client that calls a hosted and a local open-weight model through one interface. Start on paper: pick a hosted provider, and Ollama or vLLM, and write docs/providers.md with a section for each:
- the endpoint, the key header and the environment variable for the key;
- how the system instruction is sent, and the output-limit field;
- the sampling and reasoning settings the model accepts;
- its stop reasons, and what your code should do for each;
- where usage is reported, and the limits and costs for images, PDFs and audio.
Lessons 2 to 5 turn this page into code.
08. Review prompt
Without looking back, write the JSON body of a two-turn conversation with a system instruction in both API shapes, and name the header that carries the key in each. List the stop and finish reasons from this lesson with what your code should do for each one. Then explain how a screenshot, a ten-page PDF and a five-minute voice note each turn into cost, and which of them goes to a different endpoint.
References
- OpenAI API reference
- Claude docs: Vision
- Claude API reference: Create a Message
- Claude docs: Stop reasons and fallback
- Claude docs: Effort
- Claude docs: PDF support
- OpenAI API reference: Create chat completion
- OpenAI docs: Reasoning models
- OpenAI docs: Migrate to the Responses API
- OpenAI docs: Images and vision
- OpenAI docs: File inputs
- OpenAI docs: Speech to text
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.