Calling Anthropic API: messages
Use the Anthropic messages API: differences from OpenAI, system prompt placement, and Claude-specific best practices.
Calling Anthropic API: messages is a free AI Agents lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the AI Agents learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Why Anthropic?
Claude models often have stronger instruction-following, better tool use, and longer context windows than equivalent OpenAI models — and are sometimes cheaper.
Most production agents support both providers as a fallback.
Install the SDK
# pip install anthropic
import anthropic
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY from envYour First Call
The endpoint is messages.create:
response = client.messages.create(
model='claude-sonnet-4-5',
max_tokens=512,
system='You are a concise assistant.',
messages=[
{'role': 'user', 'content': 'Capital of France?'},
],
)
print(response.content[0].text)
# 'Paris.'Key Differences from OpenAI
systemis a top-level parameter, not a messagemax_tokensis REQUIREDcontentis a list of blocks (text, tool_use, etc.)- No
nparameter — use multiple calls
Content Blocks
Even text responses come as a list of blocks:
response.content # list of blocks
response.content[0].type # 'text' or 'tool_use'
response.content[0].text # the text content
response.stop_reason # 'end_turn' / 'max_tokens' / 'tool_use'
response.usage.input_tokens
response.usage.output_tokensMulti-Block Content
You can also send a list of content blocks in user messages (images, tool results):
messages = [{
'role': 'user',
'content': [
{'type': 'text', 'text': 'What is in this image?'},
{'type': 'image', 'source': {
'type': 'base64',
'media_type': 'image/png',
'data': image_base64
}}
]
}]Pre-filling the Assistant
Force the response to start a specific way:
messages = [
{'role': 'user', 'content': 'Return a JSON object.'},
{'role': 'assistant', 'content': '{'}
]
response = client.messages.create(
model='claude-sonnet-4-5',
max_tokens=512,
messages=messages,
)
# Output starts after '{', guaranteed to be JSON.Tool Use
Anthropic tool format is similar to OpenAI but uses input_schema:
tools = [{
'name': 'get_weather',
'description': 'Get current weather',
'input_schema': {
'type': 'object',
'properties': {'city': {'type': 'string'}},
'required': ['city']
}
}]
response = client.messages.create(
model='claude-sonnet-4-5',
max_tokens=1024,
tools=tools,
messages=messages,
)
if response.stop_reason == 'tool_use':
for block in response.content:
if block.type == 'tool_use':
print(block.name, block.input)Returning Tool Results
Tool results go into a user message with a tool_result block:
messages.append({
'role': 'user',
'content': [{
'type': 'tool_result',
'tool_use_id': 'toolu_abc',
'content': json.dumps(weather_data)
}]
})Prompt Caching
Anthropic supports prompt caching — mark long static prefixes with cache_control and pay 10% on cache hits:
system = [
{'type': 'text', 'text': '...long system prompt...',
'cache_control': {'type': 'ephemeral'}}
]
for block in system:
print(f"type={block['type']} cache_control={block['cache_control']}")
print("text preview:", block['text'][:30])
Extended Thinking
Claude has an "extended thinking" mode where it reasons internally before answering:
response = client.messages.create(
model='claude-sonnet-4-5',
max_tokens=4096,
thinking={'type': 'enabled', 'budget_tokens': 2048},
messages=messages,
)System Prompt Location
Where does the system prompt go in the Anthropic API?
Recap
You can now call both major providers. The differences are small but real — most teams build a thin adapter to swap between them.
Frequently asked questions
Is the “Calling Anthropic API: messages” lesson free?
Yes — the full text of “Calling Anthropic API: messages” is free to read here on the web, and the AI Agents course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the AI Agents course, upgrade to CoddyKit PRO.
What will I learn in “Calling Anthropic API: messages”?
Use the Anthropic messages API: differences from OpenAI, system prompt placement, and Claude-specific best practices. You practise AI Agents with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start AI Agents?
No prior experience is required. AI Agents on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Calling Anthropic API: messages” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this AI Agents lesson?
Yes. Every AI Agents lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Calling OpenAI API: chat.completions
- Calling Anthropic API: messages
- Streaming Responses (SSE)
- Cost Awareness: Token Counting and Budgets