ValueError
dspy.errors.ValueError: OpenAI API key not set
Stack trace
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 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
OPENAI_API_KEY environment variable is not set or is empty
Set the OPENAI_API_KEY environment variable with your valid OpenAI API key before running your application.
Environment variable is set but not loaded into the runtime environment
Ensure your environment variables are loaded correctly, for example by using a .env file with python-dotenv or exporting variables in your shell session.
Code attempts to create DSPy client before environment variables are initialized
Initialize environment variables before importing or creating the DSPy client instance.
Code: broken vs fixed
import dspy
client = dspy.Client() # Raises ValueError: OpenAI API key not set
print("Client initialized") 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") 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.