Skip to content

The agent engineering platform.

fix(anthropic): clearer error when no credentials are configured (#39285)

Mason Daugherty3579fe93eeb2
diff --git a/libs/partners/anthropic/langchain_anthropic/chat_models.py b/libs/partners/anthropic/langchain_anthropic/chat_models.py
index aa1b67acc3..76e0aa8951 100644
--- a/libs/partners/anthropic/langchain_anthropic/chat_models.py
+++ b/libs/partners/anthropic/langchain_anthropic/chat_models.py
@@ -889,6 +889,20 @@ class AnthropicContextOverflowError(anthropic.BadRequestError, ContextOverflowEr
"""BadRequestError raised when input exceeds Anthropic's context limit."""
+def _raise_if_authentication_error(e: TypeError) -> None:
+ """Re-raise anthropic SDK's missing-credentials `TypeError` with guidance."""
+ if "Could not resolve authentication method" in str(e):
+ msg = (
+ "Anthropic authentication failed: no API key or authorization "
+ "credentials were provided. Set the ANTHROPIC_API_KEY environment "
+ "variable, pass api_key=... to ChatAnthropic, or provide "
+ 'credentials via default_headers={"Authorization": ...}. If you '
+ "are routing through the LangSmith gateway, set LANGSMITH_GATEWAY "
+ "and LANGSMITH_GATEWAY_API_KEY."
+ )
+ raise TypeError(msg) from e
+
+
def _handle_anthropic_bad_request(e: anthropic.BadRequestError) -> None:
"""Handle Anthropic BadRequestError."""
if "prompt is too long" in e.message:
@@ -1593,14 +1607,22 @@ class ChatAnthropic(BaseChatModel):
return {k: v for k, v in payload.items() if v is not None}
def _create(self, payload: dict) -> Any:
- if "betas" in payload:
- return self._client.beta.messages.create(**payload)
- return self._client.messages.create(**payload)
+ try:
+ if "betas" in payload:
+ return self._client.beta.messages.create(**payload)
+ return self._client.messages.create(**payload)
+ except TypeError as e:
+ _raise_if_authentication_error(e)
+ raise
async def _acreate(self, payload: dict) -> Any:
- if "betas" in payload:
- return await self._async_client.beta.messages.create(**payload)
- return await self._async_client.messages.create(**payload)
+ try:
+ if "betas" in payload:
+ return await self._async_client.beta.messages.create(**payload)
+ return await self._async_client.messages.create(**payload)
+ except TypeError as e:
+ _raise_if_authentication_error(e)
+ raise
def _stream(
self,
diff --git a/libs/partners/anthropic/tests/unit_tests/test_chat_models.py b/libs/partners/anthropic/tests/unit_tests/test_chat_models.py
index c7b77b89a3..079f7116a9 100644
--- a/libs/partners/anthropic/tests/unit_tests/test_chat_models.py
+++ b/libs/partners/anthropic/tests/unit_tests/test_chat_models.py
@@ -4567,3 +4567,65 @@ def test_langsmith_gateway_provider_base_url_uses_provider_key(
llm = ChatAnthropic(model=MODEL_NAME)
assert llm.anthropic_api_url == "https://api.anthropic.com"
assert llm.anthropic_api_key.get_secret_value() == "provider-key"
+
+
+_MISSING_CREDENTIALS_TYPE_ERROR = TypeError(
+ "Could not resolve authentication method. Expected one of api_key, "
+ "auth_token, or credentials to be set. Or for one of the `X-Api-Key` or "
+ "`Authorization` headers to be explicitly omitted"
+)
+
+
+def _clear_auth_env(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.delenv("ANTHROPIC_API_KEY", raising=False)
+ monkeypatch.delenv("LANGSMITH_GATEWAY", raising=False)
+ monkeypatch.delenv("LANGSMITH_GATEWAY_API_KEY", raising=False)
+ monkeypatch.delenv("ANTHROPIC_API_URL", raising=False)
+ monkeypatch.delenv("ANTHROPIC_BASE_URL", raising=False)
+
+
+def test_missing_credentials_error_sync(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Missing credentials raise a `TypeError` with LangChain guidance."""
+ _clear_auth_env(monkeypatch)
+ llm = ChatAnthropic(model=MODEL_NAME)
+
+ with ( # noqa: PT012
+ patch.object(llm._client.messages, "create") as mock_create,
+ pytest.raises(TypeError, match="ANTHROPIC_API_KEY") as exc_info,
+ ):
+ mock_create.side_effect = _MISSING_CREDENTIALS_TYPE_ERROR
+ llm.invoke([HumanMessage(content="test")])
+
+ assert exc_info.value.__cause__ is _MISSING_CREDENTIALS_TYPE_ERROR
+
+
+async def test_missing_credentials_error_async(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Missing credentials raise a `TypeError` with LangChain guidance (async)."""
+ _clear_auth_env(monkeypatch)
+ llm = ChatAnthropic(model=MODEL_NAME)
+
+ with ( # noqa: PT012
+ patch.object(llm._async_client.messages, "create") as mock_create,
+ pytest.raises(TypeError, match="ANTHROPIC_API_KEY") as exc_info,
+ ):
+ mock_create.side_effect = _MISSING_CREDENTIALS_TYPE_ERROR
+ await llm.ainvoke([HumanMessage(content="test")])
+
+ assert exc_info.value.__cause__ is _MISSING_CREDENTIALS_TYPE_ERROR
+
+
+def test_unrelated_type_error_propagates_unchanged() -> None:
+ """A `TypeError` not about authentication is re-raised as-is."""
+ llm = ChatAnthropic(model=MODEL_NAME)
+ unrelated_error = TypeError("some unrelated client error")
+
+ with ( # noqa: PT012
+ patch.object(llm._client.messages, "create") as mock_create,
+ pytest.raises(TypeError) as exc_info,
+ ):
+ mock_create.side_effect = unrelated_error
+ llm.invoke([HumanMessage(content="test")])
+
+ assert exc_info.value is unrelated_error