I'm using the OpenAI API in a Python script and have set the OPENAI_API_KEY as an environment variable in my system, which works fine when running the script in the integrated terminal. What I have used to set the key. https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
However, when I change the debugging configuration in my launch.json file from "console": "integratedTerminal" to "console": "internalConsole", the API key is not recognized, and I get an AuthenticationError.
How can I properly set the API key when using the "internalConsole" configuration in VS Code so that the OpenAI API works correctly?
To use the OpenAI API key when using the "internalConsole" configuration in VS Code, you can create a separate secrets.json file containing your API key, and then load the key in your Python script directly to openai object.
{
"OPENAI_API_KEY": "your-api-key-here"
}
Replace "your-api-key-here" with your actual OpenAI API key.
# .gitignore
secrets.json
import json
import openai
def load_api_key(secrets_file="secrets.json"):
with open(secrets_file) as f:
secrets = json.load(f)
return secrets["OPENAI_API_KEY"]
# Set secret API key
# Typically, we'd use an environment variable (e.g., echo "export OPENAI_API_KEY='yourkey'" >> ~/.zshrc)
# However, using "internalConsole" in launch.json requires setting it in the code for compatibility with Hebrew
api_key = load_api_key()
openai.api_key = api_key
# Your script's content goes here
By following these steps, your API key will be properly set when using the "internalConsole" configuration in VS Code, and your OpenAI API calls should work as expected.