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 1 of 6 · Concept · 15 min · revision 3

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

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:

JSON · a Messages API request body
{
  "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?"}
  ]
}
  • model names the model. Models are replaced every few months, so read the name from configuration, such as an ANTHROPIC_MODEL environment variable.
  • system holds the standing instructions, kept apart from what the user typed.
  • messages is 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_tokens caps 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:

JSON · the same request as a chat completion
{
  "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, or stop on chat completions) end generation when the model writes one; the stop string is left out of the text. Some OpenAI reasoning models do not accept stop.
  • 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_p or top_k at all, even at their default values; version 1 of the anthropic Python SDK had already dropped these arguments. Only raw requests that still send the older anthropic-version: 2023-06-01 can 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 as top_k and repetition_penalty through the SDK argument extra_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 seed on Chat Completions as a best-effort Beta feature, and the Responses API has no seed; local servers such as Ollama honour it.
  • Reasoning effort (output_config.effort on Claude, reasoning_effort on 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:

TOML · models.toml, an example configuration
[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 = 7

04. Reading the response: content, stop reason and usage

An answer from the Messages API looks like this (some usage fields left out):

JSON · a Messages API response, abridged
{
  "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:

JSON · a chat completion response, abridged
{
  "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:

Stop reasons in the two API shapes
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_filter

Chat 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:

JSON · a user message with an image, a PDF and a question
{
  "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/transcriptions takes 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

Practice check · 3 questions

Read requests and responses

Three situations from real integrations.

Q1. A request with temperature 0.2 works against an open-weight model served by Ollama. Sent unchanged to a current Claude model, it fails with 400 invalid_request_error. What is the most likely cause?
Q2. Your chat completion request set stop to ["###"], and the response has finish_reason "stop". What can you conclude from that field?
Q3. A reasoning model returns finish_reason "length" and an empty message, although max_completion_tokens is 300 and the expected answer is one sentence. What is the likeliest explanation?
Practice only: not graded, not saved, not evidence.

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:

  1. the endpoint, the key header and the environment variable for the key;
  2. how the system instruction is sent, and the output-limit field;
  3. the sampling and reasoning settings the model accepts;
  4. its stop reasons, and what your code should do for each;
  5. 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

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