Get the Messages API mechanics right
Write Messages API requests that carry conversation state, return tool results, stream long outputs, cache a stable prefix and match batch results, and pick realtime or batch for a workload.
Scenario
Your Claude integration passed the demo. In its first week in production, a long report request times out, the cache dashboard shows no reads at all, and the nightly batch writes labels onto the wrong rows.
None of these is a model problem. Each is a mechanic of the API.
Explanation
1. State lives in your code. The Messages API is stateless: every request sends the full conversation as messages, alternating user and assistant. After each reply, append Claude's turn to your history, then the next user turn. Images go in the same content arrays as image blocks (base64, URL or a Files API file_id; on Amazon Bedrock and Google Cloud, base64 only).
2. Tool results go back in a fixed shape. When stop_reason is tool_use:
- append Claude's assistant message unchanged, including its
tool_useblocks (and any thinking blocks, unmodified), - then send one user message whose content starts with a
tool_resultblock for eachtool_use, matched bytool_use_id. Any text comes after all tool results. - A tool that failed still gets a result: the error in
contentand"is_error": true.
3. Stream long outputs. A non-streaming request with a large max_tokens risks an HTTP timeout; the docs advise streaming (or batches) for long requests. If you don't need the text as it arrives, stream anyway and let the SDK assemble the result: stream.get_final_message() in Python, stream.finalMessage() in TypeScript. The token counts in message_delta events are cumulative: read the last one, don't add them up.
4. Cache the stable prefix. The cache covers tools, then system, then messages, in that order, up to the block marked with cache_control. Put static content first and the breakpoint on the last block that stays identical. Anything that varies before the breakpoint (a timestamp, a user's name, a reordered tool list) makes a new prefix every time, so nothing is read. Check cache_read_input_tokens and cache_creation_input_tokens in usage. Prompts under the minimum cacheable length are not cached, with no error.
5. Batch what nobody waits for. The Message Batches API costs 50% of standard prices and is asynchronous: most batches finish within an hour, and anything not done in 24 hours expires. Results come back in any order, so match each one by the custom_id you set. stream: true is not allowed in a batch, and because results are kept 29 days, batches are not ZDR-eligible.
Realtime or batch? If a person is waiting, or the deadline is shorter than the 24-hour window, use the Messages API (streamed if long). If the work is bulk and can wait, batch it.
Worked example
An agent looks up an order, then calls Claude again. Before: the API rejects it with a 400 error.
messages.append({"role": "user", "content": [
{"type": "text", "text": "Lookup done:"},
{"type": "tool_result",
"tool_use_id": block.id,
"content": order_json},
]})
Two mistakes: Claude's assistant turn with the tool_use block was never appended, and text comes before the tool_result.
After:
messages.append({"role": "assistant",
"content": response.content})
messages.append({"role": "user", "content": [
{"type": "tool_result",
"tool_use_id": block.id,
"content": order_json},
]})
response = client.messages.create(
model=MODEL, max_tokens=2048,
tools=tools, messages=messages)
The result now immediately follows the call it answers, and the next request carries the whole exchange.