Spaces:
Sleeping
Sleeping
| from __future__ import annotations | |
| import os | |
| from pathlib import Path | |
| from typing import Dict | |
| from openai import OpenAI | |
| ENV_FILE_NAME = ".env" | |
| _ENV_KEY_CANDIDATES = ( | |
| "OPENAI_API_KEY", | |
| "OpenAI_API_KEY", | |
| "OpenAI-API", | |
| "OpenAI_API", | |
| "OPENAIKEY", | |
| ) | |
| _OPENAI_CLIENT: OpenAI | None = None | |
| def _read_env_file(path: Path) -> Dict[str, str]: | |
| entries: Dict[str, str] = {} | |
| if not path.exists(): | |
| return entries | |
| for raw_line in path.read_text().splitlines(): | |
| line = raw_line.strip() | |
| if not line or line.startswith("#"): | |
| continue | |
| if "=" in line: | |
| key, value = line.split("=", 1) | |
| elif ":" in line: | |
| key, value = line.split(":", 1) | |
| else: | |
| continue | |
| entries[key.strip()] = value.strip().strip('"').strip("'") | |
| return entries | |
| def ensure_openai_api_key() -> str: | |
| key = os.getenv("OPENAI_API_KEY") | |
| if key: | |
| return key | |
| env_path = Path(__file__).resolve().parent.parent / ENV_FILE_NAME | |
| env_entries = _read_env_file(env_path) | |
| for candidate in _ENV_KEY_CANDIDATES: | |
| if env_entries.get(candidate): | |
| key = env_entries[candidate] | |
| break | |
| else: | |
| key = None | |
| if not key: | |
| raise RuntimeError( | |
| "OpenAI API key is not configured. Set OPENAI_API_KEY or add it to .env (e.g., 'OpenAI-API: sk-...')." | |
| ) | |
| os.environ["OPENAI_API_KEY"] = key | |
| return key | |
| def get_openai_client() -> OpenAI: | |
| global _OPENAI_CLIENT | |
| if _OPENAI_CLIENT is None: | |
| api_key = ensure_openai_api_key() | |
| _OPENAI_CLIENT = OpenAI(api_key=api_key) | |
| return _OPENAI_CLIENT | |