Créer un bot de support IA pour votre boutique en ligne

Bot de support en Python : code source

Fichiers : 2988,4 KiBTélécharger le ZIP

store_assistant/config.py

3,0 KiBBrutTélécharger
Python
1"""Runtime settings, read from environment variables (and an optional .env file)."""23from __future__ import annotations45import os6from dataclasses import dataclass7from pathlib import Path89from dotenv import load_dotenv1011PROJECT_ROOT = Path(__file__).resolve().parent.parent1213DEFAULT_BASE_URL = "https://api.devupai.com/v1"14DEFAULT_MODEL = "deepseek-ai/DeepSeek-V4.1-Flash-1017"151617class ConfigError(RuntimeError):18    """Raised when a required setting is missing or invalid."""192021def _int_env(name: str, default: int, minimum: int = 1) -> int:22    raw = os.getenv(name)23    if raw is None or raw.strip() == "":24        return default25    try:26        value = int(raw)27    except ValueError as exc:28        raise ConfigError(f"{name} must be an integer, got {raw!r}") from exc29    if value < minimum:30        raise ConfigError(f"{name} must be >= {minimum}, got {value}")31    return value323334@dataclass(frozen=True)35class Settings:36    devup_api_key: str37    devup_base_url: str38    model: str39    telegram_bot_token: str | None40    admin_chat_id: int | None41    db_path: Path42    catalog_path: Path43    history_messages: int44    rate_limit_per_minute: int45    max_input_chars: int46    max_tool_rounds: int47    max_output_tokens: int48    request_timeout_s: int4950    @classmethod51    def from_env(cls, *, require_api_key: bool = True, require_telegram: bool = False) -> Settings:52        load_dotenv(PROJECT_ROOT / ".env")5354        api_key = os.getenv("DEVUP_API_KEY", "").strip()55        if require_api_key and not api_key:56            raise ConfigError("DEVUP_API_KEY is not set. Copy .env.example to .env and add your key.")5758        token = os.getenv("TELEGRAM_BOT_TOKEN", "").strip() or None59        if require_telegram and not token:60            raise ConfigError("TELEGRAM_BOT_TOKEN is not set. Create a bot with @BotFather and add its token to .env.")6162        admin_raw = os.getenv("ADMIN_CHAT_ID", "").strip()63        try:64            admin_chat_id = int(admin_raw) if admin_raw else None65        except ValueError as exc:66            raise ConfigError(f"ADMIN_CHAT_ID must be a numeric Telegram chat id, got {admin_raw!r}") from exc6768        return cls(69            devup_api_key=api_key,70            devup_base_url=os.getenv("DEVUP_BASE_URL", DEFAULT_BASE_URL).strip() or DEFAULT_BASE_URL,71            model=os.getenv("DEVUP_MODEL", DEFAULT_MODEL).strip() or DEFAULT_MODEL,72            telegram_bot_token=token,73            admin_chat_id=admin_chat_id,74            db_path=Path(os.getenv("STORE_DB_PATH", str(PROJECT_ROOT / "data" / "store.db"))),75            catalog_path=Path(os.getenv("STORE_CATALOG_PATH", str(PROJECT_ROOT / "data" / "demo_store.json"))),76            history_messages=_int_env("HISTORY_MESSAGES", 12),77            rate_limit_per_minute=_int_env("RATE_LIMIT_PER_MINUTE", 8),78            max_input_chars=_int_env("MAX_INPUT_CHARS", 1000),79            max_tool_rounds=_int_env("MAX_TOOL_ROUNDS", 4),80            max_output_tokens=_int_env("MAX_OUTPUT_TOKENS", 8192),81            request_timeout_s=_int_env("REQUEST_TIMEOUT_S", 60),82        )