Skip to main content

How to Set the Anthropic API Key for LangChain in Python

· 12 min read
Jagdish Kumawat
Founder @ Dewiride

LangChain's Claude integration needs your Anthropic API key, and it looks for it in an environment variable called ANTHROPIC_API_KEY. You can fill that variable from a .env file or set it in your terminal, or skip it and hand the key to the model in code. This guide tries all three with LangChain 1.5.2, shows which one wins when two of them disagree, and checks that a key arrived without ever printing it.

Syntax​

.env
ANTHROPIC_API_KEY=<your-key>
Terminal
export ANTHROPIC_API_KEY="<your-key>"
In code
model = init_chat_model("anthropic:<model>", api_key=<key>)
PartWhat it means
.envA text file in the project folder. load_dotenv() from python-dotenv copies its lines into the program's environment variables when the program starts
export / $env:Sets the variable in the terminal, for every program you start from that terminal window until you close it
api_key=<key>Gives the key to this one model directly. <key> is Python code that produces the key, such as a variable you read from somewhere else
<your-key>Your Claude API key, which starts with sk-ant-

LangChain's ChatAnthropic reference describes the key's setting, anthropic_api_key, as "Automatically read from env var ANTHROPIC_API_KEY if not provided". api_key is the short name init_chat_model passes it under.

The Example​

A project called claude-key-demo creates a Claude Opus 5.5 model, prints the key as LangChain stores it, and asks "What is 2 + 2?". The project sits in a folder with no other .env file above it, so each way of giving the key can be tested on its own.

Prerequisites​

  • uv. This guide uses uv 0.13.10 with Python 3.14.10.
  • A Claude API key with credit. The Claude API has no free tier. Each run below asks one short question, which costs a fraction of a cent.

Step 1: Create the Project​

Terminal
uv init --python 3.14 --no-package claude-key-demo
cd claude-key-demo
uv add langchain langchain-anthropic python-dotenv
Output
Initialized project `claude-key-demo` at `/Users/you/source/claude-key-demo`
Using CPython 3.14.10
Creating virtual environment at: .venv
Resolved 47 packages in 14ms
Installed 45 packages in 83ms

The list of the 45 packages follows, with langchain==1.5.2, langchain-anthropic==1.9.0 and python-dotenv==1.2.4 among them. Replace the main.py that uv init wrote with this one:

main.py
from dotenv import load_dotenv
from langchain.chat_models import init_chat_model

load_dotenv() # Reads ANTHROPIC_API_KEY from a .env file, if there is one.

model = init_chat_model("anthropic:claude-opus-5-5")
print("Key:", model.anthropic_api_key)

reply = model.invoke("What is 2 + 2? Answer with the number only.")
print("Answer:", reply.text)

The main.py script in a macOS-style code window: it calls load_dotenv(), creates the model with init_chat_model("anthropic"), prints Key: followed by model.anthropic_api_key, then asks what 2 + 2 is and prints the answer.

model.anthropic_api_key is where the model keeps the key it found. Its type is SecretStr, a string that prints as stars instead of its value, so the line shows whether a key arrived without ever showing the key. If you don't have a key yet, How to Get a Claude API Key walks through creating one in the Claude Console.

Step 2: Way 1, a .env File​

Create a file called .env in the project folder, with your key after the =:

.env
ANTHROPIC_API_KEY=sk-ant-your-key-here

Keep it out of Git before your first commit; How to Keep a .env File Out of Git with .gitignore shows how. Then run the script:

Terminal
uv run main.py
Output
Key: **********
Answer: 4

The terminal after uv run main.py with the key in .env: Key: followed by ten stars, then Answer: 4.

load_dotenv() copied the key from .env into ANTHROPIC_API_KEY, the model found it there, and the stars confirm it has one. Claude answered 4.

Step 3: Way 2, a Variable in the Terminal​

To see this way on its own, move the .env file out of the project folder first. Then set the variable in the terminal, with your key in place of the placeholder, and run the script again:

Terminal
export ANTHROPIC_API_KEY="sk-ant-your-key-here"
uv run main.py
Output
Key: **********
Answer: 4

The terminal after export ANTHROPIC_API_KEY with a placeholder key and uv run main.py: Key: followed by ten stars, then Answer: 4.

Both shells gave the same output. load_dotenv() found no .env this time, and the model read the key the terminal had set. The variable lasts only as long as that terminal window: PowerShell's documentation says "When you change environment variables in PowerShell, the change affects only the current session", and a variable set with export disappears when its terminal window closes.

Step 4: Way 3, the api_key Parameter​

api_key= hands the key to one model in code. Never type the key itself into the file, where it would be saved and shared with the code. Read it from somewhere else, for example from a variable with another name:

param.py
import os

from langchain.chat_models import init_chat_model

key = os.environ["REPORTS_CLAUDE_KEY"] # The key, stored under another name.
model = init_chat_model("anthropic:claude-opus-5-5", api_key=key)

reply = model.invoke("What is 2 + 2? Answer with the number only.")
print("Answer:", reply.text)

The param.py script in a macOS-style code window: it reads REPORTS_CLAUDE_KEY from os.environ, passes it to init_chat_model as api_key, asks what 2 + 2 is and prints the answer.

os.environ["REPORTS_CLAUDE_KEY"] reads an environment variable by its name. Set it in a terminal, with no .env file in the folder, and run the script:

Terminal
export REPORTS_CLAUDE_KEY="sk-ant-your-key-here"
uv run param.py
Output
Answer: 4

The terminal after export REPORTS_CLAUDE_KEY and uv run param.py: Answer: 4.

There was no ANTHROPIC_API_KEY anywhere, and the call worked, because the key came in through api_key=. That's the way to go when a key is stored under a different name, or comes from a password manager or a secrets service.

Which One Wins​

When two ways hold different keys, only one gets used. A wrong key that's still set in the terminal from an earlier test shows the order. Here the terminal holds a made-up key and .env holds the real one:

Terminal
export ANTHROPIC_API_KEY="sk-ant-not-a-real-key"
uv run main.py
unset ANTHROPIC_API_KEY
uv run main.py
Output
Key: **********
Traceback (most recent call last):
...
langchain_anthropic.chat_models.AnthropicAuthenticationError: 401 invalid x-api-key (request_id: req_011C…, path: /v1/messages, type: authentication_error)
Key: **********
Answer: 4

The terminal with a made-up key set in the terminal: the first run prints the stars and ends with AnthropicAuthenticationError: 401 invalid x-api-key, and after unset ANTHROPIC_API_KEY the second run prints the stars and Answer: 4.

I've shortened the traceback to its first and last lines. The first run used the made-up key from the terminal, even though .env held a real one, and Claude's API answered 401 invalid x-api-key. The stars were there both times: they show that a key arrived, not that it's the right one. load_dotenv() doesn't replace variables that are already set; its reference describes override, which is False unless you pass override=True, as "Whether to override the system environment variables with the variables from the .env file." After unset in bash, or Remove-Item in PowerShell, the .env key was used again and the call worked.

The api_key= parameter wins over both. With a real key in ANTHROPIC_API_KEY and a made-up one in REPORTS_CLAUDE_KEY, param.py used the made-up one:

Terminal
export ANTHROPIC_API_KEY="sk-ant-your-key-here"
export REPORTS_CLAUDE_KEY="sk-ant-not-a-real-key"
uv run param.py
Output
Traceback (most recent call last):
...
langchain_anthropic.chat_models.AnthropicAuthenticationError: 401 invalid x-api-key (request_id: req_011C…, path: /v1/messages, type: authentication_error)

The terminal with a real key in ANTHROPIC_API_KEY and a made-up key in REPORTS_CLAUDE_KEY: uv run param.py ends with AnthropicAuthenticationError: 401 invalid x-api-key.

So the order is:

OrderWayWhy
1api_key= in codeThe variable is read only "if not provided"
2A variable set in the terminalload_dotenv() doesn't override it
3The .env fileUsed when neither of the others is set

With No Key at All​

With no .env file, nothing set in the terminal and no api_key=, the stars are missing and the call fails before anything is sent:

Terminal
uv run main.py
Output
Key:
Traceback (most recent call last):
...
TypeError: Anthropic authentication failed: no API key or authorization credentials were provided. Set the ANTHROPIC_API_KEY environment variable, pass api_key=..., auth_token=..., or credentials=... to ChatAnthropic, or configure the anthropic SDK's own credential resolution (a profile, or the workload identity federation environment variables). If you are routing through the LangSmith gateway, set LANGSMITH_GATEWAY and LANGSMITH_GATEWAY_API_KEY.

The terminal after uv run main.py with no key anywhere: Key: with nothing after it, then the shortened traceback ending with TypeError: Anthropic authentication failed: no API key or authorization credentials were provided.

Key: with nothing after it means the model has an empty key. The error message lists the same ways this guide used. If you do have a .env file and still get this error, Fixed: TypeError: Anthropic authentication failed covers the most common reason: a script that runs from outside the project folder.

Common Mistakes​

MistakeWhat happensDo this instead
Typing the key into the code: api_key="sk-ant-..."The key is saved in the file and travels with every copy of the codeRead it from .env or an environment variable
Leaving an old key set in the terminal401 invalid x-api-key, although .env holds the right keyunset ANTHROPIC_API_KEY, or Remove-Item -Path Env:\ANTHROPIC_API_KEY in PowerShell
Reading the stars as proof the key is rightA made-up key printed the same **********Treat the stars as "a key is set"; only a call proves it's valid

Troubleshooting​

SymptomLikely causeFix
TypeError: Anthropic authentication failed: no API key or authorization credentials were provided.No key reached the modelUse one of the three ways above
AnthropicAuthenticationError: 401 invalid x-api-keyThe key that won is wrong, revoked or mistypedCheck the order above, then the key itself. Claude's error reference says a 401 means "There's an issue with your credential"
Key: prints stars but the call fails with 401A wrong key wins, often an old one in the terminalClear the terminal variable, or open a new terminal

FAQ​

Which way should I use?​

A .env file for a project you work on, because every run finds the key without extra steps. A terminal variable for a quick test. api_key= when the key is stored under another name or comes from a secrets service.

Does printing the model show my key?​

No. The key is a SecretStr, so print(model.anthropic_api_key) printed **********. Even repr(model), which lists all of the model's settings, showed it as anthropic_api_key=SecretStr('**********').

Why not set the key with os.environ in the code?​

os.environ["ANTHROPIC_API_KEY"] = "sk-ant-..." works, but it puts the key in the file, the same problem as typing it into api_key=. Keep the key outside the code and let the program read it.

Conclusion​

LangChain's Claude model read the key from ANTHROPIC_API_KEY, whether load_dotenv() filled it from .env or the terminal set it, and api_key= gave it a key directly. When they disagreed, api_key= won, then the terminal variable, then .env, and the stars that model.anthropic_api_key printed showed only that some key had arrived.

Additional Resources​