Complete Anthropic Claude API Tutorial: From Basics to Advanced Features
Anthropic Claude is one of the most capable Large Language Models (LLMs) available today, known for its strong reasoning abilities, large context window (up to 200K tokens), and excellent safety features. In this tutorial, we'll learn how to use the Claude API through the Anthropic Python SDK, covering everything from initial setup, basic chat, streaming, vision (image analysis), tool use (function calling), to prompt caching for cost optimization.
Why Claude API?
Before we start coding, here are some reasons why the Claude API deserves consideration for your AI projects:
- Large Context Window: Supports up to 200K tokens, enabling processing of long documents in a single request.
- Strong Reasoning: Extended thinking allows Claude to think step-by-step before answering.
- Built-in Tool Use: Claude can call functions/tools you define, ideal for building AI agents.
- Vision: Capable of analyzing images directly through the API.
- Prompt Caching: Save up to 90% on costs for frequently repeated prompts.
- Streaming: Real-time responses for a better user experience.
Installation and Setup
1. Install Anthropic Python SDK
pip install anthropic
2. Get Your API Key
Create an account at console.anthropic.com, then create an API key on the Settings > API Keys page.
3. Set Environment Variable
export ANTHROPICAPIKEY="sk-ant-api03-xxxxx"
Or save it in a .env file:
ANTHROPICAPIKEY=sk-ant-api03-xxxxx
4. Verify Installation
import anthropic
client = anthropic.Anthropic()
print("Anthropic SDK version:", anthropic.version)
Basic Usage: Simple Chat
Let's start with the most basic example, sending a message to Claude and getting a response:
import anthropic
client = anthropic.Anthropic()
message = client.messages.create(
model="claude-sonnet-4-6",
maxtokens=1024,
messages=[
{"role": "user", "content": "Explain what machine learning is in 3 sentences."}
]
)
print(message.content[0].text)
Using System Prompts
System prompts help set Claude's behavior and persona:
message = client.messages.create(
model="claude-sonnet-4-6",
maxtokens=1024,
system="You are a senior data science assistant who explains complex concepts using simple analogies.",
messages=[
{"role": "user", "content": "What is gradient descent?"}
]
)
print(message.content[0].text)
Multi-turn Conversation
For multi-turn conversations, send the entire conversation history:
messages = [
{"role": "user", "content": "What is a neural network?"},
{"role": "assistant", "content": "A neural network is a computational model inspired by the human brain..."},
{"role": "user", "content": "How do you train one?"}
]
message = client.messages.create(
model="claude-sonnet-4-6",
maxtokens=1024,
messages=messages
)
print(message.content[0].text)
Streaming Responses
For real-time applications like chatbots, streaming allows you to display the response token by token:
import anthropic
client = anthropic.Anthropic()
with client.messages.stream(
model="claude-sonnet-4-6",
maxtokens=1024,
messages=[
{"role": "user", "content": "Write a brief guide on deploying ML models to production."}
]
) as stream:
for text in stream.textstream:
print(text, end="", flush=True)
print()
Streaming with Event Handling
For more granular control, you can handle various events:
with client.messages.stream(
model="claude-sonnet-4-6",
maxtokens=1024,
messages=[
{"role": "user", "content": "Explain the transformer architecture."}
]
) as stream:
for event in stream:
if event.type == "contentblockdelta":
if event.delta.type == "textdelta":
print(event.delta.text, end="", flush=True)
elif event.type == "messagestop":
print("\n[Done]")
Vision: Image Analysis
Claude can analyze images sent through the API. This is extremely useful for OCR, chart analysis, or visual descriptions:
From URL
import anthropic
client = anthropic.Anthropic()
message = client.messages.create(
model="claude-sonnet-4-6",
maxtokens=1024,
messages=[
{
"role": "user",
"content": [
{
"type": "image",
"source": {
"type": "url",
"url": "https://upload.wikimedia.org/wikipedia/commons/thumb/3/3a/Cat03.jpg/1200px-Cat03.jpg"
}
},
{
"type": "text",
"text": "Describe this image in detail."
}
]
}
]
)
print(message.content[0].text)
From Local File (Base64)
import anthropic
import base64
client = anthropic.Anthropic()
with open("chart.png", "rb") as f:
imagedata = base64.standardb64encode(f.read()).decode("utf-8")
message = client.messages.create(
model="claude-sonnet-4-6",
maxtokens=1024,
messages=[
{
"role": "user",
"content": [
{
"type": "image",
"source": {
"type": "base64",
"mediatype": "image/png",
"data": imagedata
}
},
{
"type": "text",
"text": "Analyze this chart. What are the key insights?"
}
]
}
]
)
print(message.content[0].text)
Tool Use (Function Calling)
Tool use allows Claude to call functions you define. This is the foundation for building AI agents:
import anthropic
import json
client = anthropic.Anthropic()
tools = [
{
"name": "getweather",
"description": "Get weather information for a specific city",
"inputschema": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "City name, e.g., Jakarta"
},
"unit": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
"description": "Temperature unit"
}
},
"required": ["city"]
}
},
{
"name": "calculate",
"description": "Perform mathematical calculations",
"inputschema": {
"type": "object",
"properties": {
"expression": {
"type": "string",
"description": "Math expression, e.g., 2+2"
}
},
"required": ["expression"]
}
}
]
message = client.messages.create(
model="claude-sonnet-4-6",
maxtokens=1024,
tools=tools,
messages=[
{"role": "user", "content": "What's the weather like in Jakarta today?"}
]
)
print("Stop reason:", message.stopreason)
for block in message.content:
if block.type == "tooluse":
print(f"Tool call: {block.name}")
print(f"Input: {json.dumps(block.input, indent=2)}")
Agentic Loop: Executing Tools and Continuing the Conversation
In real-world scenarios, you need to execute the tool Claude requests, then send the results back:
import anthropic
import json
client = anthropic.Anthropic()
def getweather(city, unit="celsius"):
weatherdata = {
"Jakarta": {"temp": 32, "condition": "Partly cloudy"},
"Tokyo": {"temp": 18, "condition": "Clear"},
}
data = weatherdata.get(city, {"temp": 25, "condition": "Unknown"})
return json.dumps(data)
def processtoolcall(toolname, toolinput):
if toolname == "getweather":
return getweather(toolinput["city"], toolinput.get("unit", "celsius"))
return json.dumps({"error": "Tool not found"})
tools = [
{
"name": "getweather",
"description": "Get weather information for a specific city",
"inputschema": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "City name"},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
},
"required": ["city"]
}
}
]
messages = [{"role": "user", "content": "Compare the weather in Jakarta and Tokyo today."}]
while True:
response = client.messages.create(
model="claude-sonnet-4-6",
maxtokens=1024,
tools=tools,
messages=messages
)
if response.stopreason == "endturn":
for block in response.content:
if hasattr(block, "text"):
print(block.text)
break
if response.stopreason == "tooluse":
messages.append({"role": "assistant", "content": response.content})
toolresults = []
for block in response.content:
if block.type == "tooluse":
result = processtoolcall(block.name, block.input)
toolresults.append({
"type": "toolresult",
"tooluseid": block.id,
"content": result
})
messages.append({"role": "user", "content": toolresults})
Prompt Caching
Prompt caching is an extremely useful feature for saving costs and improving speed. When you send the same prompt repeatedly (such as a long system prompt or reference document), Claude can cache that portion:
import anthropic
client = anthropic.Anthropic()
longsystemprompt = """You are a senior data analysis assistant with expertise in:
Python, Pandas, NumPy, Scikit-learn
SQL and database management
Statistics and probability
Machine learning and deep learning
Data visualization with Matplotlib and Seaborn
... (imagine this is a very long prompt with hundreds of lines of instructions)
"""
message = client.messages.create(
model="claude-sonnet-4-6",
maxtokens=1024,
system=[
{
"type": "text",
"text": longsystemprompt,
"cachecontrol": {"type": "ephemeral"}
}
],
messages=[
{"role": "user", "content": "How should I handle missing values in a dataset?"}
]
)
print(message.content[0].text)
print(f"Input tokens: {message.usage.inputtokens}")
print(f"Cache read tokens: {message.usage.cachereadinputtokens}")
print(f"Cache creation tokens: {message.usage.cachecreationinputtokens}")
The cache lasts for 5 minutes. A second request with the same system prompt will be much cheaper as it reads from cache.
Caching Reference Documents
with open("companyhandbook.txt", "r") as f:
handbook = f.read()
message = client.messages.create(
model="claude-sonnet-4-6",
maxtokens=1024,
system=[
{
"type": "text",
"text": "You are an HR assistant that answers questions based on the following company handbook.",
},
{
"type": "text",
"text": handbook,
"cachecontrol": {"type": "ephemeral"}
}
],
messages=[
{"role": "user", "content": "How many annual leave days do new employees get?"}
]
)
Extended Thinking
Extended thinking allows Claude to show its reasoning process before providing a final answer. This is invaluable for complex problems:
import anthropic
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-sonnet-4-6",
maxtokens=16000,
thinking={
"type": "enabled",
"budgettokens": 10000
},
messages=[
{
"role": "user",
"content": "A company has 3 years of sales data. Year 1: $500K, Year 2: $650K, Year 3: $780K. Predict Year 4 sales using linear regression. Show the calculation steps."
}
]
)
for block in response.content:
if block.type == "thinking":
print("=== Thinking Process ===")
print(block.thinking)
print()
elif block.type == "text":
print("=== Answer ===")
print(block.text)
Async Client
For applications requiring high concurrency, use the async client:
import anthropic
import asyncio
async def analyzedocument(doctext, question):
client = anthropic.AsyncAnthropic()
message = await client.messages.create(
model="claude-sonnet-4-6",
maxtokens=1024,
messages=[
{"role": "user", "content": f"Document:\n{doctext}\n\nQuestion: {question}"}
]
)
return message.content[0].text
async def main():
documents = [
("Q1 Report: Revenue up 15%...", "What are the key highlights?"),
("Q2 Report: Expansion to 3 new cities...", "What's the expansion plan?"),
("Q3 Report: Cost optimization achieved...", "How much was saved?"),
]
tasks = [analyzedocument(doc, q) for doc, q in documents]
results = await asyncio.gather(tasks)
for i, result in enumerate(results):
print(f"\nDocument {i+1}: {result[:200]}...")
asyncio.run(main())
Message Batches API
For high-volume batch processing at 50% lower cost:
import anthropic
client = anthropic.Anthropic()
batch = client.messages.batches.create(
requests=[
{
"customid": "review-1",
"params": {
"model": "claude-sonnet-4-6",
"maxtokens": 1024,
"messages": [
{"role": "user", "content": "Review this code: def add(a,b): return a+b"}
]
}
},
{
"customid": "review-2",
"params": {
"model": "claude-sonnet-4-6",
"maxtokens": 1024,
"messages": [
{"role": "user", "content": "Review this code: def multiply(x,y): return xy"}
]
}
}
]
)
print(f"Batch ID: {batch.id}")
print(f"Status: {batch.processingstatus}")
Error Handling and Best Practices
Retry Logic
import anthropic
client = anthropic.Anthropic(maxretries=3)
try:
message = client.messages.create(
model="claude-sonnet-4-6",
maxtokens=1024,
messages=[
{"role": "user", "content": "Hello!"}
]
)
print(message.content[0].text)
except anthropic.RateLimitError:
print("Rate limit reached. Try again later.")
except anthropic.APIConnectionError:
print("Failed to connect to API. Check your internet connection.")
except anthropic.APIStatusError as e:
print(f"API error: {e.statuscode} - {e.message}")
Best Practices
claude-sonnet-4-6 for general tasks, claude-opus-4-6 for complex tasks, claude-haiku-4-5 for lightweight and fast tasks.message.usage to track token consumption and costs.print(f"Input tokens: {message.usage.inputtokens}")
print(f"Output tokens: {message.usage.outputtokens}")
Example Project: Simple RAG with Claude
Here's an example implementation of simple Retrieval-Augmented Generation:
import anthropic
client = anthropic.Anthropic()
knowledgebase = {
"products": "We sell 3 plans: Basic ($10/month), Pro ($50/month), Enterprise (custom pricing).",
"refund": "Refunds can be requested within 30 days of purchase by contacting support.",
"support": "Support is available 24/7 via email support@example.com or chat on our website.",
}
def simpleretrieval(query):
querylower = query.lower()
relevantdocs = []
for key, value in knowledgebase.items():
if key in querylower or any(word in querylower for word in value.lower().split()[:5]):
relevantdocs.append(value)
return "\n".join(relevantdocs) if relevantdocs else "No relevant information found."
def raganswer(question):
context = simpleretrieval(question)
message = client.messages.create(
model="claude-sonnet-4-6",
maxtokens=1024,
system=[
{
"type": "text",
"text": "You are a customer support assistant. Answer questions ONLY based on the provided context. If the information is not available in the context, say you don't have that information.",
},
{
"type": "text",
"text": f"Context:\n{context}",
"cachecontrol": {"type": "ephemeral"}
}
],
messages=[
{"role": "user", "content": question}
]
)
return message.content[0].text
print(raganswer("How much does the Pro plan cost?"))
print(rag_answer("How do I get a refund?"))
Conclusion
The Anthropic Claude API offers a comprehensive set of capabilities for building modern AI applications. Here are the key features you should master:
- Messages API as the foundation for all interactions with Claude
- Streaming for responsive user experiences
- Vision for multimodal applications that analyze images
- Tool Use for building AI agents that can interact with external systems
- Prompt Caching for cost optimization in production
- Extended Thinking for problems requiring deep reasoning
- Batches API for high-volume processing at lower costs
With these features under your belt, you're ready to build powerful, production-ready AI applications using the Claude API. Start with the simple examples in this tutorial, then scale up according to your project needs.