function validate_api_key
Validates the presence of an OpenAI API key by checking function parameters and environment variables, returning the key or exiting with an error message if not found.
/tf/active/vicechatdev/e-ink-llm/main.py
111 - 124
simple
Purpose
This function ensures that an OpenAI API key is available before proceeding with API operations. It implements a fallback mechanism by first checking if an API key was passed as a parameter, then checking the OPENAI_API_KEY environment variable. If neither source provides a key, it displays helpful error messages with multiple resolution options and terminates the program with exit code 1.
Source Code
def validate_api_key(api_key: str = None) -> str:
"""Validate and return API key"""
# Try parameter first, then environment variable
key = api_key or os.getenv("OPENAI_API_KEY")
if not key:
print("❌ Error: OpenAI API key not found!")
print(" Please either:")
print(" 1. Set OPENAI_API_KEY environment variable")
print(" 2. Create a .env file with OPENAI_API_KEY=your_key")
print(" 3. Use --api-key parameter")
sys.exit(1)
return key
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
api_key |
str | None | positional_or_keyword |
Parameter Details
api_key: Optional string parameter containing an OpenAI API key. If provided, this takes precedence over environment variables. If None (default), the function will attempt to retrieve the key from the OPENAI_API_KEY environment variable. Expected format is a valid OpenAI API key string (typically starting with 'sk-').
Return Value
Type: str
Returns a string containing the validated OpenAI API key. The key is guaranteed to be non-empty and truthy. If no valid key is found through either the parameter or environment variable, the function does not return but instead calls sys.exit(1) to terminate the program.
Dependencies
ossysdotenv
Required Imports
import os
import sys
from dotenv import load_dotenv
Usage Example
import os
import sys
from dotenv import load_dotenv
# Load environment variables from .env file
load_dotenv()
def validate_api_key(api_key: str = None) -> str:
key = api_key or os.getenv("OPENAI_API_KEY")
if not key:
print("❌ Error: OpenAI API key not found!")
print(" Please either:")
print(" 1. Set OPENAI_API_KEY environment variable")
print(" 2. Create a .env file with OPENAI_API_KEY=your_key")
print(" 3. Use --api-key parameter")
sys.exit(1)
return key
# Example 1: Using environment variable
api_key = validate_api_key()
print(f"Using API key: {api_key[:10]}...")
# Example 2: Passing key directly
api_key = validate_api_key(api_key="sk-your-api-key-here")
print(f"Using API key: {api_key[:10]}...")
# Example 3: In CLI application with argparse
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--api-key', help='OpenAI API key')
args = parser.parse_args()
api_key = validate_api_key(args.api_key)
Best Practices
- Always call load_dotenv() before using this function to ensure .env file variables are loaded
- Never hardcode API keys in source code; use environment variables or secure parameter passing
- This function will terminate the program with sys.exit(1) if validation fails, so it should be called early in the application lifecycle
- The function prints user-friendly error messages to stdout, making it suitable for CLI applications but potentially unsuitable for library code where exceptions might be preferred
- Consider wrapping this function or modifying it to raise exceptions instead of calling sys.exit() if using in a library or service context
- The API key is returned as-is without format validation; additional validation of the key format (e.g., checking for 'sk-' prefix) may be needed depending on use case
- For production applications, consider logging the validation attempt (without logging the actual key) for debugging purposes
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function test_setup 70.1% similar
-
function init_openai_client 68.8% similar
-
function test_configuration_v1 59.4% similar
-
function check_configuration_v1 52.2% similar
-
function validate_azure_client_secret 50.0% similar