Critical severity HTTP 401 beginner · Fix: 2-5 min

AuthenticationError

deepseek.AuthenticationError: Missing API key: DEEPSEEK_API_KEY

What this error means
DeepSeek-R1 client cannot authenticate because the DEEPSEEK_API_KEY environment variable is not set or is empty.

Stack trace

traceback
Traceback (most recent call last):
  File "script.py", line 12, in <module>
    response = client.chat.completions.create(
  File "site-packages/deepseek/api.py", line 89, in create
    self._validate_api_key()
  File "site-packages/deepseek/auth.py", line 34, in _validate_api_key
    raise AuthenticationError("Missing API key: DEEPSEEK_API_KEY environment variable not found or empty")
deepseek.AuthenticationError: Missing API key: DEEPSEEK_API_KEY environment variable not found or empty
QUICK FIX
Add `import os; from dotenv import load_dotenv; load_dotenv()` at the top of your script, create a .env file with `DEEPSEEK_API_KEY=sk-your-key`, and verify it with `echo $DEEPSEEK_API_KEY` in the same shell before running Python.

Why it happens

DeepSeek-R1 SDK requires authentication via the DEEPSEEK_API_KEY environment variable to make API requests to the DeepSeek reasoning model endpoints. When this variable is not set, not exported, or contains an empty string, the client initialization fails before any API call is made. This is a security measure to prevent accidental credential exposure in code and enforce proper credential management.

Detection

Check that DEEPSEEK_API_KEY is defined and exported before importing the DeepSeek client. Add `echo $DEEPSEEK_API_KEY` to your terminal to verify the variable is accessible, and confirm your .env file is loaded before running Python code.

Causes & fixes

1

DEEPSEEK_API_KEY environment variable is not set at all in the shell or process

✓ Fix

Export the variable in your shell before running Python: `export DEEPSEEK_API_KEY='sk-xxx'` on Linux/macOS or `set DEEPSEEK_API_KEY=sk-xxx` on Windows, or add it to your .env file and load it with python-dotenv

2

.env file exists but python-dotenv is not installed or load_dotenv() is not called before importing DeepSeek client

✓ Fix

Install python-dotenv (`pip install python-dotenv`) and call `from dotenv import load_dotenv; load_dotenv()` at the start of your script before any DeepSeek imports

3

DEEPSEEK_API_KEY is set but contains an empty string or only whitespace

✓ Fix

Verify the key value is non-empty and correct: add `print(os.environ.get('DEEPSEEK_API_KEY', 'NOT SET'))` to debug, and ensure your .env or shell export includes the full API key without truncation

4

Running in a containerized environment (Docker, Lambda, cloud function) where environment variables are not passed through

✓ Fix

Add the DEEPSEEK_API_KEY to your Docker .env file, use `docker run -e DEEPSEEK_API_KEY='sk-xxx'`, or configure it in your cloud platform's environment variable settings (AWS Lambda, Google Cloud Functions, etc.)

Code: broken vs fixed

Broken - triggers the error
python
from deepseek import DeepSeek

# BROKEN: API key is not set — this will crash immediately
client = DeepSeek()  # AuthenticationError: Missing API key: DEEPSEEK_API_KEY

response = client.chat.completions.create(
    model="deepseek-reasoner",
    messages=[
        {"role": "user", "content": "Solve 17 * 23 step by step"}
    ],
    max_completion_tokens=8000
)
Fixed - works correctly
python
import os
from dotenv import load_dotenv
from deepseek import DeepSeek

# FIXED: Load environment variables from .env file first
load_dotenv()

# Verify the API key is actually set before creating client
api_key = os.environ.get('DEEPSEEK_API_KEY')
if not api_key:
    raise ValueError("DEEPSEEK_API_KEY not found. Set it in your .env file or export it in your shell.")

# Now safe to create client — it will find the API key
client = DeepSeek(api_key=api_key)

response = client.chat.completions.create(
    model="deepseek-reasoner",
    messages=[
        {"role": "user", "content": "Solve 17 * 23 step by step"}
    ],
    max_completion_tokens=8000
)

print(f"Reasoning output: {response.choices[0].message.content}")
print("✓ Authentication successful!")
Added load_dotenv() to read the .env file, explicitly retrieved the API key with os.environ.get(), validated it is not empty, and passed it directly to the DeepSeek client initialization.

Workaround

If you cannot modify your environment setup immediately, hardcode the API key temporarily in a protected local script (never commit to version control): `client = DeepSeek(api_key='sk-your-actual-key')`. This is a temporary measure only: migrate to environment variables immediately after. Better: use Python's getpass module to prompt for the key at runtime without storing it: `from getpass import getpass; api_key = getpass('Enter DEEPSEEK_API_KEY: '); client = DeepSeek(api_key=api_key)`

Prevention

Adopt a three-layer credential strategy: 1) Always use environment variables via load_dotenv() for development, 2) Never commit .env files to git (add to .gitignore), 3) Use your platform's secrets manager for production (AWS Secrets Manager, Google Secret Manager, HashiCorp Vault). For CI/CD, configure secrets as masked environment variables in GitHub Actions, GitLab CI, or Jenkins, never as hardcoded strings in workflows.

Python 3.9+ · deepseek-sdk >=0.1.0 · tested on 0.2.x
Verified 2026-04 · deepseek-reasoner, deepseek-chat
Verify ↗

Community Notes

No notes yetBe the first to share a version-specific fix or tip.