File size: 1,868 Bytes
363cda9 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
import os
from pydantic import Field, ConfigDict, field_validator
from pydantic_settings import BaseSettings
from pathlib import Path
from dotenv import load_dotenv
from pydantic import ValidationError
import sys
# Load environment variables
load_dotenv()
class OpenAIApiKey(BaseSettings):
"""Schema for validating and loading the OpenAI API key configuration.
"""
model_config = ConfigDict(
title="OpenAI API Key Schema",
description="Validates and loads the OpenAI API key from environment variables.",
)
api_key: str = Field(
..., # >>> required field
title="OpenAI API Key",
description="API key for OpenAI authentication.",
examples=["sk-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"],
alias="OPENAI_API_KEY",
)
@field_validator("api_key")
@classmethod
def validate_openai_api_key(cls, v: str) -> str:
"""Validate that the API key is present and has the correct format.
"""
if not v:
raise ValueError(
"π₯ Missing `OPENAI_API_KEY` environment variable."
)
if not v.startswith("sk-"):
raise ValueError(
"π₯ Invalid `OPENAI_API_KEY` β must start with 'sk-'."
)
return v
@classmethod
def validate_environment(cls) -> "OpenAIApiKey":
"""
Load .env from the root directory
and validate that the API key is present and valid.
"""
try:
# Pydantic auto-loads .env and validates
config = cls()
os.environ["OPENAI_API_KEY"] = config.api_key # Set for runtime access
return config
except ValidationError as e:
print(f"π₯ OpenAI API key misconfiguration:\n{e}")
sys.exit(1)
|