🔍 Code Extractor

function validate_api_key

Maturity: 51

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.

File:
/tf/active/vicechatdev/e-ink-llm/main.py
Lines:
111 - 124
Complexity:
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

  • os
  • sys
  • dotenv

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

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function test_setup 70.1% similar

    Validates the presence of required API keys (OpenAI and SERPER) and sets them as environment variables with fallback default values.

    From: /tf/active/vicechatdev/find_email/test_enrichment.py
  • function init_openai_client 68.8% similar

    Initializes the OpenAI client by setting the API key from either a provided parameter or environment variable.

    From: /tf/active/vicechatdev/chromadb-cleanup/src/summarization/summarizer.py
  • function test_configuration_v1 59.4% similar

    Validates that all required configuration variables (Azure AD credentials, OpenAI API key, and domain) are properly set and not using placeholder values.

    From: /tf/active/vicechatdev/find_email/test_vendor_extractor.py
  • function check_configuration_v1 52.2% similar

    Validates the presence of a .env configuration file and checks that all required environment variables (TENANT_ID, CLIENT_ID, CLIENT_SECRET, FROM_EMAIL) are defined.

    From: /tf/active/vicechatdev/email-forwarder/run_service.py
  • function validate_azure_client_secret 50.0% similar

    Validates an Azure client secret by checking for placeholder values, minimum length requirements, and common invalid patterns.

    From: /tf/active/vicechatdev/SPFCsync/validate_config.py
← Back to Browse