Spaces:
Sleeping
Sleeping
File size: 1,675 Bytes
a8d3381 |
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 58 59 60 61 62 63 64 65 66 67 68 |
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
|