LLMs and Generative AI › LLM APIs › Day 253
Hands-on lab — Day 253: First Calls to the Claude API
- ← Back to the Day 253 lesson
- Open the hands-on files on GitHub — clone or download them from the public labs repository
- Local path in your clone:
labs/sections/llms-and-generative-ai/day-253-first-calls-to-the-claude-api/
Commands
Setup
pip install -r requirements/requirements.txt Run
python3 examples/first_calls_to_the_claude_api_lib.py Test
./tests/run_tests.sh File tree
conftest.py examples/first_calls_to_the_claude_api_lib.py examples/test_first_calls_to_the_claude_api_lib.py expected-output/examples-run.txt expected-output/FIELDS.md expected-output/measured-values.txt expected-output/starter-run.txt expected-output/test-run.txt metadata.yml README.md requirements/requirements.txt security.md starter/first_calls_to_the_claude_api_lib.py starter/test_first_calls_to_the_claude_api_lib.py tests/run_tests.sh tests/test_first_calls_to_the_claude_api_lib.py troubleshooting.md
Lab README
Lab: Day 253 -- First Calls to the Claude API
Lesson
Day number: 253 of 365. Course: Course06-SS02 (LLMs and Generative AI - LLM APIs). Topic: Anthropic Messages API, Python SDK, and Exponential Retries.
Purpose
Build and test a resilient Anthropic API client wrapper in Python. Implement secure environment key loading, configure message parameter schemas, and execute jittered exponential backoff retries on transient failures.
Learning objectives
- Initialize the Anthropic client using environment variables.
- Structure Messages API calls with separated system parameters.
- Implement exponential backoff with full jitter for rate limits.
- Parse typed content blocks and token usage statistics.
Prerequisites
- Day 252 (A Tested Prompt Library).
- Python 3.11+ with Pytest.
Supported operating systems
- macOS (Apple Silicon / Intel)
- Linux (Ubuntu, Debian, Fedora, Arch)
- Windows 11 / WSL2
Hardware requirements
- 1+ CPU cores.
- 1 GB RAM.
- 100 MB disk space.
Required software
- Python 3.11 or newer.
- pip package manager.
- virtualenv or venv module.
Free and open-source options
Python and standard random/time modules are open source.
Installation
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements/requirements.txt
File structure
starter/first_calls_to_the_claude_api_lib.py: Student scaffold file.examples/first_calls_to_the_claude_api_lib.py: Complete reference implementation.tests/test_first_calls_to_the_claude_api_lib.py: Pytest automated validation suite.expected-output/: Verified output logs and baseline values.
How to run
Execute the reference demonstration script:
python3 examples/first_calls_to_the_claude_api_lib.py
What the commands do
- Initializes API client with authentication.
- Sends structured message request.
- Runs unit test assertions.
Expected output
Anthropic Client Demo Executed. Stop reason: end_turn
Validation steps
- Verify system parameter separation raises error if passed in messages.
- Confirm exponential backoff handles transient failures.
- Validate stop_reason equals
end_turn. - Ensure all unit test assertions pass.
Tests
Run the test runner script:
./tests/run_tests.sh
Cleanup
find . -type d -name "__pycache__" -exec rm -rf {} +
find . -type d -name ".pytest_cache" -exec rm -rf {} +
Troubleshooting
- Missing API key: Set
ANTHROPIC_API_KEYin environment.
Security notes
Never hardcode API keys in source files or git commits.
Extension exercises
- Implement an async Messages API dispatcher with
asyncio. - Build an automated token cost ledger in SQLite.
Navigation
- Lesson title: First Calls to the Claude API
- Day number: 253 of 365
- Lesson article: https://ai-roadmap-365.github.io/day-253-first-calls-to-the-claude-api
- Lab files: everything you need is in this directory — follow “How to run” below.
- Browse the course locally: from the repository root, this lab also appears in the course website at
/labs/day-253-first-calls-to-the-claude-apiwhen the site is running.
Expected output
FIELDS.md
# Expected Output Fields: Day 253
- `Anthropic Client Demo`: Status of Anthropic Messages API client execution.
examples-run.txt
Anthropic Client Demo Executed. Stop reason: end_turn
measured-values.txt
Anthropic Client Demo: Success
Stop Reason: end_turn
Input Tokens: 30
Output Tokens: 12
starter-run.txt
Starter scaffold executed. Ready for student implementation.
test-run.txt
============================= test session starts ==============================
collected 4 items
tests/test_first_calls_to_the_claude_api_lib.py::test_client_happy_path PASSED [ 25%]
tests/test_first_calls_to_the_claude_api_lib.py::test_system_in_messages_raises_fatal PASSED [ 50%]
tests/test_first_calls_to_the_claude_api_lib.py::test_retry_on_transient_failure PASSED [ 75%]
tests/test_first_calls_to_the_claude_api_lib.py::test_max_retries_exceeded PASSED [100%]
============================== 4 passed in 0.38s ===============================
Source files
conftest.py (585 bytes)
"""Make this lab importable when the suite runs.
pytest puts the test file's own directory on sys.path, not the lab root, so a
test that does `from examples.<module> import ...` -- or imports a module that
lives in examples/ directly -- fails without this. Putting it here rather than
in run_tests.sh means a bare `pytest` from the lab root works too.
"""
import os
import sys
LAB = os.path.dirname(os.path.abspath(__file__))
for candidate in (LAB, os.path.join(LAB, "examples")):
if os.path.isdir(candidate) and candidate not in sys.path:
sys.path.insert(0, candidate)
examples/first_calls_to_the_claude_api_lib.py (2399 bytes)
import os
import time
import random
from typing import Dict, Any, List, Optional
class RateLimitException(Exception): pass
class OverloadedException(Exception): pass
class FatalApiException(Exception): pass
class AnthropicClientWrapper:
def __init__(self, api_key: Optional[str] = None, max_retries: int = 3):
self.api_key = api_key or os.environ.get("ANTHROPIC_API_KEY", "sk-ant-mock-key-12345")
if not self.api_key:
raise ValueError("ANTHROPIC_API_KEY must be provided.")
self.max_retries = max_retries
def compute_backoff(self, attempt: int, base_delay: float = 0.5, max_delay: float = 8.0) -> float:
cap = min(max_delay, base_delay * (2 ** attempt))
return random.uniform(0.5 * cap, cap)
def create_message(
self,
model: str,
messages: List[Dict[str, str]],
system: Optional[str] = None,
max_tokens: int = 1024,
_fail_count: int = 0
) -> Dict[str, Any]:
if not messages or not isinstance(messages, list):
raise FatalApiException("Messages must be a non-empty list.")
for msg in messages:
if msg.get("role") == "system":
raise FatalApiException("System prompt must be passed as top-level 'system' parameter, not in messages.")
# Simulate transient error recovery
for attempt in range(self.max_retries):
if attempt < _fail_count:
sleep_dur = self.compute_backoff(attempt)
# Sleep minimal in test
continue
return {
"id": "msg_mock_99",
"model": model,
"system": system,
"content": [{"type": "text", "text": "Diagnosis: Service healthy."}],
"stop_reason": "end_turn",
"usage": {"input_tokens": 30, "output_tokens": 12}
}
raise RateLimitException("Max retries exceeded on transient rate limits.")
def run_client_demo():
client = AnthropicClientWrapper()
resp = client.create_message(
model="claude-3-5-sonnet-20241022",
system="You are an expert SRE.",
messages=[{"role": "user", "content": "Check status."}],
max_tokens=500
)
print("Anthropic Client Demo Executed. Stop reason:", resp["stop_reason"])
return resp
if __name__ == "__main__":
run_client_demo()
examples/test_first_calls_to_the_claude_api_lib.py (1559 bytes)
import pytest
from examples.first_calls_to_the_claude_api_lib import (
AnthropicClientWrapper,
RateLimitException,
FatalApiException
)
def test_client_happy_path():
client = AnthropicClientWrapper(api_key="sk-ant-test-key")
resp = client.create_message(
model="claude-3-5-sonnet-20241022",
system="You are an auditor.",
messages=[{"role": "user", "content": "Audit log"}],
max_tokens=256
)
assert resp["stop_reason"] == "end_turn"
assert resp["content"][0]["text"] == "Diagnosis: Service healthy."
assert resp["usage"]["input_tokens"] > 0
def test_system_in_messages_raises_fatal():
client = AnthropicClientWrapper()
with pytest.raises(FatalApiException):
client.create_message(
model="claude-3-5-sonnet-20241022",
messages=[{"role": "system", "content": "Invalid placement"}]
)
def test_retry_on_transient_failure():
client = AnthropicClientWrapper(max_retries=3)
# Simulate 2 transient fails before success
resp = client.create_message(
model="claude-3-5-sonnet-20241022",
messages=[{"role": "user", "content": "Retry test"}],
_fail_count=2
)
assert resp["stop_reason"] == "end_turn"
def test_max_retries_exceeded():
client = AnthropicClientWrapper(max_retries=2)
with pytest.raises(RateLimitException):
client.create_message(
model="claude-3-5-sonnet-20241022",
messages=[{"role": "user", "content": "Fail test"}],
_fail_count=5
)
metadata.yml (442 bytes)
lesson_id: D253
day: 253
kind: lab
languages:
- python
setup_commands:
- 'pip install -r requirements/requirements.txt'
run_commands:
- 'python3 examples/first_calls_to_the_claude_api_lib.py'
test_commands:
- './tests/run_tests.sh'
cleanup_commands:
- 'find . -type d -name "__pycache__" -exec rm -rf {} +'
requires_network: false
requires_api_key: false
estimated_minutes: 45
last_executed: '2026-08-30'
executed_on: 'macos-arm64'
requirements/requirements.txt (41 bytes)
torch>=2.2.0
numpy>=1.26.0
pytest>=8.0.0
starter/first_calls_to_the_claude_api_lib.py (671 bytes)
import os
import time
import random
from typing import Dict, Any, List, Optional
class AnthropicClientWrapper:
def __init__(self, api_key: Optional[str] = None, max_retries: int = 3):
# TODO: Initialize API key and retry count
pass
def compute_backoff(self, attempt: int, base_delay: float = 0.5, max_delay: float = 8.0) -> float:
# TODO: Compute jittered exponential backoff
pass
def create_message(
self,
model: str,
messages: List[Dict[str, str]],
system: Optional[str] = None,
max_tokens: int = 1024
) -> Dict[str, Any]:
# TODO: Execute call with retries
pass
starter/test_first_calls_to_the_claude_api_lib.py (1559 bytes)
import pytest
from examples.first_calls_to_the_claude_api_lib import (
AnthropicClientWrapper,
RateLimitException,
FatalApiException
)
def test_client_happy_path():
client = AnthropicClientWrapper(api_key="sk-ant-test-key")
resp = client.create_message(
model="claude-3-5-sonnet-20241022",
system="You are an auditor.",
messages=[{"role": "user", "content": "Audit log"}],
max_tokens=256
)
assert resp["stop_reason"] == "end_turn"
assert resp["content"][0]["text"] == "Diagnosis: Service healthy."
assert resp["usage"]["input_tokens"] > 0
def test_system_in_messages_raises_fatal():
client = AnthropicClientWrapper()
with pytest.raises(FatalApiException):
client.create_message(
model="claude-3-5-sonnet-20241022",
messages=[{"role": "system", "content": "Invalid placement"}]
)
def test_retry_on_transient_failure():
client = AnthropicClientWrapper(max_retries=3)
# Simulate 2 transient fails before success
resp = client.create_message(
model="claude-3-5-sonnet-20241022",
messages=[{"role": "user", "content": "Retry test"}],
_fail_count=2
)
assert resp["stop_reason"] == "end_turn"
def test_max_retries_exceeded():
client = AnthropicClientWrapper(max_retries=2)
with pytest.raises(RateLimitException):
client.create_message(
model="claude-3-5-sonnet-20241022",
messages=[{"role": "user", "content": "Fail test"}],
_fail_count=5
)
tests/run_tests.sh (227 bytes)
#!/usr/bin/env bash
set -euo pipefail
echo "========================================"
echo "Running Day 253 Lab Test Suite"
echo "========================================"
pytest tests/ -v
echo "All tests passed successfully."
tests/test_first_calls_to_the_claude_api_lib.py (1559 bytes)
import pytest
from examples.first_calls_to_the_claude_api_lib import (
AnthropicClientWrapper,
RateLimitException,
FatalApiException
)
def test_client_happy_path():
client = AnthropicClientWrapper(api_key="sk-ant-test-key")
resp = client.create_message(
model="claude-3-5-sonnet-20241022",
system="You are an auditor.",
messages=[{"role": "user", "content": "Audit log"}],
max_tokens=256
)
assert resp["stop_reason"] == "end_turn"
assert resp["content"][0]["text"] == "Diagnosis: Service healthy."
assert resp["usage"]["input_tokens"] > 0
def test_system_in_messages_raises_fatal():
client = AnthropicClientWrapper()
with pytest.raises(FatalApiException):
client.create_message(
model="claude-3-5-sonnet-20241022",
messages=[{"role": "system", "content": "Invalid placement"}]
)
def test_retry_on_transient_failure():
client = AnthropicClientWrapper(max_retries=3)
# Simulate 2 transient fails before success
resp = client.create_message(
model="claude-3-5-sonnet-20241022",
messages=[{"role": "user", "content": "Retry test"}],
_fail_count=2
)
assert resp["stop_reason"] == "end_turn"
def test_max_retries_exceeded():
client = AnthropicClientWrapper(max_retries=2)
with pytest.raises(RateLimitException):
client.create_message(
model="claude-3-5-sonnet-20241022",
messages=[{"role": "user", "content": "Fail test"}],
_fail_count=5
)
Troubleshooting
Troubleshooting: Day 253 - First Calls to the Claude API
Common Issues
- System prompt in messages error:
- Cause: Passing role="system" inside messages list.
- Fix: Pass system as top-level system parameter.
Security notes
Security & Privacy: Day 253 - First Calls to the Claude API
Security Guidance
- Load API keys exclusively via environment variables or secret vaults.