sage-api / src /llm /env.py
hiasgnpsadgd's picture
Deploy current MIMIC-only SAGE backend
de0f30b verified
Raw
History Blame Contribute Delete
1.39 kB
"""Environment helpers for LLM provider configuration."""
from __future__ import annotations
import os
import shlex
from pathlib import Path
def load_project_dotenv(dotenv_path: str | Path = ".env", *, override: bool = False) -> Path | None:
"""Load simple shell-style KEY=value lines into ``os.environ``."""
path = Path(dotenv_path).expanduser().resolve()
if not path.exists():
return None
for raw_line in path.read_text(encoding="utf-8").splitlines():
parsed = parse_dotenv_line(raw_line)
if parsed is None:
continue
key, value = parsed
if not override and key in os.environ:
continue
os.environ[key] = value
return path
def parse_dotenv_line(raw_line: str) -> tuple[str, str] | None:
line = raw_line.strip()
if not line or line.startswith("#"):
return None
if line.startswith("export "):
line = line[len("export ") :].strip()
if "=" not in line:
return None
key, value = line.split("=", 1)
key = key.strip()
if not key:
return None
return key, _parse_env_value(value.strip())
def _parse_env_value(value: str) -> str:
if not value:
return ""
try:
parsed = shlex.split(value, posix=True)
except ValueError:
return value
if len(parsed) == 1:
return parsed[0]
return value