88 lines
2.6 KiB
Python
88 lines
2.6 KiB
Python
"""
|
|
集中读取 .env / 环境变量。
|
|
|
|
使用方式:
|
|
from config import settings
|
|
print(settings.llm_model)
|
|
print(settings.has_openai_key)
|
|
"""
|
|
|
|
import os
|
|
from dataclasses import dataclass
|
|
from pathlib import Path
|
|
|
|
|
|
def _load_dotenv(env_path: Path) -> None:
|
|
"""极简 .env 解析,避免引入 python-dotenv 依赖。"""
|
|
if not env_path.is_file():
|
|
return
|
|
for raw_line in env_path.read_text(encoding="utf-8").splitlines():
|
|
line = raw_line.strip()
|
|
if not line or line.startswith("#"):
|
|
continue
|
|
if "=" not in line:
|
|
continue
|
|
key, _, value = line.partition("=")
|
|
key = key.strip()
|
|
value = value.strip().strip('"').strip("'")
|
|
# 已存在则不覆盖(让真实环境变量优先)
|
|
os.environ.setdefault(key, value)
|
|
|
|
|
|
_ROOT = Path(__file__).resolve().parent
|
|
_load_dotenv(_ROOT / ".env")
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Settings:
|
|
openai_api_key: str
|
|
anthropic_api_key: str
|
|
llm_provider: str
|
|
llm_model: str
|
|
llm_max_tokens: int
|
|
rag_chroma_path: str
|
|
rag_collection_name: str
|
|
rag_embed_model: str
|
|
validation_service_url: str
|
|
log_level: str
|
|
|
|
@property
|
|
def has_openai_key(self) -> bool:
|
|
return bool(self.openai_api_key) and self.openai_api_key != "your_openai_api_key_here"
|
|
|
|
@property
|
|
def has_anthropic_key(self) -> bool:
|
|
return bool(self.anthropic_api_key) and self.anthropic_api_key != "your_anthropic_api_key_here"
|
|
|
|
|
|
def _int(name: str, default: int) -> int:
|
|
raw = os.environ.get(name)
|
|
try:
|
|
return int(raw) if raw else default
|
|
except ValueError:
|
|
return default
|
|
|
|
|
|
settings = Settings(
|
|
openai_api_key=os.environ.get("OPENAI_API_KEY", ""),
|
|
anthropic_api_key=os.environ.get("ANTHROPIC_API_KEY", ""),
|
|
llm_provider=os.environ.get("LLM_PROVIDER", "openai"),
|
|
llm_model=os.environ.get("LLM_MODEL", "gpt-4o-mini"),
|
|
llm_max_tokens=_int("LLM_MAX_TOKENS", 4096),
|
|
rag_chroma_path=os.environ.get("RAG_CHROMA_PATH", "./db/chroma"),
|
|
rag_collection_name=os.environ.get("RAG_COLLECTION_NAME", "jrxml_chunks"),
|
|
rag_embed_model=os.environ.get("RAG_EMBED_MODEL", "sentence-transformers/all-MiniLM-L6-v2"),
|
|
validation_service_url=os.environ.get("VALIDATION_SERVICE_URL", "http://localhost:8001"),
|
|
log_level=os.environ.get("LOG_LEVEL", "INFO"),
|
|
)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
s = settings
|
|
print(f"provider = {s.llm_provider}")
|
|
print(f"model = {s.llm_model}")
|
|
print(f"max_tok = {s.llm_max_tokens}")
|
|
print(f"openai? = {s.has_openai_key}")
|
|
print(f"anthro? = {s.has_anthropic_key}")
|
|
print(f"rag_path = {s.rag_chroma_path}")
|