Critical severity beginner · Fix: 2-5 min

KeyError or ValueError: DASHSCOPE_API_KEY

builtins.KeyError or builtins.ValueError: DASHSCOPE_API_KEY environment variable not found

What this error means
The DASHSCOPE_API_KEY environment variable is not set or not accessible to your Python process when attempting to initialize a Qwen model client.

Stack trace

traceback
Traceback (most recent call last):
  File "main.py", line 12, in <module>
    client = QwenClient(model="qwen-turbo")
  File "/usr/local/lib/python3.11/site-packages/dashscope/api.py", line 45, in __init__
    api_key = os.environ["DASHSCOPE_API_KEY"]
KeyError: 'DASHSCOPE_API_KEY'

Or:

ValueError: DASHSCOPE_API_KEY environment variable is not set. Please set it before initializing the client.
QUICK FIX
Add os.environ['DASHSCOPE_API_KEY'] = 'your-api-key' at the top of your script, or set export DASHSCOPE_API_KEY='your-key' in your terminal before running Python, or use python-dotenv to load from .env.

Why it happens

Qwen models hosted on Alibaba Cloud's DashScope platform require API authentication via the DASHSCOPE_API_KEY environment variable. When this variable is not set in your shell environment, Python process environment (os.environ), or .env file, the Qwen SDK cannot authenticate requests and raises a KeyError or ValueError. This is critical because every API call will fail until the key is properly configured.

Detection

Check your environment before instantiating the client: verify os.environ.get('DASHSCOPE_API_KEY') is not None, or use python-dotenv to load .env early in your startup sequence and print the result to confirm it loaded.

Causes & fixes

1

DASHSCOPE_API_KEY environment variable never set in shell, virtualenv, or Docker container

✓ Fix

Set the variable in your shell session before running Python: export DASHSCOPE_API_KEY='your-key-here', or add it to your .env file and load with python-dotenv before importing the Qwen SDK

2

API key is set in one terminal session but running Python in a different shell or after restarting the terminal

✓ Fix

Environment variables are process-specific and don't persist across terminal sessions. Set DASHSCOPE_API_KEY in your current shell with export, or use a persistent .env file with python-dotenv, or add to ~/.bashrc or ~/.zshrc for all future sessions

3

Running inside a Docker container where the environment variable was not passed via --env, -e flag, or in the Docker Compose environment section

✓ Fix

Pass the API key to the container using docker run -e DASHSCOPE_API_KEY='your-key' myapp:latest or add environment: - DASHSCOPE_API_KEY=${DASHSCOPE_API_KEY} to your docker-compose.yml, or ADD it to the Dockerfile with ENV DASHSCOPE_API_KEY=value

4

Using python-dotenv but .env file is in the wrong directory or was not loaded before SDK initialization

✓ Fix

Call load_dotenv(dotenv_path='path/to/.env') immediately at the top of your main.py, before any Qwen imports. Verify the file exists and contains DASHSCOPE_API_KEY='your-key' on a single line with no spaces around the equals sign

Code: broken vs fixed

Broken - triggers the error
python
import os
from dashscope import Generation

# BROKEN: No DASHSCOPE_API_KEY set — this line will raise KeyError
client = Generation()  # Internally tries to read os.environ['DASHSCOPE_API_KEY']

response = client.call(
    model='qwen-turbo',
    messages=[{'role': 'user', 'content': 'Hello Qwen'}]
)
print(response['output']['text'])
Fixed - works correctly
python
import os
from dotenv import load_dotenv
from dashscope import Generation

# FIXED: Load .env file before any SDK initialization
load_dotenv(dotenv_path='.env')

# Verify the key is set
api_key = os.environ.get('DASHSCOPE_API_KEY')
if not api_key:
    raise ValueError(
        'DASHSCOPE_API_KEY environment variable not set. '
        'Set it in .env or export DASHSCOPE_API_KEY=your-key-here'
    )

client = Generation(api_key=api_key)  # Pass key explicitly or rely on env var

response = client.call(
    model='qwen-turbo',
    messages=[{'role': 'user', 'content': 'Hello Qwen'}]
)
print(f'Response: {response["output"]["text"]}')
Added load_dotenv() to load the .env file, explicit os.environ.get() to retrieve and validate the key, and pass it explicitly to the Generation() constructor so authentication succeeds.

Workaround

If you cannot set environment variables in your current deployment, create the .env file with DASHSCOPE_API_KEY='your-key' in your project root and use load_dotenv(find_dotenv()) at the very first line of your main.py (before any imports from dashscope), then pass os.environ['DASHSCOPE_API_KEY'] directly to the client constructor.

Prevention

Use a configuration management pattern: load all secrets from environment variables or a secrets manager (AWS Secrets Manager, HashiCorp Vault, or 1Password CLI) at application startup, validate they exist with explicit checks, and fail fast with a clear error message before attempting any API calls. For Docker/Kubernetes, use secrets or ConfigMaps to inject DASHSCOPE_API_KEY at runtime rather than hardcoding.

Python 3.9+ · dashscope >=1.0.0 · tested on 1.11.x
Verified 2026-04
Verify ↗

Community Notes

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