CertPrep
Domain 2 · Lesson 2.1 · 5 min read

Messages API Mechanics

Exam skillMessages API Mechanics

Applying Messages API mechanics in application code and API requests, including message structure, tool use, streaming, vision, thinking, prompt caching, structured output, and stop reasons, to produce the intended behavior, and choosing between realtime and batch processing.

Write correct Messages API requests and handle responses: system prompt and alternating turns, content blocks for images and documents, tool use and tool results, the streaming event sequence, thinking budgets, cache breakpoints, structured output and every stop reason, and choose realtime or batch for each workload.

What you need to know

Request structure

  • system: a top-level parameter, not a message role.
  • messages: alternating user and assistant turns, starting with user. The API is stateless: send the history the model needs on every request.
  • Content is a list of blocks: text, image, document, tool_use, tool_result, thinking.
  • Images go in the user message as image blocks (base64, URL or file ID), ideally before the question about them. Resize large photos.
  • Large or reused files are uploaded once with the Files API and referenced by file_id.

Stop reasons

stop_reasonMeaningWhat the app does
end_turnNatural finishUse the answer
tool_useModel wants toolsRun them; send tool_result blocks
max_tokensOutput budget reachedTreat as incomplete; raise budget, ask for less, or continue
stop_sequenceA stop sequence matchedHandle as designed
pause_turnLong server-tool turn pausedSend the response back to continue
refusalModel declinedSafety path; do not route around it
model_context_window_exceededInput plus output outgrew the windowReduce or compact the input

Streaming

Events arrive in order: message_start, then for each block content_block_start, content_block_delta... content_block_stop, then message_delta (carrying stop_reason and usage) and finally message_stop, the terminal event. ping events keep the connection alive.

Tool inputs stream as input_json_delta fragments: collect them and parse at the block's stop. Branch on each block's type; thinking and tool_use blocks are not text.

Thinking and tools

  • Extended thinking takes a token budget that counts toward max_tokens, so max_tokens must exceed it. Adaptive thinking lets the model decide how much to think; effort steers depth.
  • With tools, pass the assistant turn back unchanged, thinking blocks included.
  • tool_choice: auto, any, a specific tool (forces it), or none.

Caching and structured output

  • Mark a cache breakpoint (cache_control) at the end of content that repeats exactly. The cache key is the exact prefix in the order tools, system, messages.
  • Structured outputs constrain responses to a JSON schema; strict tool use constrains tool inputs. Use them instead of "respond in JSON" or prefilling.

Realtime or batch

WorkloadChoice
A user is waitingRealtime, usually streaming
Large, can wait hoursMessage Batches API: about half price, results within 24 hours, matched by custom_id

In the exam

Items show a request or handler and a symptom: rejected system role, truncated JSON, a stream cut short, images ignored, a thinking budget larger than max_tokens, a cache breakpoint after changing text. Apply the mechanic precisely. Distractors switch off features (streaming, thinking) instead of handling them, retry deterministic stops, or use batch for interactive traffic.

Check your understanding

Question 1

A response has stop_reason "tool_use". What next?

Show answer

Answer: B. The model is waiting for the tool's output to continue.

Question 2

Thinking budget 16,000 and max_tokens 8,000 fails validation. Why?

Show answer

Answer: C. The budget must fit inside the output limit.

Question 3

Which event marks the end of a streamed message?

Show answer

Answer: D. message_stop is terminal; stop_reason arrives just before it in message_delta.

Apply it: Build Larkspur's label-photo request

Exercise · about 20 minCase: Larkspur Pharmacy

Larkspur's label-photo reader sends a 9 MB phone photo and the instruction "Extract the drug name, strength, quantity and prescriber" in one user message, with the text block first. The backend parses the reply with a regular expression. It fails on 11% of photos.

  1. Rewrite the request: content order, image handling and output format.
  2. Handle each stop reason the backend might receive.
  3. Decide realtime or batch for this feature and for a monthly re-check of 9,000 old transfers.
    Done when: the backend never parses free text and never treats a truncated reply as complete.
Check your work
Show model answer

1. Resize the photo to the recommended dimensions; send the image block first, then the instruction; use structured output with a schema (drug_name, strength, quantity, prescriber, each nullable when unreadable).

2. end_turn: validate and use. max_tokens: treat as incomplete and retry once with a higher budget. refusal: show "Please enter details manually." Context-window stop: should not occur at this size; log and alert if it does. Any unreadable field (null) goes to a pharmacist.

3. Realtime for the app, because a customer is waiting. Batch for the monthly re-check, matched back by custom_id.

Key termsExtended thinkingPrefillingPrompt cachingStop reasonStreaming

Sources