惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Microsoft Azure Blog
Microsoft Azure Blog
WordPress大学
WordPress大学
小众软件
小众软件
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
V
V2EX
Hugging Face - Blog
Hugging Face - Blog
美团技术团队
博客园 - 三生石上(FineUI控件)
Last Week in AI
Last Week in AI
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园 - Franky
Microsoft Security Blog
Microsoft Security Blog
Y
Y Combinator Blog
A
About on SuperTechFans
The GitHub Blog
The GitHub Blog
U
Unit 42
H
Hackread – Cybersecurity News, Data Breaches, AI and More
云风的 BLOG
云风的 BLOG
IT之家
IT之家
MyScale Blog
MyScale Blog
V
Visual Studio Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
I
InfoQ
博客园 - 司徒正美

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
How to Use Claude API with Python: Complete Beginner's Gu...
Serhii Kalyn · 2026-05-08 · via DEV Community

Serhii Kalyna

The Anthropic Python SDK makes it simple to integrate Claude into your applications. In this guide you'll go from zero to a working chatbot in under 10 minutes — covering installation, your first API call, streaming, multi-turn conversations, and error handling.

Prerequisites

  • Python 3.8+
  • An Anthropic API key (console.anthropic.com)
  • Basic Python knowledge

Step 1: Install the SDK

pip install anthropic

Enter fullscreen mode Exit fullscreen mode

That's the only dependency you need. The SDK includes everything: the client, streaming support, and type hints.

Step 2: Set Your API Key

Store your key as an environment variable — never hardcode it in your source files:

export ANTHROPIC_API_KEY="sk-ant-..."

Enter fullscreen mode Exit fullscreen mode

Or create a .env file in your project root:

ANTHROPIC_API_KEY=sk-ant-...

Enter fullscreen mode Exit fullscreen mode

Load it with python-dotenv:

pip install python-dotenv

Enter fullscreen mode Exit fullscreen mode

Step 3: Your First API Call

Create a file main.py and add:

import anthropic

client = anthropic.Anthropic()  # reads ANTHROPIC_API_KEY from env

message = client.messages.create(
    model="claude-sonnet-4-6",
    max_tokens=1024,
    messages=[
        {"role": "user", "content": "Explain what an API is in 2 sentences."}
    ]
)

print(message.content[0].text)

Enter fullscreen mode Exit fullscreen mode

Run it:

python main.py

Enter fullscreen mode Exit fullscreen mode

You'll get a clean, concise response from Claude. The message.content[0].text contains the text output.

Step 4: Add a System Prompt

A system prompt sets the context and personality for Claude — it's the first thing Claude reads before any user message:

client = anthropic.Anthropic()

message = client.messages.create(
    model="claude-sonnet-4-6",
    max_tokens=1024,
    system="You are a senior Python developer. Answer concisely with code examples.",
    messages=[
        {"role": "user", "content": "How do I read a JSON file in Python?"}
    ]
)

print(message.content[0].text)

Enter fullscreen mode Exit fullscreen mode

Step 5: Streaming Responses

For a better user experience — especially with long outputs — use streaming so text appears word by word:

import anthropic

client = anthropic.Anthropic()

with client.messages.stream(
    model="claude-sonnet-4-6",
    max_tokens=1024,
    messages=[{"role": "user", "content": "Write a Python function to parse CSV files"}]
) as stream:
    for text in stream.text_stream:
        print(text, end="", flush=True)

print()  # newline at the end

Enter fullscreen mode Exit fullscreen mode

Step 6: Multi-Turn Conversations

Build a simple chatbot by keeping track of the message history:

import anthropic

client = anthropic.Anthropic()
conversation_history = []

def chat(user_message: str) -> str:
    conversation_history.append({
        "role": "user",
        "content": user_message
    })

    response = client.messages.create(
        model="claude-sonnet-4-6",
        max_tokens=1024,
        system="You are a helpful AI assistant.",
        messages=conversation_history
    )

    assistant_message = response.content[0].text
    conversation_history.append({
        "role": "assistant",
        "content": assistant_message
    })

    return assistant_message

# Example conversation
print(chat("What is Python?"))
print(chat("What are its main use cases?"))
print(chat("Which one is best for AI development?"))

Enter fullscreen mode Exit fullscreen mode

Each call passes the full history so Claude remembers what was said earlier in the conversation.

Step 7: Error Handling

Always wrap API calls in try/except for production code:

import anthropic

client = anthropic.Anthropic()

try:
    message = client.messages.create(
        model="claude-sonnet-4-6",
        max_tokens=1024,
        messages=[{"role": "user", "content": "Hello!"}]
    )
    print(message.content[0].text)

except anthropic.APIConnectionError as e:
    print(f"Connection error: {e}")
except anthropic.RateLimitError as e:
    print(f"Rate limit hit — slow down: {e}")
except anthropic.APIStatusError as e:
    print(f"API error {e.status_code}: {e.message}")

Enter fullscreen mode Exit fullscreen mode

Available Models

Choose the right Claude model for your use case:

  • claude-opus-4-7 — most capable, best for complex reasoning and analysis
  • claude-sonnet-4-6 — best balance of speed and intelligence (recommended for most apps)
  • claude-haiku-4-5-20251001 — fastest and most affordable, great for simple tasks

Key Parameters

The most important parameters in messages.create():

message = client.messages.create(
    model="claude-sonnet-4-6",   # which Claude model to use
    max_tokens=1024,              # maximum tokens in the response
    temperature=0.7,             # 0 = deterministic, 1 = creative
    system="...",                # system prompt (optional)
    messages=[...]               # conversation history
)

Enter fullscreen mode Exit fullscreen mode

💡 Tip: Use temperature=0 for code generation and factual tasks. Use higher values (0.7–1.0) for creative writing.

Complete Example: Simple CLI Chatbot

import anthropic

def main():
    client = anthropic.Anthropic()
    history = []
    print("Claude Chatbot — type 'quit' to exit\n")

    while True:
        user_input = input("You: ").strip()
        if user_input.lower() in ("quit", "exit"):
            break
        if not user_input:
            continue

        history.append({"role": "user", "content": user_input})

        with client.messages.stream(
            model="claude-sonnet-4-6",
            max_tokens=2048,
            system="You are a helpful assistant.",
            messages=history
        ) as stream:
            print("Claude: ", end="", flush=True)
            response_text = ""
            for text in stream.text_stream:
                print(text, end="", flush=True)
                response_text += text
            print()

        history.append({"role": "assistant", "content": response_text})

if __name__ == "__main__":
    main()

Enter fullscreen mode Exit fullscreen mode

What's Next?

Now that you have the basics working, here's what to explore next:

  • Tool use — let Claude call functions and APIs in your code
  • Vision — send images to Claude for analysis
  • Prompt caching — reduce costs on repeated context (up to 90% savings)
  • Batch API — process thousands of requests asynchronously at 50% discount

💡 Resources: Anthropic Docs | Python SDK on GitHub


Originally published at kalyna.pro