Anthropic Claude API Guide — Chat, Vision, Tool Use, and Streaming
In this tutorial, you'll learn about Anthropic Claude API Guide. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
The Anthropic Claude API gives you programmatic access to Claude's language models for chat, vision, tool use, and streaming across web and mobile applications.
What You'll Learn
- Setting up the Anthropic SDK and authenticating with an API key
- Sending chat completions via the Messages API with system prompts
- Streaming responses token-by-token for real-time UIs
- Implementing tool use (function calling) for external data access
- Analyzing images with Claude's vision capabilities
- Managing costs with prompt Caching and rate limits
Why the Anthropic Claude API Matters
Claude leads the industry in long-context reasoning (200K tokens), safety alignment via Constitutional AI, and nuanced instruction following. DodaTech's Doda Browser uses the Claude API for privacy-preserving content summarization, DodaZIP leverages it to analyze compressed file metadata for security risks, and Durga Antivirus Pro relies on Claude's extended thinking for multi-stage threat analysis.
flowchart LR
A["Your Application\nPython / JS / curl"] --> B["Anthropic API\ngateway.anthropic.com"]
B --> C["Claude Model\nSonnet / Opus / Haiku"]
C --> D["Response\nText / Tool Calls / Stream"]
D --> A
style B fill:#dbeafe,stroke:#2563eb
style C fill:#fef3c7,stroke:#d97706
1. Setup and Authentication
Install the Anthropic Python SDK and initialize the client with your API key. Keys are created at console.Anthropic.com and start with sk-ant-.
import anthropic
import os
client = anthropic.Anthropic(
api_key=os.environ["ANTHROPIC_API_KEY"]
)
Expected output: No output -- the client initializes silently. If <a href="/ai-frameworks-apis/anthropic/">Anthropic</a>_API_KEY is missing, Python raises KeyError, and the Anthropic SDK raises <a href="/ai-frameworks-apis/anthropic/">Anthropic</a>.AnthropicError.
Store the key as an environment variable in your shell profile or .env file. Never hardcode it in source code or commit it to version control.
2. Chat Completions with the Messages API
The Messages API is Claude's primary interface. You send a list of messages with alternating user and assistant roles and receive a model response.
response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=300,
system="You are a helpful <a href="/programming-languages/python/">Python</a> tutor. Explain concepts briefly with analogies.",
messages=[
{"role": "user", "content": "What is a Python generator?"}
]
)
print(response.content[0].text)
Expected output:
A generator is like a bookmark in a book: instead of reading the whole book at once, you read one page at a time and remember where you left off. In Python, a generator function uses `yield` to produce values lazily, saving memory for large sequences.
The max_tokens parameter is required -- Claude does not use a default. The system parameter accepts a string that guides Claude's behavior across the entire conversation.
3. Streaming Responses
Streaming delivers tokens as the model generates them, enabling progressive display in chat UIs and command-line tools.
with client.messages.stream(
model="claude-sonnet-4-20250514",
max_tokens=200,
messages=[
{"role": "user", "content": "List three benefits of streaming API responses."}
]
) as stream:
for text in stream.text_stream:
print(text, end="")
Expected output:
1. Lower perceived latency -- users see content immediately instead of waiting for the full response.
2. Progressive rendering -- chat UIs can display tokens as they arrive, creating a natural typing feel.
3. Early cancellation -- you can stop generation mid-stream if the initial output is sufficient.
Doda Browser uses streaming to show page summaries appearing character by character, giving users instant feedback while Claude processes the full context.
4. Tool Use (Function Calling)
Claude can request structured tool calls when it needs external data. Define tools with a JSON input schema, and Claude responds with tool_use content blocks.
import json
tools = [
{
"name": "get_weather",
"description": "Get the current weather for a location",
"input_schema": {
"type": "object",
"properties": {
"location": {"type": "string", "description": "City name, e.g. London"},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
},
"required": ["location"]
}
}
]
response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=500,
tools=tools,
messages=[
{"role": "user", "content": "What is the weather in Tokyo?"}
]
)
for block in response.content:
if block.type == "tool_use":
print(json.dumps(block.input, indent=2))
Expected output:
{
"location": "Tokyo",
"unit": "celsius"
}
You execute the tool against your data source and return the result in a tool_result content block. Claude then uses that result to form its final answer. Durga Antivirus Pro uses this pattern to let Claude query internal threat databases with file hashes and return structured risk assessments.
5. System Prompts
Claude's system parameter is a first-class concept -- it is processed differently from user messages and carries higher precedence for instruction following.
response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=400,
system="You are a security analyst at DodaTech. Analyze the following code and output "
"a JSON object with keys: severity (CRITICAL/HIGH/MEDIUM/LOW), vulnerability_type, "
"affected_lines, and remediation.",
messages=[
{"role": "user", "content": "password = request.GET.get('pass')\nquery = f'SELECT * FROM users WHERE pass = {password}'"}
]
)
print(response.content[0].text)
Expected output:
{
"severity": "CRITICAL",
"vulnerability_type": "SQL Injection",
"affected_lines": "Line 2: f-string interpolation of user input into SQL query",
"remediation": "Use parameterized queries: cursor.execute('SELECT * FROM users WHERE pass = %s', (password,))"
}
Claude follows system instructions more reliably than most models, making it ideal for applications where output format consistency is critical -- such as automated security scanning in Durga Antivirus Pro or structured data extraction in DodaZIP.
6. Vision (Image Analysis)
Claude can analyze images sent as base64-encoded data or via URL. This enables document processing, screenshot analysis, and visual content moderation.
import base64
with open("screenshot.png", "rb") as f:
image_data = base64.b64encode(f.read()).decode("utf-8")
response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=500,
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": "Describe the UI elements visible in this screenshot."},
{
"type": "image",
"source": {
"type": "base64",
"media_type": "image/png",
"data": image_data
}
}
]
}
]
)
print(response.content[0].text)
Expected output:
The screenshot shows a login form with:
- A "Username" text input field at the top
- A "Password" masked input field below it
- A "Remember me" checkbox underneath
- A blue "Sign In" button centered at the bottom
- A "Forgot password?" link in the lower-right corner
- The application logo in the top-left header area
The vision API accepts PNG, JPEG, GIF, and WebP formats. Images are resized and compressed by Claude's preprocessing layer. You can combine text and image content in any order within a single message.
7. Best Practices
Prompt Caching
Anthropic offers prompt Caching to reduce costs and latency when repeating the same system prompt or context across requests. Enable it by marking prefix content with "cache_control": {"type": "ephemeral"}.
response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=200,
system=[
{"type": "text", "text": "You are a security analyst. Analyze logs for threats."},
{"type": "text", "text": "Output format: SEVERITY | DESCRIPTION | TIMESTAMP", "cache_control": {"type": "ephemeral"}}
],
messages=[
{"role": "user", "content": "Analyze this log entry: 2025-01-15 03:14:22 ERROR failed login from 192.168.1.50"}
]
)
print(f"Cache created: {'cache_creation_input_tokens' in response.usage}")
Expected output:
Cache created: True
Cached prompts reduce input token costs by up to 90% and cut time-to-first-token by 2-3x. Cache entries expire after 5 minutes of inactivity.
Cost Management
| Model | Input (per 1M tokens) | Output (per 1M tokens) | Best For |
|---|---|---|---|
| Claude Haiku | $0.25 | $1.25 | Simple tasks, classification, extraction |
| Claude Sonnet | $3.00 | $15.00 | General chat, Code Generation, analysis |
| Claude Opus | $15.00 | $75.00 | Complex reasoning, research, deep analysis |
Use Haiku for high-volume classification and extraction. Reserve Opus for complex multi-step analysis where accuracy is paramount.
Rate Limits
Anthropic enforces rate limits per API key tier:
- Tier 1 (free trial): 5 RPM, 40K TPM
- Tier 2 ($50+ spent): 50 RPM, 200K TPM
- Tier 3 ($500+ spent): 500 RPM, 2M TPM
- Tier 4 ($5,000+ spent): 5,000 RPM, 20M TPM
Implement exponential backoff with the <a href="/ai-frameworks-apis/anthropic/">Anthropic</a>.RateLimitError catch. Batch smaller requests when possible.
import time
from anthropic import Anthropic, RateLimitError
client = Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
for attempt in range(5):
try:
response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=100,
messages=[{"role": "user", "content": "Hello"}]
)
break
except RateLimitError:
wait = 2 ** attempt
print(f"Rate limited. Retrying in {wait}s...")
time.sleep(wait)
Expected output:
(No output on success, or) Rate limited. Retrying in 1s...
Practice Questions
- What environment variable should hold your Anthropic API key and what prefix do keys start with?
- Why is
max_tokensrequired in every Messages API call? - How does Claude's
systemparameter differ from including instructions in the user message? - What content types does the
tool_useresponse block contain and how do you respond to it? - Which Claude model offers the lowest cost per token and what is it best suited for?
Answers:
<a href="/ai-frameworks-apis/anthropic/">Anthropic</a>_API_KEY-- keys start withsk-ant-. Never hardcode keys in source files.- Claude does not assume a default -- if omitted the API returns an error. It also controls the maximum output length for cost predictability.
- The
systemparameter sets persistent instructions that apply across the entire conversation with higher precedence. Instructions in user messages apply only to that turn and may be overridden by later messages. - A
tool_useblock containsname,id, andinput(the structured arguments). You respond by adding atool_resultcontent block with the sameidand the tool's output. - Claude Haiku ($0.25/M input) -- best for classification, moderation, extraction, and simple chat where speed and cost matter more than depth.
Challenge: Build a multi-step threat analysis pipeline: Claude Opus analyzes a network log for suspicious patterns, outputs a tool_use request to query API threat intelligence, and produces a final risk report with severity scores and mitigation steps.
Real-World Task: DodaZIP needs a Claude-powered feature that scans uploaded archive contents. Using the vision API, analyze screenshots of archived document previews to detect sensitive information (passwords, credit card numbers, personal data). Use a system prompt to enforce a JSON output schema with detected_fields, risk_score, and recommendation.
FAQ
{{< faq "Can I use Claude with LangChain?">}}
Yes. LangChain provides an ChatAnthropic integration that wraps the Messages API. It handles streaming, tool use, and memory out of the box. The LangChain guide covers building chains and agents with Claude. This is the fastest path to production for multi-step AI workflows.
{{< /faq >}}
Next Steps
Now that you have mastered the Anthropic Claude API, continue your learning:
- OpenAI API Guide -- compare Claude with GPT-4 and understand the differences
- [LangChain Guide](/machine-learning/LangChain-guide/) -- build chains and agents with Claude using LangChain
- AI Agents -- design autonomous AI agents powered by Claude and other LLMs
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro