Critical severity beginner · Fix: 2-5 min

ValueError

dspy.errors.ValueError: OpenAI API key not set

What this error means
DSPy raises a ValueError when the OpenAI API key environment variable is missing or not set properly.

Stack trace

traceback
Traceback (most recent call last):
  File "app.py", line 10, in <module>
    client = dspy.Client()
  File "/usr/local/lib/python3.9/site-packages/dspy/client.py", line 45, in __init__
    raise ValueError("OpenAI API key not set")
ValueError: OpenAI API key not set
QUICK FIX
Set the OPENAI_API_KEY environment variable in your shell or environment before running your DSPy code.

Why it happens

DSPy requires the OpenAI API key to be set in the environment variable before initializing the client. If the key is missing or empty, DSPy raises this error to prevent unauthorized API calls.

Detection

Check for the presence of the OPENAI_API_KEY environment variable before client initialization, or catch ValueError exceptions during client creation to log missing key issues.

Causes & fixes

1

OPENAI_API_KEY environment variable is not set or is empty

✓ Fix

Set the OPENAI_API_KEY environment variable with your valid OpenAI API key before running your application.

2

Environment variable is set but not loaded into the runtime environment

✓ Fix

Ensure your environment variables are loaded correctly, for example by using a .env file with python-dotenv or exporting variables in your shell session.

3

Code attempts to create DSPy client before environment variables are initialized

✓ Fix

Initialize environment variables before importing or creating the DSPy client instance.

Code: broken vs fixed

Broken - triggers the error
python
import dspy

client = dspy.Client()  # Raises ValueError: OpenAI API key not set
print("Client initialized")
Fixed - works correctly
python
import os
import dspy

os.environ["OPENAI_API_KEY"] = os.environ.get("OPENAI_API_KEY", "your_api_key_here")  # Set your API key securely
client = dspy.Client()  # Now works without error
print("Client initialized")
Added setting of OPENAI_API_KEY environment variable before creating the DSPy client to ensure the API key is available.

Workaround

Wrap the DSPy client initialization in a try/except block catching ValueError, and prompt the user or log an error message to set the API key before retrying.

Prevention

Use environment management tools like python-dotenv or container environment variables to guarantee the OPENAI_API_KEY is always set before application start.

Python 3.7+ · dspy >=0.1.0 · tested on 0.1.5
Verified 2026-04
Verify ↗

Community Notes

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