Skip to main content

Fixed: "AnthropicConnectionError: Connection error." When a LangGraph Node Calls Claude

· 11 min read
Jagdish Kumawat
Founder @ Dewiride

A LangGraph graph whose node asks Claude worked from its project folder, but the same code in a script kept outside that folder failed with AnthropicConnectionError: Connection error. Nothing was wrong with the connection. load_dotenv() hadn't found the .env file, so the API key was empty, and telling it where to look fixed it.

What I Was Doing​

I was building a small LangGraph graph whose first node asks Claude through ChatAnthropic, from the langchain-anthropic package, with the API key in a .env file in the project folder. Run from the project folder, the graph worked. Then I wrote a second script that runs the same graph and also prints the request it sends to Claude. I saved it in a folder outside the project and ran it from the project folder with uv run python and the script's path, so that it used the project's packages.

The smallest setup that does the same thing has a project, claude-hello, and a folder next to it, tryouts:

Folders
source/
├── claude-hello/ ← the project: pyproject.toml, .venv, .env and main.py
└── tryouts/
└── ask.py ← a copy of main.py

.env holds the API key, in the form python-dotenv reads:

claude-hello/.env
ANTHROPIC_API_KEY=your-api-key

main.py builds a graph with one node, ask, which sends the question to Claude Opus 5.5 and saves the text of the reply as the answer:

claude-hello/main.py
from typing import TypedDict

from dotenv import load_dotenv
from langchain_anthropic import ChatAnthropic
from langgraph.graph import END, START, StateGraph

load_dotenv()

claude = ChatAnthropic(model="claude-opus-5-5", effort="low")


class State(TypedDict):
question: str
answer: str


def ask(state: State) -> dict:
reply = claude.invoke(state["question"])
return {"answer": reply.text}


builder = StateGraph(State)
builder.add_node("ask", ask)
builder.add_edge(START, "ask")
builder.add_edge("ask", END)
graph = builder.compile()

print(graph.invoke({"question": "What is the capital of France? Answer in one word."}))

The versions were LangGraph 1.2.25, langchain-anthropic 1.7.13, the Anthropic SDK 2.16.0 and python-dotenv 1.2.4, on Python 3.14.10. From the project folder, main.py worked:

Terminal
cd claude-hello
uv run main.py
Output
{'question': 'What is the capital of France? Answer in one word.', 'answer': 'Paris'}

Then I ran the copy in tryouts, still from the project folder:

Terminal
uv run python ../tryouts/ask.py

What I Expected​

The same answer, 'answer': 'Paris'. The code was the same, and so were the packages, the key and the network.

What I Got​

A traceback of over 180 lines, which ended with:

Output (last lines)
File "/Users/you/source/claude-hello/.venv/lib/python3.14/site-packages/langchain_anthropic/chat_models.py", line 1348, in _handle_anthropic_api_error
raise AnthropicConnectionError(message=e.message, request=e.request) from e
langchain_anthropic.chat_models.AnthropicConnectionError: Connection error.
During task with name 'ask' and id '00000000-0000-0000-0000-000000000000'

The end of the traceback in a terminal: two frames in langchain_anthropic's chat_models.py, the line raise AnthropicConnectionError, then langchain_anthropic.chat_models.AnthropicConnectionError: Connection error., then During task with name ask.

During task with name 'ask' is LangGraph naming the node that failed. Connection error. sounded like a network problem, yet main.py had just reached Claude over the same network.

What I Checked​

1. The first error in the traceback​

The traceback holds four errors, each in its own Traceback (most recent call last): block, joined by the line "The above exception was the direct cause of the following exception". Python's tutorial shows that this line appears when code raises a new error from the one it's handling, which "can be useful when you are transforming exceptions". So the first error is the cause, and each one after it wraps the one before. These are the last lines of the four blocks:

Output (the last line of each error)
httpcore2.LocalProtocolError: Illegal header value b'Bearer '
httpx2.LocalProtocolError: Illegal header value b'Bearer '
anthropic.APIConnectionError: Connection error.
langchain_anthropic.chat_models.AnthropicConnectionError: Connection error.

The first one shows that the request never left the computer: the HTTP library refused one of its headers, Bearer with nothing after it. That's the place where the API key goes.

2. Whether the key was loaded​

This script asks python-dotenv where it finds .env, loads it, and says whether ANTHROPIC_API_KEY is set, without printing the key:

tryouts/check_env.py
import os

from dotenv import find_dotenv, load_dotenv

print("find_dotenv():", repr(find_dotenv()))
print("load_dotenv():", load_dotenv())
print("ANTHROPIC_API_KEY is set:", "ANTHROPIC_API_KEY" in os.environ)

I ran it from the project folder, and then a copy of it saved in the project folder:

Terminal
uv run python ../tryouts/check_env.py
uv run python check_env.py
Output
find_dotenv(): ''
load_dotenv(): False
ANTHROPIC_API_KEY is set: False
find_dotenv(): '/Users/you/source/claude-hello/.env'
load_dotenv(): True
ANTHROPIC_API_KEY is set: True

The terminal after running check_env.py twice: from tryouts, find_dotenv returned an empty string, load_dotenv returned False and ANTHROPIC_API_KEY was not set; from the project, find_dotenv returned the path of claude-hello/.env, load_dotenv returned True and the key was set.

From tryouts, python-dotenv found no .env at all, so the key was never set. The copy inside the project found it, although both ran from the same folder.

3. Where python-dotenv looks​

python-dotenv's documentation says that, by default, load_dotenv() will "Look for a .env file in the same directory as the Python script (or higher up the directory tree)." ask.py lives in tryouts, and neither tryouts nor any folder above it holds a .env. The folder you run the command from doesn't count. The reference explains the two results above: load_dotenv() returns "True if at least one environment variable is set else False", and find_dotenv() "Returns path to the file if found, or an empty string otherwise".

4. What ChatAnthropic does without a key​

ChatAnthropic doesn't stop when the variable is missing. In langchain-anthropic 1.7.13, its key is a field with an empty default, which its docstring says is "Automatically read from env var ANTHROPIC_API_KEY if not provided":

langchain_anthropic/chat_models.py (ChatAnthropic)
anthropic_api_key: SecretStr = Field(default=SecretStr(""), alias="api_key")

A three-line script confirmed it. Run from the project folder, it printed True:

tryouts/key_check.py
from langchain_anthropic import ChatAnthropic

claude = ChatAnthropic(model="claude-opus-5-5")
print(claude.anthropic_api_key.get_secret_value() == "")

The empty key then goes to the Anthropic SDK, which in version 2.16.0 puts the key into the request's Authorization header:

anthropic/_client.py (Anthropic._api_key_auth)
api_key = self.api_key
if api_key is None:
return {}
return {"Authorization": f"Bearer {api_key}"}

An empty string isn't None, so the header became Bearer with nothing after the space.

5. Why the error says "Connection error."​

RFC 9110, the HTTP standard, says: "A field value does not include leading or trailing whitespace." h11, the library that writes the request for httpcore2, checks every header against that rule, and it raised Illegal header value b'Bearer ' before anything was sent. The Anthropic SDK reports every error it meets while sending a request as a connection error, except timeouts and its own errors:

anthropic/_base_client.py (_attempt_request)
except httpx2.TimeoutException as err:
log.debug("Encountered httpx2.TimeoutException", exc_info=True)
raise APITimeoutError(request=request) from err
except Exception as err:
if isinstance(err, AnthropicError):
# SDK-originated errors already carry their own type; don't wrap.
raise

log.debug("Encountered Exception", exc_info=True)
raise APIConnectionError(request=request) from err

langchain-anthropic then raised its own AnthropicConnectionError from that.

Why It Happens​

load_dotenv() looks for .env starting from the folder of the script that calls it, not from the folder you're in. ask.py sat outside the project, so it found nothing, and ANTHROPIC_API_KEY stayed unset. ChatAnthropic used an empty key instead of stopping, the SDK sent it as Authorization: Bearer , the HTTP library refused that header, and the SDK reported the refusal as Connection error.

The Fix​

Tell load_dotenv() to start looking in the folder you run the command from. In tryouts/ask.py, import find_dotenv too, and pass its result to load_dotenv():

tryouts/ask.py (top)
from typing import TypedDict

from dotenv import find_dotenv, load_dotenv
from langchain_anthropic import ChatAnthropic
from langgraph.graph import END, START, StateGraph

load_dotenv(find_dotenv(usecwd=True))

claude = ChatAnthropic(model="claude-opus-5-5", effort="low")

The top of the fixed ask.py in a macOS-style code window: the imports, now with find_dotenv next to load_dotenv, then load_dotenv(find_dotenv(usecwd=True)), then the ChatAnthropic model for claude-opus-5-5 with low effort.

python-dotenv's reference describes this: "If you need to change the default parameters of find_dotenv(), you can explicitly call find_dotenv() and pass the result to this function as dotenv_path." With usecwd=True, find_dotenv() starts in the current folder, as its source shows:

dotenv/main.py (find_dotenv)
if usecwd or _is_interactive() or _is_debugger() or getattr(sys, "frozen", False):
# Should work without __file__, e.g. in REPL or IPython notebook.
path = os.getcwd()

The other way is to keep the script inside the project, next to .env or in a folder below it. From there, a plain load_dotenv() finds the key, as main.py showed.

After the Fix​

Terminal
uv run python ../tryouts/ask.py
Output
{'question': 'What is the capital of France? Answer in one word.', 'answer': 'Paris'}

The terminal after uv run python ../tryouts/ask.py with the fix: the state with the question about the capital of France and the answer Paris.

The same answer as main.py. The commands in this post work unchanged in PowerShell.

Common Mistakes​

MistakeWhat happensDo this instead
Saving the key under another name, such as ANTHROPIC_KEYThe same Connection error., with Illegal header value b'Bearer ' as the first errorName it ANTHROPIC_API_KEY
ANTHROPIC_API_KEY= with nothing after the =The same errorPaste the key right after the =
Calling load_dotenv() after ChatAnthropic(...)The same error, even though .env is found: ChatAnthropic reads the variable when you create itCall load_dotenv() first, at the top of the script
Reading Connection error. as a network problemYou check the network, and it's fineRead the first error in the traceback: Illegal header value b'Bearer ' means an empty key

Troubleshooting​

SymptomLikely causeFix
AnthropicConnectionError: Connection error., with Illegal header value b'Bearer ' as the first errorANTHROPIC_API_KEY is empty or not setCheck it with check_env.py, then load .env from the right folder
load_dotenv() returns False, or find_dotenv() returns ''No .env in the script's folder or any folder above itload_dotenv(find_dotenv(usecwd=True)), or move the script into the project
AnthropicAuthenticationError: Error code: 401 with Invalid bearer tokenThe key was sent, but it's wrongCopy the key again, or create a new one

FAQ​

What happens with a wrong key instead of an empty one?​

A different and clearer error. With ANTHROPIC_API_KEY=not-a-real-key in .env, the request reached Claude's API, which turned it down:

Output (last line, shortened)
langchain_anthropic.chat_models.AnthropicAuthenticationError: Error code: 401 - {'type': 'error', 'error': {'type': 'authentication_error', 'message': 'Invalid bearer token'}, ...}

So Connection error. with Illegal header value b'Bearer ' means that no key was sent at all, and 401 with Invalid bearer token means that the key was wrong. How to Get a Claude API Key shows where to create one.

Does it matter which folder I run the command from?​

With a plain load_dotenv(), no. Both runs of check_env.py started in the project folder: the copy in tryouts found nothing, and the copy in the project found .env. With find_dotenv(usecwd=True), yes, because the search starts in the folder you're in.

Conclusion​

AnthropicConnectionError: Connection error. came from an empty API key, not from the network. load_dotenv() looks for .env from the script's own folder, and ask.py lived outside the project, so ChatAnthropic sent an empty key that the HTTP library refused. load_dotenv(find_dotenv(usecwd=True)) loaded the key from the folder I ran the command in, and the graph answered Paris.

Additional Resources​