Install Anthropic SDK

Su Suriya Ravichandran Updated 10 Nov 2026
13 min read ·Lesson 4 of 200

What Installing the SDK Does

The Anthropic Python SDK is published on the Python Package Index (PyPI) under the name anthropic. When you install it, pip:

  1. Finds a compatible release. It checks PyPI for the newest version that supports your Python version.
  2. Downloads it. Packages are usually distributed as wheels (.whl files), which are prebuilt archives that install quickly.
  3. Resolves dependencies. It works out which other libraries the SDK needs, such as Pydantic and the httpx2 HTTP client, and which versions of them are compatible.
  4. Copies everything into site-packages. This is the folder where your Python interpreter looks for importable modules.

After installation, import anthropic works in any program run by that same Python interpreter. That last point is why virtual environments matter so much.

The basic command is:

python -m pip install anthropic

The rest of this lesson shows how to do it the recommended way: inside a virtual environment, verified, and recorded so it can be repeated.


Step 1: Create a Project Folder

Keep each project in its own folder:

mkdir claude-tutorial
cd claude-tutorial

The virtual environment, your scripts, and your dependency file will all live here.


Step 2: Create a Virtual Environment

What a Virtual Environment Is

A virtual environment is a self-contained folder with its own Python interpreter link and its own site-packages directory. Packages installed inside it are invisible to other projects and to the system Python.

Why You Should Use One

Without virtual environments, every project on your computer shares one set of installed packages. That causes real problems:

  • Version conflicts. Project A needs pydantic 1.x and Project B needs 2.x. Only one can be installed globally.
  • Breaking the operating system. On many Linux distributions and on macOS with Homebrew, system tools depend on the system Python's packages. Modifying them can break those tools. Modern systems now block global installs for this reason (see Common Mistakes).
  • Unreproducible setups. You cannot tell which packages a project actually needs when everything is installed in one place.

A virtual environment per project solves all three.

Create It

# macOS / Linux
python3 -m venv .venv
# Windows
py -m venv .venv
  • -m venv runs Python's built-in venv module.
  • .venv is the folder name. The leading dot is a widely used convention. Many editors, including VS Code, detect a .venv folder automatically, and it is easy to exclude from Git.

Activate It

Activation changes your terminal session so that python and pip refer to the environment's interpreter:

# macOS / Linux (bash, zsh)
source .venv/bin/activate
:: Windows Command Prompt
.venv\Scripts\activate.bat
# Windows PowerShell
.venv\Scripts\Activate.ps1

When activation works, your prompt shows the environment name:

(.venv) user@laptop:~/claude-tutorial$

Confirm that python now points into the project:

python -c "import sys; print(sys.executable)"
/home/user/claude-tutorial/.venv/bin/python

On Windows, the path ends in .venv\Scripts\python.exe.

What activation actually does: it puts the environment's bin folder (Scripts on Windows) at the front of your PATH. When you type python, the shell finds the environment's interpreter first. Activation affects only the current terminal window.

To leave the environment:

deactivate

Note: You can also skip activation and call the environment's interpreter directly, for example .venv/bin/python script.py or .venv\Scripts\python.exe script.py. This is common in scripts, cron jobs, and service configurations.


Step 3: Install the SDK

With the environment active:

python -m pip install anthropic

Typical output (abbreviated; package versions and the dependency list will differ):

Collecting anthropic
  Downloading anthropic-2.0.0-py3-none-any.whl (...)
Collecting ... (the SDK's dependencies)
  ...
Installing collected packages: ..., anthropic
Successfully installed anthropic-2.0.0 ...

How to read it:

  • Collecting anthropic means pip found the package on PyPI.
  • anthropic-2.0.0-py3-none-any.whl is the wheel filename: package name, version, then compatibility tags. py3-none-any means it is pure Python and runs on any OS.
  • The following Collecting lines are the dependencies pip resolved automatically.
  • Successfully installed lists everything that was added to the environment.

Note: If pip prints a notice that a newer version of pip is available, you can upgrade it with python -m pip install --upgrade pip. It is optional, but a current pip resolves dependencies more reliably.


Step 4: Verify the Installation

Check the Version

python -c "import anthropic; print(anthropic.__version__)"
2.0.0

If this prints a version, the package is installed and importable by this interpreter.

Inspect the Package

python -m pip show anthropic
Name: anthropic
Version: 2.0.0
Summary: The official Python library for the anthropic API
Location: /home/user/claude-tutorial/.venv/lib/python3.13/site-packages
Requires: ...
Required-by:

The two most useful lines are:

  • Location shows where it was installed. It should be inside your .venv folder.
  • Requires lists the SDK's dependencies.

Run a Smoke Test

A smoke test is a minimal run that confirms the basics work. This one creates a client and sends a tiny request. It needs an API key, which Lessons 6 and 7 show how to create and set:

from anthropic import Anthropic

client = Anthropic()

message = client.messages.create(
    model="claude-opus-5-5",
    max_tokens=1024,
    messages=[{"role": "user", "content": "Reply with exactly: installation works"}],
)

print("".join(block.text for block in message.content if block.type == "text"))
installation works

Why the code looks this way:

  • max_tokens=1024, even though the expected reply is two words: the model may think before answering, and thinking tokens count toward max_tokens. With a tiny limit, the budget could run out before any text is written (Lesson 13). You pay only for the tokens actually generated, so a generous limit costs nothing extra.
  • Joining the text blocks instead of reading message.content[0].text: with current models, the first content block can be a thinking block, which has no text attribute. Filtering blocks by type works in every case (Lessons 11 and 16).

If you do not have an API key yet, it is enough that import anthropic succeeds. Come back to this test after Lesson 7.


Installing Extras

Platform integrations need extra dependencies, requested with square brackets:

python -m pip install "anthropic[bedrock]"        # Amazon Bedrock
python -m pip install "anthropic[vertex]"         # Google Cloud (Google managed)
python -m pip install "anthropic[google_cloud]"   # Google Cloud (Anthropic managed)
python -m pip install "anthropic[aws]"            # Claude Platform on AWS
python -m pip install "anthropic[aiohttp]"        # aiohttp backend for the async client

You can combine extras:

python -m pip install "anthropic[bedrock,aiohttp]"

Why the quotes are needed: some shells, especially zsh (the default on macOS), treat square brackets as file-matching patterns. Without quotes, zsh reports no matches found: anthropic[bedrock] and does not run pip. Quoting passes the text to pip unchanged. Quotes are harmless in other shells, so always use them.


Installing a Specific Version

Sometimes you need an exact version, for example to match a teammate's setup or to reproduce a bug:

python -m pip install "anthropic==2.0.0"      # Exactly this version
python -m pip install "anthropic>=2.0,<3"     # Any 2.x release
python -m pip install "anthropic<2"           # Stay on the previous major version
SpecifierMeaning
==2.0.0Exactly version 2.0.0
>=2.0,<3At least 2.0, but below 3.0
~=2.0Compatible release: >=2.0 and ==2.* (same as >=2.0,<3)
<2Anything before 2.0

Major SDK versions can contain breaking changes (Lesson 5), so production projects usually allow minor updates but block the next major version.


Recording Dependencies

A project should list its dependencies in a file, so anyone (including you, on another machine) can recreate the environment with one command.

requirements.txt

Create a requirements.txt file in the project folder:

anthropic>=2.0,<3

Install everything in it:

python -m pip install -r requirements.txt

There are two styles:

StyleHowUse for
Hand-written rangesWrite anthropic>=2.0,<3 yourselfLibraries and flexible projects
Frozen exact versionspython -m pip freeze > requirements.txtApplications that need identical environments everywhere

pip freeze lists every installed package with its exact version, including dependencies. That makes deployments reproducible, but it means you must update the file deliberately.

pyproject.toml

Modern Python projects often declare dependencies in pyproject.toml:

[project]
name = "claude-tutorial"
version = "0.1.0"
requires-python = ">=3.10"
dependencies = [
    "anthropic>=2.0,<3",
]

Tools such as uv and Poetry manage this file for you.

Exclude the Environment from Git

Add this to .gitignore:

.venv/

The environment contains thousands of files and machine-specific paths. Commit the requirements file instead, and recreate the environment wherever you need it.


Alternative Installation Tools

uv

uv is a fast package and project manager. It creates the virtual environment and records dependencies automatically:

uv init claude-tutorial
cd claude-tutorial
uv add anthropic
uv run main.py
  • uv init creates a project with a pyproject.toml.
  • uv add anthropic creates .venv if needed, installs the SDK, and adds it to pyproject.toml and the lock file uv.lock.
  • uv run main.py runs the script inside the project environment, with no manual activation.

In an existing pip-style environment, uv pip install anthropic works as a faster replacement for pip install.

Poetry

poetry add anthropic

Poetry adds the dependency to pyproject.toml, updates poetry.lock, and installs it into the project's environment.

Jupyter Notebooks

Inside a notebook cell, use the %pip magic command:

%pip install anthropic

Why %pip and not !pip: %pip always installs into the kernel the notebook is running on. !pip runs whatever pip the shell finds first, which may belong to a different Python. That leads to the familiar "installed but still ModuleNotFoundError" problem. Restart the kernel after installing if the import still fails.

ToolInstall commandCreates environmentRecords dependency
pip + venvpython -m pip install anthropicManually (python -m venv)Manually (requirements.txt)
uvuv add anthropicAutomaticallyAutomatically (pyproject.toml, uv.lock)
Poetrypoetry add anthropicAutomaticallyAutomatically (pyproject.toml, poetry.lock)
Jupyter%pip install anthropicUses the kernel's environmentNo

All of them install the same package from PyPI. Choose based on your project's workflow. This tutorial uses pip + venv because it is built into Python.


Uninstalling

python -m pip uninstall anthropic

pip asks for confirmation (add -y to skip it). Dependencies that were installed alongside the SDK are not removed automatically. The cleanest way to reset an environment completely is to delete the .venv folder and create a new one.


Practical Example: A Complete Setup from Scratch

This is the full sequence for a new project on macOS or Linux. Windows equivalents are shown in the comments.

# 1. Create and enter the project folder
mkdir claude-tutorial && cd claude-tutorial

# 2. Create and activate the virtual environment
python3 -m venv .venv               # Windows: py -m venv .venv
source .venv/bin/activate           # Windows PowerShell: .venv\Scripts\Activate.ps1

# 3. Upgrade pip (optional, recommended)
python -m pip install --upgrade pip

# 4. Record and install the dependency
echo "anthropic>=2.0,<3" > requirements.txt
python -m pip install -r requirements.txt

# 5. Keep the environment out of Git
echo ".venv/" > .gitignore

# 6. Verify
python -c "import anthropic; print('anthropic', anthropic.__version__)"

Expected final output:

anthropic 2.0.0

Why this order: the environment is created and activated before anything is installed, so nothing lands in the system Python. The dependency is written to requirements.txt before installing, so the file and the environment always agree. Verification comes last, so it tests the final state.

On another machine, recreating this environment takes three commands: create the venv, activate it, and run pip install -r requirements.txt.


Common Mistakes

error: externally-managed-environment

What happens: running pip install anthropic outside a virtual environment on a recent Linux distribution, or with Homebrew's Python on macOS, fails with error: externally-managed-environment.

Why: these systems mark their Python as managed by the operating system. pip refuses to modify it, so that system tools that depend on it do not break. This behavior is defined in Python standard PEP 668.

Fix: create and activate a virtual environment, then install. Do not use --break-system-packages to work around it for project code.

Installing with sudo

What happens: sudo pip install anthropic installs into the system Python as root.

Why it is a problem: it can overwrite packages the OS depends on, it creates files your normal user cannot modify, and it bypasses project isolation.

Fix: never use sudo with pip for project work. Use a virtual environment.

ModuleNotFoundError After a "Successful" Install

What happens: pip says Successfully installed anthropic, but the script fails with ModuleNotFoundError: No module named 'anthropic'.

Why: the package went into one interpreter, and the script runs with another. Typical causes are a terminal without the venv activated, an editor configured with a different interpreter, or a notebook kernel pointing elsewhere.

Fix:

  1. Run python -c "import sys; print(sys.executable)" in the same place you run your script.
  2. Run python -m pip show anthropic and compare its Location.
  3. In VS Code, use Python: Select Interpreter and choose the interpreter inside .venv.

PowerShell Refuses to Run the Activation Script

What happens: .venv\Scripts\Activate.ps1 fails with a message that running scripts is disabled on this system.

Why: PowerShell's execution policy blocks local scripts by default on some Windows systems.

Fix: allow locally created scripts for your user account, then activate again:

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

Alternatively, use Command Prompt and .venv\Scripts\activate.bat.

zsh: no matches found: anthropic[bedrock]

Why: zsh interprets the square brackets.

Fix: quote the requirement: python -m pip install "anthropic[bedrock]".

Committing the Virtual Environment

What happens: the .venv folder ends up in Git.

Why it is a problem: it bloats the repository, contains machine-specific paths, and does not work on other operating systems.

Fix: add .venv/ to .gitignore, remove the folder from Git tracking with git rm -r --cached .venv, and commit requirements.txt instead.

Installing a Similarly Named Package

What happens: a typo or an unofficial package name installs a different library, possibly a malicious one. This kind of name-squatting is called typosquatting.

Fix: the official package is exactly anthropic. Check the name before pressing Enter, and confirm with pip show anthropic that the Summary describes the official library.


Best Practices

  • One virtual environment per project, created before installing anything.
  • Use python -m pip so the package goes into the interpreter you actually run.
  • Record dependencies in a file (requirements.txt or pyproject.toml) and commit it. Never commit .venv.
  • Use version ranges that block the next major version (anthropic>=2.0,<3) so major upgrades with breaking changes are deliberate.
  • Pin exact versions for deployments (pip freeze or a lock file) so production matches what you tested.
  • Install extras only when needed. The base package is enough unless you use a cloud platform or the aiohttp backend.
  • Verify after installing with anthropic.__version__ and pip show anthropic, especially on servers and in CI.

Exercise

  1. Create a new project folder with a virtual environment, and install the SDK from a requirements.txt file.
  2. Use pip show anthropic to find the installation Location. Confirm that it is inside your .venv.
  3. Deactivate the environment and run python -c "import anthropic". What happens, and why?
  4. Delete .venv, recreate it, and reinstall from requirements.txt. How many commands did it take?
Show answers
  1. Use python3 -m venv .venv, activate it, write anthropic>=2.0,<3 to requirements.txt, then run python -m pip install -r requirements.txt.
  2. The Location should contain .venv/lib/pythonX.Y/site-packages (or .venv\Lib\site-packages on Windows).
  3. Outside the environment, python refers to the system interpreter, which normally does not have the SDK. You get ModuleNotFoundError: No module named 'anthropic'. This demonstrates the isolation that virtual environments provide.
  4. Three commands: create the venv, activate it, and run python -m pip install -r requirements.txt. That is the benefit of recording dependencies in a file.

0 Comments

Reviewed before they appear

No comments yet.

Anthropic SDK Using Python
Anthropic SDK Intro Claude API Intro SDK Requirements Install Anthropic SDK Upgrade the SDK Create an API Key Set API Keys Use Environment Variables Import Anthropic Create a Client Send Your First Message Choose a Claude Model Set Max Tokens Read a Response Print Response Text Understand Message Blocks Use System Prompts Send User Messages Set Temperature Handle Stop Reasons Messages API Intro Create Messages Use Message Roles Send Conversation History Continue a Conversation Build a Chat Loop Reset Chat History Use Multiple Turns Inspect Message IDs Read Usage Data Write Clear Prompts Set a System Prompt Add Context to Prompts Use Prompt Templates Add Examples to Prompts Request JSON Output Use XML Tags Control Response Length Improve Prompt Quality Avoid Prompt Injection Read Text Blocks Read Content Blocks Check Stop Reasons Count Input Tokens Count Output Tokens Count Tokens Before Sending Limit Output Tokens Use Stop Sequences Read Request IDs Parse API Responses Streaming Intro Stream Text Output Use Stream Events Use Stream Helpers Get Final Messages Stream Async Responses Handle Stream Errors Build a Live Chat Stream Long Responses Close Streams Safely Build a Chatbot Keep Chat History Manage Chat Sessions Add Chat Memory Build a CLI Chatbot Build a Web Chatbot Use Flask with Claude Use FastAPI with Claude Return JSON from an API Add Chat Error Messages Async SDK Intro Create an Async Client Send Async Messages Use asyncio Run Parallel Requests Stream Async Text Handle Async Errors Set Async Timeouts Close Async Clients Choose Sync or Async Tool Use Intro Define a Tool Create Tool Schemas Send Tools to Claude Read Tool Calls Run Python Tools Return Tool Results Continue After Tool Use Control Tool Choice Handle Tool Errors Use the beta_tool Decorator Create a Tool Runner Add Tool Docstrings Validate Tool Inputs Use Multiple Tools Limit Tool Calls Log Tool Activity Build a Weather Tool Build a Search Tool Build a Calculator Tool Structured Output Intro Request JSON Data Validate JSON Output Use Pydantic Models Handle Invalid JSON Extract Fields from Text Generate Typed Data Use Image URLs Send Base64 Images Read PDFs with Claude Use Output Schemas Build Data Extraction Test Structured Responses Send Image Inputs Upload Files Use File IDs Process Text Files Summarize Documents Extract Table Data Handle File Errors Read Cache Usage Reduce Repeated Input Costs Debug Cache Misses Prompt Caching Intro Enable Prompt Caching Cache System Prompts Cache Long Context Test Cache Performance Use Cache Breakpoints Cache Best Practices Message Batches Intro Create a Message Batch Set Batch IDs Check Batch Status List Message Batches Get Batch Results Process Batch Outputs Handle Failed Batch Items Use Batches for Bulk Tasks Compare Batches and Requests Handle API Errors Handle Rate Limits Retry Failed Requests Set Request Timeouts Handle Network Errors Use Exponential Backoff Build Reliable API Calls Use Extended Thinking Log API Errors Track Request IDs Paginate API Results Set Thinking Budgets Read Thinking Blocks Use Tool Search Use Web Search Tools Use Computer Tools Use Citations Use Token Counting Read Raw Responses Set Custom Headers Use Claude on AWS Bedrock Use Claude on Vertex AI Use Claude on Microsoft Foundry Configure Cloud Credentials Choose a Cloud Provider Compare API Integrations Configure Provider Clients Handle Cloud Errors Use Cloud SDK Extras Deploy Cloud Apps Protect API Keys Use a .env File Ignore Secrets in Git Validate User Input Reduce Prompt Injection Limit Tool Permissions Avoid Unsafe Tool Calls Sanitize Tool Results Set Usage Limits Review Security Logs Test SDK Functions Mock API Responses Test Error Handling Test Streaming Code Measure Token Usage Track API Costs Configure Logging Deploy with Docker Deploy a FastAPI App Monitor Production Apps Build a Claude Chatbot Build a Text Summarizer Build a Code Explainer Build a JSON Extractor Build a PDF Assistant Build a Streaming Chat App Build a Tool-Calling Agent Build a Batch Processor Build a Research Assistant Build a Claude API Dashboard
Ask about this post
AI Ask about this post

Ask questions about Install Anthropic SDK and get answers drawn from it.

Signed-in readers only.