Messages API: Format, Response Object, and Chatbot
The messages structure with role and content, the Message object (id, stop_reason, usage), reading text from response blocks, response format via structured outputs instead of prefill, few-shot prompting, mid-conversation system messages, and a simple chatbot.
Messages Structure
Each message is a dictionary with two keys: role and content.
from anthropic import Anthropic
client = Anthropic()
def text_of(response):
return "".join(b.text for b in response.content if b.type == "text")
messages = [
{"role": "user", "content": "What flavors are used in Dr. Pepper?"}
]
response = client.messages.create(
model="claude-haiku-5-5",
max_tokens=2000,
messages=messages
)
print(text_of(response))
The response comes back as a list of content blocks. Current Claude models use adaptive thinking, so a thinking block may come before the text. The text_of helper joins the blocks whose type == "text", and every example below uses it. Code like response.content[0].text breaks on such a response.
Rules:
- The list starts with a user message, then roles alternate (user → assistant → user...).
- The model is trained on alternating turns. If you send several messages of the same role in a row, the API accepts them and merges them into a single turn.
- The last message should be from the user (or a system-role message, covered below). A trailing assistant message is a prefill, and current models (Claude 4.6 and later) reject it with a 400 error.
The rest of this lesson opens after a free sign-up
Sign up with email or Google: the first two lessons of every course stay open for good, and the whole catalog is open for 7 days. No card needed.


