langchain-ai/langchain · error · ValueError
{error_message}
Error message
{error_message} What it means
Raised inside the closure produced by `from_env(...)` when the requested environment variable is missing, no usable default exists, and the caller supplied a custom `error_message`. It is LangChain's mechanism for declaring a field whose value must come from the environment (common in integration `SecretStr`/string fields), with a tailored message explaining what to set.
Source
Thrown at libs/core/langchain_core/utils/utils.py:413
Raises:
ValueError: If the environment variable is not set and no default is
provided.
Returns:
The value from the environment.
"""
if isinstance(key, (list, tuple)):
for k in key:
if k in os.environ:
return os.environ[k]
if isinstance(key, str) and key in os.environ:
return os.environ[key]
if isinstance(default, (str, type(None))):
return default
if error_message:
raise ValueError(error_message)
msg = (
f"Did not find {key}, please add an environment variable"
f" `{key}` which contains it, or pass"
f" `{key}` as a named parameter."
)
raise ValueError(msg)
return get_from_env_fn
@overload
def secret_from_env(key: str | Sequence[str], /) -> Callable[[], SecretStr]: ...
@overload
def secret_from_env(key: str, /, *, default: str) -> Callable[[], SecretStr]: ...
View on GitHub (pinned to e32fa9a52e)
Solutions
- Set the environment variable named in the constructor's `from_env` declaration (the message text states which credential it needs), e.g. `export MY_API_KEY=...` or add it to `.env` and load it.
- Pass the value directly as a constructor argument, which takes precedence over the env lookup.
- For optional credentials, provide a default: use the `default=` overload or wrap instantiation in a check.
Example fix
# before llm = ChatXAI() # ValueError: <custom error_message> because XAI_API_KEY unset # after export XAI_API_KEY=sk-... llm = ChatXAI()
Defensive patterns
Strategy: validation
Validate before calling
import os
REQUIRED_ENV = ["MY_PROVIDER_API_KEY"]
missing = [k for k in REQUIRED_ENV if not os.environ.get(k)]
if missing:
raise SystemExit(f"Missing env vars: {missing}. Set them or pass the value as a constructor argument.") Try / catch
try:
client = MyIntegration()
except ValueError as e:
if "API key" in str(e) or "environment variable" in str(e):
client = MyIntegration(api_key=get_secret_from_vault()) # fallback source
else:
raise Prevention
- Load `.env` at process start (`dotenv.load_dotenv()`) before importing integrations.
- Fail fast at startup with an explicit env checklist instead of waiting for the constructor to fail.
- Keep a documented list of every env var each integration consumes.
When it happens
Trigger: Instantiating an integration whose field default was built with `from_env('API_KEY', error_message='...')` while the environment variable is unset and no fallback default was configured; any direct use of `from_env(key)( )` without the variable present.
Common situations: Missing `.env` file or forgetting to load it (`load_dotenv()` not called); CI/containers where the secret was never injected; typo'd variable name; `.env` listed in `.gitignore` so fresh clones lack it.
Related errors
- Did not find {key}, please add an environment variable `{key
- maxsize must be greater than 0
- Tracing using LangChainTracerV1 is no longer supported. Plea
- Could not resolve content_key {full_path!r}: expected a mapp
- Could not resolve content_key {full_path!r}: missing key {ke
AI-assisted analysis of langchain-ai/langchain@e32fa9a52e (2026-08-14).
Data as JSON: /api/errors/3620874603915851.
Report an issue: GitHub.