Claude integration design
Start with a fictional Messages request
The Claude Messages API takes a conversation and returns a message with typed content blocks. A block is a piece of a message, such as text or a request to use a tool. Imagine an inventory assistant that drafts short labels for folders. The local mock below illustrates the request shape without using the Anthropic SDK. Its response is a simplified dictionary, not a captured live response; model name and usage are fictional. The printed label and stop reason are deterministic. Do not send the mock model name to a provider.
class MockMessages: def create(self, **request): assert request["model"] == "offline-demo" assert request["messages"][0]["role"] == "user" return {"content": [{"type": "text", "text": "Blue folder"}], "stop_reason": "end_turn", "usage": {"input_tokens": 12, "output_tokens": 2}}
client = MockMessages()reply = client.create(model="offline-demo", max_tokens=32, system="Return a short draft label.", messages=[{"role": "user", "content": "Label: blue folder"}])print(reply["content"][0]["text"])print(reply["stop_reason"])Map the request to the Python SDK
The official Python interface is Anthropic().messages.create(...) and the HTTP resource is POST /v1/messages. For the basic request pattern, pass instructions as the top-level system parameter and conversation turns in messages; user and assistant turns contain text or typed blocks. Some models support additional system-message patterns; this lesson uses the basic form only. max_tokens is an output limit, not a promise of output length. An inert SDK sketch follows; it defines a function but does not call it. Install and pin the approved anthropic package and verify signatures before authorized use.
import osfrom anthropic import Anthropic
def draft_label(approved_note): client = Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"], timeout=15.0, max_retries=0) return client.messages.create( model=os.environ["APPROVED_CLAUDE_MODEL"], max_tokens=64, system="Draft a short label.", messages=[{"role": "user", "content": approved_note}])Keep credentials on an authenticated server, never in browser code or logs. Claude app subscriptions and API billing are separate arrangements; some plans may offer specific API credit benefits, but verify eligibility rather than assuming them. The official catalog excerpt lists claude-sonnet-5-5 as a model ID; this is a catalog example, not an access guarantee. Check exact platform ID, version, capabilities, lifecycle and retention before selecting a model.
Inspect content and completion before use
A message can hold more than one text block, thinking blocks, tool calls, or other types. Do not assume content[0] is always text. end_turn indicates a natural end; max_tokens signals the output limit; tool_use requests client tools; stop_sequence indicates a configured stop. Other reasons may be supported, including refusal or pause_turn. The narrow local adapter below accepts only nonblank text-only end_turn messages and returns None for everything else. It assumes well-formed fixture keys, not arbitrary JSON. Joining blocks without separators is a chosen contract for this label example, not an API guarantee. The second fixture is incomplete and is deliberately discarded. Validate factual content even after a natural end.
def route_text(message): # Only complete, ordinary text-only replies are accepted here. if message["stop_reason"] != "end_turn": return None blocks = message["content"] if not blocks or any(b["type"] != "text" for b in blocks): return None result = "".join(b["text"] for b in blocks) return result if result.strip() else None
print(route_text({"stop_reason": "end_turn", "content": [ {"type": "text", "text": "Blue "}, {"type": "text", "text": "folder"}]}))print(route_text({"stop_reason": "max_tokens", "content": [ {"type": "text", "text": "Blue"}]}))Streaming and structured output
The Messages API streams server-sent events. A simplified text path is message_start, content_block_start, content_block_delta, content_block_stop, message_delta, message_stop. Text fragments have an index and a text_delta payload. Tool input can arrive as JSON fragments; do not dispatch from partial JSON. The official Python SDK recommends messages.stream() and offers accumulated final messages. A transport disconnect, error event or missing terminal event must not be interpreted as a complete result. Handle indices, non-text blocks, unknown events and final stop reason. Use the SDK rather than a homemade SSE parser. For supported models, the JSON output format is output_config={"format":{"type":"json_schema","schema":schema}}; schema limitations apply. Strict tool input is a separate capability. Check refusal, truncation and local semantic rules even when a schema is enabled. No provider streaming or schema enforcement was executed here.
Practice with two blocks and an incomplete reply
Modify the mock to return two text blocks forming a single label. Route it through route_text; expect the joined label. Next, change stop_reason to max_tokens or insert a tool_use block; expect None. Explain why the prior OpenAI Responses adapter cannot simply be reused: provider request fields, output objects, event names and call linkage differ. Review Chapter 33 for local semantic validation. The next lesson handles tool requests, errors and cache usage.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Claude integration design quiz
Apply the provider-specific offline integration contract.
Where do basic Messages API system instructions belong?
Why inspect the type of each Messages API content block?
How should the narrow label adapter handle max_tokens?
Which setting requests JSON output on supported Claude models?
When is it safe to dispatch a streamed tool request?