Anthropic Claude API Guide — Prompt Engineering and Integration
The Anthropic Claude API provides access to Claude’s advanced language models with industry-leading safety features, extended thinking capabilities, and powerful tool use patterns.
What You’ll Learn
- Setting up the Anthropic API and authenticating requests
- Building conversations with the Messages API including system prompts
- Implementing tool use (function calling) and extended thinking
- Understanding Claude’s safety features and comparing with OpenAI
Why Claude Matters
Claude excels at nuanced instruction following, long-context reasoning (200K tokens), and safe AI deployment. DodaTech’s Doda Browser uses Claude for privacy-preserving content analysis where safety constraints are critical, and Durga Antivirus Pro leverages Claude’s extended thinking for complex threat analysis requiring step-by-step reasoning.
flowchart LR
A["API Key\n& Client Setup"] --> B["Messages API\nClaude 3.5 Sonnet"]
B --> C["System Prompts\n& Instructions"]
B --> D["Tool Use\nFunction Calling"]
B --> E["Extended\nThinking"]
B --> F["Streaming\nResponses"]
style B fill:#dbeafe,stroke:#2563eb
Setting Up the Client
Install the Anthropic SDK and initialize the client with your API key.
import anthropic
import os
client = anthropic.Anthropic(
api_key=os.environ["ANTHROPIC_API_KEY"]
)Expected output: No output — client initializes silently. Missing key raises anthropic.AnthropicError.
Messages API — Basic Chat
The Messages API accepts a list of messages and returns a model response. Claude uses alternating user and assistant roles.
response = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=200,
system="You are a concise Python expert. Keep answers under three sentences.",
messages=[
{"role": "user", "content": "What is a decorator in Python?"}
]
)
print(response.content[0].text)Expected output:
A decorator is a function that takes another function and extends its behavior without modifying it directly. You use the @decorator syntax to apply it. Common examples include @staticmethod, @classmethod, and custom decorators for logging or timing.System Prompts for Instruction Control
Claude’s system parameter lets you set persistent instructions that apply across the entire conversation. This is separate from the messages array.
response = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=300,
system="You are a security analyst at DodaTech. Analyze code for vulnerabilities. "
"Format your response with: risk level, affected lines, and remediation steps.",
messages=[
{"role": "user", "content": "Check this SQL query: query = f'SELECT * FROM users WHERE id = {user_input}'"}
]
)
print(response.content[0].text)Expected output:
Risk Level: CRITICAL
Affected Lines: Line 1 — f-string interpolation of user_input into SQL query
Remediation Steps: Use parameterized queries with placeholders (%s) instead of f-strings. Example: cursor.execute("SELECT * FROM users WHERE id = %s", (user_input,))Durga Antivirus Pro uses this pattern internally — system prompts define the analysis framework, then user messages provide the code or file to inspect.
Tool Use (Function Calling)
Claude can request tool calls when it needs external data or actions. Define tools using a JSON schema.
import json
tools = [
{
"name": "search_threat_database",
"description": "Look up a file hash in the threat intelligence database",
"input_schema": {
"type": "object",
"properties": {
"hash": {"type": "string", "description": "SHA256 hash of the file"}
},
"required": ["hash"]
}
}
]
response = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=500,
tools=tools,
messages=[
{"role": "user", "content": "Check if file hash a1b2c3d4 is a known threat"}
]
)
for block in response.content:
if block.type == "tool_use":
print(json.dumps(block.input, indent=2))Expected output:
{
"hash": "a1b2c3d4"
}Claude responds with a tool_use content block containing the structured input. You execute the tool, return the result in a tool_result block, and Claude continues its response.
Extended Thinking
Claude’s extended thinking mode reveals its step-by-step reasoning process, useful for complex analysis tasks.
response = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1000,
thinking={"type": "enabled", "budget_tokens": 500},
messages=[
{"role": "user", "content": "Design an algorithm to detect duplicate files efficiently."}
]
)
for block in response.content:
if block.type == "thinking":
print("Thinking:", block.thinking[:100] + "...")
if block.type == "text":
print("Answer:", block.text)Expected output:
Thinking: The user wants an algorithm for duplicate file detection. Let me think about the approaches...
First approach: compare file sizes — fast but not definitive
Second approach: hash file contents — accurate but requires reading all files
Optimal hybrid approach...
Answer: Use a multi-step approach: (1) Group by file size, (2) Hash first few KB of same-size files, (3) Full SHA256 hash of matching groups. This minimizes disk I/O while guaranteeing accuracy.Streaming Responses
Stream Claude’s responses token by token for real-time display.
with client.messages.stream(
model="claude-3-5-sonnet-20241022",
max_tokens=200,
messages=[{"role": "user", "content": "Write a haiku about JavaScript."}]
) as stream:
for text in stream.text_stream:
print(text, end="")Expected output:
Callbacks chain and flow,
Event loop dances with grace,
Async dreams take flight.Comparison with OpenAI
| Feature | Claude (Anthropic) | GPT-4 (OpenAI) |
|---|---|---|
| Context Window | 200K tokens | 128K tokens (GPT-4) |
| System Prompt | Separate system parameter | Via system role message |
| Tool Use | tool_use / tool_result blocks | tool_calls / tool message |
| Pricing (input) | $3.00 / M tokens (Sonnet) | $2.50 / M tokens (GPT-4) |
| Pricing (output) | $15.00 / M tokens | $10.00 / M tokens |
| Safety | Constitutional AI (built-in) | Moderation API (separate) |
| Thinking Mode | Built-in thinking block | No native equivalent |
Common Errors
1. InvalidAuthenticationError
The API key is missing or incorrect. Verify ANTHROPIC_API_KEY environment variable is set. Keys start with sk-ant-.
2. OverloadedError
Anthropic’s servers are at capacity. Implement retry with backoff. Use the anthropic.AnthropicError base class for catch-all handling.
3. ContextLengthExceededError
The conversation exceeds Claude’s 200K token limit. Implement conversation summarization or truncate older messages.
4. InvalidRequestError — Missing Required Field
The max_tokens parameter is required and must be a positive integer. Claude does not have a default — you must always specify it.
5. Tool Use Format Error
Tool result blocks must follow the exact format expected by Claude. Each tool_use must be answered with a corresponding tool_result using the same ID.
6. Safety Filter Triggered
Claude may refuse to generate harmful content. Review your prompts against Anthropic’s usage guidelines. Claude is more cautious than GPT-4 by design.
7. Model Not Available
The requested model version is deprecated or unavailable. Check the latest model IDs at docs.anthropic.com. Always pin to a specific version like claude-3-5-sonnet-20241022.
Practice Questions
- How does Claude’s
systemparameter differ from including instructions in user messages? - What is the maximum context window for Claude 3.5 Sonnet?
- How does tool use work in the Messages API?
- What is extended thinking and when should you use it?
- Which Claude model variant offers the best balance of speed and quality?
Answers:
- The
systemparameter sets persistent instructions across the entire conversation, while user message instructions apply only to that turn. System prompts are processed more efficiently. - 200,000 tokens — enough for documents of 150+ pages or extended conversation histories.
- Define tools with JSON schemas, Claude responds with
tool_useblocks containing structured inputs, you execute the tool and return results viatool_resultblocks. - Extended thinking reveals Claude’s reasoning process in a separate
thinkingcontent block. Use it for complex analysis, code review, and multi-step problem solving. claude-3-5-sonnet-20241022— fastest model with the best quality-to-speed ratio. Useclaude-3-opusfor maximum accuracy on difficult tasks.
Challenge: DodaZIP needs a feature that uses Claude to analyze compressed file contents and detect potential security risks. Build a Python script that takes a file listing, sends it to Claude with a security-focused system prompt, and returns risk assessments using tool use to query a mock threat database.
Mini Project: AI Security Analyzer
Build a CLI tool that analyzes Python code for security vulnerabilities using Claude:
import anthropic
import os
import sys
client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
def analyze_code(filepath):
with open(filepath) as f:
code = f.read()
response = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=800,
system="You are a security code reviewer. Analyze the provided code for: "
"SQL injection, XSS, command injection, path traversal, hardcoded secrets. "
"Format as a table with: Vulnerability | Severity | Location | Fix",
messages=[{"role": "user", "content": f"Analyze this code:\n\n{code}"}]
)
return response.content[0].text
if __name__ == "__main__":
print(analyze_code(sys.argv[1]))Try it: Save a Python file with intentional vulnerabilities and run the analyzer. Observe how Claude’s extended thinking catches issues a linter might miss.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro