Fixed: TypeError: Anthropic authentication failed: no API key or authorization credentials were provided
A LangChain script stopped with TypeError: Anthropic authentication failed: no API key or authorization credentials were provided, although the project's .env file held a working Claude API key. The script lived in a folder outside the project, and load_dotenv() looks for .env from the script's own folder, not from the folder you run it in. Moving the script next to .env, or loading find_dotenv(usecwd=True), fixed it.
What I Was Doing
I had a LangChain project called hello-langchain, set up the way Set Up Your Python Environment for LangChain sets one up: Python 3.14.10 with langchain 1.5.2, langchain-anthropic 1.9.0 and python-dotenv 1.2.4, and the Claude API key in a .env file in the project folder. Its main.py called Claude without a problem.
Then I wanted a second script that also prints how many tokens a call uses. I first hit the error with a measuring script I kept in another folder. The runs below repeat it with a scripts folder next to the project:
source/
├── hello-langchain/
│ ├── .env
│ ├── .git/
│ ├── .gitignore
│ ├── .python-version
│ ├── .venv/
│ ├── README.md
│ ├── main.py
│ ├── pyproject.toml
│ └── uv.lock
└── scripts/
└── count_tokens.py
from dotenv import load_dotenv
from langchain.chat_models import init_chat_model
load_dotenv() # Reads ANTHROPIC_API_KEY from the .env file.
model = init_chat_model("anthropic:claude-opus-5-5")
response = model.invoke("Welcome me to LangChain in one short sentence.")
print(response.text)
print(response.usage_metadata)

It loads .env with load_dotenv(), creates a Claude model with init_chat_model(), asks for a one-sentence welcome, and prints the reply and its token usage. I ran it from inside the project folder, so that uv run would use the project's packages:
uv run ../scripts/count_tokens.py
.. is the folder above the one you're in, so ../scripts/count_tokens.py is the script in the scripts folder next to the project.
What I Expected
A one-sentence welcome and the token counts, as main.py gives. The script ran from the same folder as main.py, and the .env there holds the key.
What I Got
A long traceback that ended in this error. I've shortened it to the lines that matter:
Traceback (most recent call last):
...
TypeError: "Could not resolve authentication method. Expected one of api_key, auth_token, or credentials to be set. Or for the `Authorization` header to be explicitly omitted"
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/you/source/hello-langchain/../scripts/count_tokens.py", line 7, in <module>
response = model.invoke("Welcome me to LangChain in one short sentence.")
...
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.

What I Checked
1. The error came at the first call, before anything was sent
The traceback holds two errors. The first came from anthropic, the Claude SDK that langchain-anthropic uses, while it built the headers of the request:
File "/Users/you/source/hello-langchain/.venv/lib/python3.14/site-packages/anthropic/_base_client.py", line 628, in _build_headers
self._validate_headers(headers, omitted)
~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^
File "/Users/you/source/hello-langchain/.venv/lib/python3.14/site-packages/anthropic/_client.py", line 397, in _validate_headers
raise TypeError(
'"Could not resolve authentication method. Expected one of api_key, auth_token, or credentials to be set. Or for the `Authorization` header to be explicitly omitted"'
)
langchain-anthropic caught it and raised the longer message, which names ANTHROPIC_API_KEY. The traceback showed three more things:
- Line 7 raised it, the
model.invoke(...)call. Line 6, which created the model, didn't complain: the missing key only showed up when the model made its first call. - The request was never sent. The SDK stopped while it was still building the request, so Claude's API never received it.
- The packages came from
hello-langchain/.venv, souv runhad used the project's environment. The imports weren't the problem.
The message says no key arrived at all. A wrong key fails differently: it reaches Claude's API, which answers 401 invalid x-api-key, as How to Set the Anthropic API Key for LangChain in Python shows.
2. Where the model reads its key
The ChatAnthropic reference says of its anthropic_api_key: "Automatically read from env var ANTHROPIC_API_KEY if not provided." The script passes no key, so the model reads the environment variable ANTHROPIC_API_KEY. I hadn't set it in the terminal, so its only source was load_dotenv(), which copies the lines of a .env file into the program's environment variables.
3. load_dotenv() found no .env
To see what load_dotenv() did, I put a second script beside count_tokens.py:
from dotenv import find_dotenv, load_dotenv
print("load_dotenv() returned", load_dotenv())
print("find_dotenv() found", repr(find_dotenv()))
load_dotenv() loads a .env file and returns whether it set anything. find_dotenv() returns the path of the .env file it would load, and repr() prints that path in quotes, so an empty result shows as ''. I ran it the same way, from the project folder:
uv run ../scripts/where_is_env.py
load_dotenv() returned False
find_dotenv() found ''

The python-dotenv reference explains both lines. load_dotenv() returns "True if at least one environment variable is set else False", and find_dotenv() returns the path "if found, or an empty string otherwise". So load_dotenv() found no .env file at all, and it said nothing about it: no warning and no error.
4. Where load_dotenv() looks
The python-dotenv documentation says that by default, load_dotenv() looks for a .env file "in the same directory as the Python script (or higher up the directory tree)". Its reference adds that when it's given no path, it uses find_dotenv() to find the file, with that function's default settings. find_dotenv() has a usecwd setting, False by default. Its source code, shown on the same page, starts the search in the current working directory, the folder you're in, only when usecwd is true. Otherwise it starts in the folder of the script that called it.
So the search started in scripts and went up from there: /Users/you/source/scripts, /Users/you/source, /Users/you, /Users and /. None of them has a .env file. The project's .env is in hello-langchain, a folder beside scripts, and never on that path.
Why It Happens
load_dotenv() looks for .env in the folder of the script that calls it, and then in each folder above that one. It doesn't look in the folder you run the script from. A script kept outside the project never reaches the project's .env, and load_dotenv() doesn't warn when it finds nothing. So ANTHROPIC_API_KEY stays unset, the model has no key, and its first call fails before it's sent. main.py works because it's in the same folder as .env.
The Fix
Move the script into the project folder, next to .env. From the project folder:
- bash/zsh
- PowerShell
mv ../scripts/count_tokens.py .
Move-Item ../scripts/count_tokens.py .
Both commands move a file, and . is the folder you're in. They print nothing when they work. You can also drag the file into the project folder in Finder or File Explorer.
After the Fix
Run the script from its new place:
uv run count_tokens.py
Welcome to LangChain, where you can chain together language models, tools, and data to build powerful AI applications!
{'input_tokens': 25, 'output_tokens': 95, 'total_tokens': 120, 'input_token_details': {'cache_read': 0, 'cache_creation': 0, 'ephemeral_5m_input_tokens': 0, 'ephemeral_1h_input_tokens': 0}, 'output_token_details': {'reasoning': 59}}

Now load_dotenv() starts in the script's own folder, hello-langchain, finds .env there, and the call goes through. It used 25 input tokens and 95 output tokens, 59 of them Claude's thinking (reasoning). At Claude Opus 5.5's $4 per million input tokens and $20 per million output tokens, that's about $0.002.
Another Fix: Look for .env from the Folder You Run In
If the script has to stay in its own folder, tell load_dotenv() which file to load. Replace everything in scripts/count_tokens.py with:
from dotenv import find_dotenv, load_dotenv
from langchain.chat_models import init_chat_model
load_dotenv(find_dotenv(usecwd=True)) # Looks for .env from the folder you run the script in.
model = init_chat_model("anthropic:claude-opus-5-5")
response = model.invoke("Welcome me to LangChain in one short sentence.")
print(response.text)
print(response.usage_metadata)

Only the first and fourth lines changed. find_dotenv(usecwd=True) starts its search in the folder you run the script from and returns the path of the .env it finds, and load_dotenv() loads that file. The reference describes this pattern: to change find_dotenv()'s defaults, call it yourself and pass its result to load_dotenv(). Run the script from the project folder, as before:
uv run ../scripts/count_tokens.py
Welcome to LangChain, where you can start building powerful applications with language models!
{'input_tokens': 25, 'output_tokens': 26, 'total_tokens': 51, 'input_token_details': {'cache_read': 0, 'cache_creation': 0, 'ephemeral_5m_input_tokens': 0, 'ephemeral_1h_input_tokens': 0}, 'output_token_details': {'reasoning': 0}}

It worked from outside the project. This time Claude didn't think before it answered, so the call used 26 output tokens, about $0.0006. The script now finds the .env of the folder you run it from, so always run it from the project folder.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
| Keeping a script outside the project and running it from the project folder | load_dotenv() finds no .env, and the first call raises this TypeError | Keep the script next to .env, or load find_dotenv(usecwd=True) |
Naming the variable ANTHROPIC_KEY in .env | load_dotenv() returns True, and the call still raises this TypeError | Name it exactly ANTHROPIC_API_KEY |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
This TypeError, and load_dotenv() returns False | No .env in the script's folder or any folder above it | Move the script next to .env, or use find_dotenv(usecwd=True) |
This TypeError, and load_dotenv() returns True | The .env file doesn't set ANTHROPIC_API_KEY | Check the variable's name in .env |
401 invalid x-api-key instead | A key arrived, but Claude's API rejected it | Check the key itself |
FAQ
What if load_dotenv() returns True and I still get the error?
Then it found a .env file, but that file doesn't set ANTHROPIC_API_KEY. I gave a small project a .env file that names the variable ANTHROPIC_KEY instead:
ANTHROPIC_KEY=sk-ant-your-key-here
Its script printed what load_dotenv() returned before it called Claude:
from dotenv import load_dotenv
from langchain.chat_models import init_chat_model
print("load_dotenv() returned", load_dotenv())
model = init_chat_model("anthropic:claude-opus-5-5")
response = model.invoke("Welcome me to LangChain in one short sentence.")
print(response.text)
uv run main.py
load_dotenv() returned True
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.
True means it set a variable, ANTHROPIC_KEY. The model reads only ANTHROPIC_API_KEY, so it still had no key. Name the variable exactly ANTHROPIC_API_KEY.
Why does main.py work when this script doesn't?
main.py is in the same folder as .env, so load_dotenv() finds the file in the first folder it checks. Where it looks depends on where the script is, not on where you run it from.
Does the failed run cost anything?
It didn't reach Claude's API. The SDK raised the error while it was still building the request, before sending it, so Claude never received a request to answer or bill.
Can I set the key in the terminal instead?
Yes. A key set as an environment variable in the terminal reaches the model without a .env file, and load_dotenv() doesn't replace a variable that's already set. How to Set the Anthropic API Key for LangChain in Python shows how, in bash and PowerShell.
Conclusion
TypeError: Anthropic authentication failed: no API key or authorization credentials were provided meant that no key reached the model at all. The .env file held the key, but the script lived outside the project, and load_dotenv() looks for .env from the script's own folder upward, so it never found the file. Moving the script next to .env, or loading find_dotenv(usecwd=True) and running it from the project folder, made the call work.
Additional Resources
- python-dotenv — where
load_dotenv()looks by default, and how it reads.envfiles. - load_dotenv and find_dotenv — their settings, what they return, and their source code.
- ChatAnthropic — the
anthropic_api_keyfield and where it reads the key from. - Errors — the errors Claude's API returns, including
401 authentication_error.
