Phase 2 — jev.py client: POST /v1/systemone, PINNED model jev-1.13.0 (drift warning when the response model differs), one retry on 429/5xx, fail-soft (None on any error), usage/latency returned for observability. Config adds TYPESAFE_API_KEY / JEV_* (thresholds 0.85/0.60, 15 questions per field); no daily cap by owner decision. bot/.env is now mounted read-only into the container so the key never enters compose/git.
Phase 3 — matching.py: برونگروهی (one request per field, parallel), درونگروهی (one choice question per mention sharing the same full candidate list + «_none»), درونواریانسی (all STT spellings in one question). Routing: conf>=exact → bind; floor..exact → ambiguity; else/_none → new; missing/failed field → difflib fallback (bug fixed during testing: a failed request used to record 'new' instead of falling back). Resolver gains full cached lists for suppliers/materials (paged) plus brands (API+DB) and specs (EAV values + draft specs). NLU prompt now emits entity_mentions (6 fields) with the voice-variant grouping rule; sanitize_mentions guards the shape. handle_message runs matching only for register_quote/update_draft/add_material behind JEV_ENABLED; jev_map threads into quote/material resolve_payload (Jev hit skips difflib; exact writes ids; ambiguity skips difflib). Spec effect per owner: spelling normalization only (normalize_brand_spec).
Phase 4 — entity-match ambiguity sub-messages: create_ambiguities() builds deduped entries {kind: entity_match, field, variants, candidates, details with Persian percentages}; new keyboards.ambiguity_candidates_keyboard renders one button per candidate + «هیچکدام — ایجاد جدید»; callbacks handle amb⛏️{prefix}:{amb_id}:{idx} (applies the candidate via matching.apply_choice then re-resolves/renders) and amb:new (rejected → auto-create path at commit). Every user choice lands in observability (ambiguity.user_choice with arg+candidates).
Phase 5 — voice variants: NLU groups different STT spellings of one entity into one variants[] (verified live: مصطفوی/مستفدی → one supplier mention); tools/test_matching.py live section (RUN_LIVE=1) exercises real DeepSeek + real Jev without touching Bale.
Tests: test_jev.py 5/5 (mock HTTP: no-key, happy path, 429-retry, 400, exception), test_matching.py 11/11 mock + 3/3 live (real NLU produced 7 mentions with correct fields; real Jev matched «50 کیلویی»→«۵۰ کیلویی» 0.98 and «کیسه» 1.0 and correctly returned new against the emptied catalog); observability regression 8/8.
166 lines
5.9 KiB
Python
166 lines
5.9 KiB
Python
"""Bot configuration.
|
|
|
|
All settings can be overridden with environment variables prefixed with
|
|
``PROCUREMENT_BOT_`` (e.g. ``PROCUREMENT_BOT_BOT_TOKEN=...``) or a local
|
|
``.env`` file. Docker/compose passes them in directly (same convention as
|
|
the api service's ``PROCUREMENT_*`` prefix).
|
|
"""
|
|
from pydantic_settings import BaseSettings, SettingsConfigDict
|
|
|
|
|
|
class Settings(BaseSettings):
|
|
model_config = SettingsConfigDict(
|
|
env_prefix="PROCUREMENT_BOT_",
|
|
env_file=".env",
|
|
env_file_encoding="utf-8",
|
|
extra="ignore",
|
|
)
|
|
|
|
# Bale Bot API — Telegram-compatible clone hosted at tapi.bale.ai.
|
|
BALE_API_BASE: str = "https://tapi.bale.ai"
|
|
BOT_TOKEN: str = "" # from Bale's BotFather
|
|
POLL_TIMEOUT_SECONDS: int = 25 # getUpdates long-poll window
|
|
POLL_ERROR_SLEEP_SECONDS: float = 3.0
|
|
|
|
# ERP API (in-network service URL inside Docker).
|
|
API_BASE_URL: str = "http://localhost:8000/api/v1"
|
|
API_TIMEOUT_SECONDS: float = 30.0
|
|
# Optional bearer for the day procurement endpoints start enforcing auth.
|
|
SERVICE_TOKEN: str = ""
|
|
|
|
# Frontend URL (for opening Wizard from Bale bot)
|
|
FRONTEND_URL: str = "http://localhost:8081"
|
|
|
|
# Security token for standalone wizard review URL
|
|
DRAFT_TOKEN_SECRET: str = "procurement-draft-secret-change-in-prod-v7"
|
|
DRAFT_TOKEN_EXPIRE_SECONDS: int = 7200 # 2 hours
|
|
|
|
# Persistent storage directory for draft attachments (proformas)
|
|
ATTACHMENTS_DIR: str = "data/attachments/proformas"
|
|
|
|
# OpenAI-compatible AI provider (LLM), e.g. OpenAI / GLM / DeepSeek / OpenRouter.
|
|
AI_BASE_URL: str = "" # e.g. https://api.openai.com/v1
|
|
AI_API_KEY: str = ""
|
|
LLM_MODEL: str = "gpt-4o-mini"
|
|
LLM_TIMEOUT_SECONDS: float = 60.0
|
|
|
|
# STT providers — support multiple models/APIs in parallel.
|
|
# 1. JSON list: [{"name": "m1", "base_url": "...", "api_key": "...", "model": "..."}, ...]
|
|
STT_PROVIDERS_JSON: str = ""
|
|
|
|
# 2. Individual provider variables (up to 3 distinct STT models)
|
|
STT_PROVIDER_1_NAME: str = "model-1"
|
|
STT_PROVIDER_1_BASE_URL: str = ""
|
|
STT_PROVIDER_1_API_KEY: str = ""
|
|
STT_PROVIDER_1_MODEL: str = ""
|
|
STT_PROVIDER_1_LANGUAGE: str = "fa"
|
|
|
|
STT_PROVIDER_2_NAME: str = "model-2"
|
|
STT_PROVIDER_2_BASE_URL: str = ""
|
|
STT_PROVIDER_2_API_KEY: str = ""
|
|
STT_PROVIDER_2_MODEL: str = ""
|
|
STT_PROVIDER_2_LANGUAGE: str = "fa"
|
|
|
|
STT_PROVIDER_3_NAME: str = "model-3"
|
|
STT_PROVIDER_3_BASE_URL: str = ""
|
|
STT_PROVIDER_3_API_KEY: str = ""
|
|
STT_PROVIDER_3_MODEL: str = ""
|
|
STT_PROVIDER_3_LANGUAGE: str = "fa"
|
|
|
|
# Legacy single STT provider fallback:
|
|
STT_BASE_URL: str = ""
|
|
STT_API_KEY: str = ""
|
|
STT_MODEL: str = "whisper-1"
|
|
STT_LANGUAGE: str = "fa"
|
|
|
|
@property
|
|
def stt_base_url(self) -> str:
|
|
return self.STT_BASE_URL or self.AI_BASE_URL
|
|
|
|
@property
|
|
def stt_api_key(self) -> str:
|
|
return self.STT_API_KEY or self.AI_API_KEY
|
|
|
|
@property
|
|
def stt_providers(self) -> list[dict]:
|
|
import json
|
|
if self.STT_PROVIDERS_JSON:
|
|
try:
|
|
data = json.loads(self.STT_PROVIDERS_JSON)
|
|
if isinstance(data, list) and len(data) > 0:
|
|
return data
|
|
except Exception:
|
|
pass
|
|
|
|
# Check explicit STT_PROVIDER_1 / 2 / 3
|
|
custom_list: list[dict] = []
|
|
for idx in (1, 2, 3):
|
|
b_url = getattr(self, f"STT_PROVIDER_{idx}_BASE_URL")
|
|
key = getattr(self, f"STT_PROVIDER_{idx}_API_KEY")
|
|
model = getattr(self, f"STT_PROVIDER_{idx}_MODEL")
|
|
name = getattr(self, f"STT_PROVIDER_{idx}_NAME")
|
|
lang = getattr(self, f"STT_PROVIDER_{idx}_LANGUAGE") or "fa"
|
|
if b_url and key:
|
|
custom_list.append({
|
|
"name": name or f"model-{idx}",
|
|
"base_url": b_url,
|
|
"api_key": key,
|
|
"model": model or self.STT_MODEL,
|
|
"language": lang,
|
|
"timeout": 30.0,
|
|
})
|
|
if custom_list:
|
|
return custom_list
|
|
|
|
# Fallback to single legacy STT provider if set
|
|
if self.stt_base_url and self.stt_api_key:
|
|
return [{
|
|
"name": "default",
|
|
"base_url": self.stt_base_url,
|
|
"api_key": self.stt_api_key,
|
|
"model": self.STT_MODEL,
|
|
"language": self.STT_LANGUAGE,
|
|
"timeout": 30.0,
|
|
}]
|
|
return []
|
|
|
|
# PostgreSQL — same instance/database as the api service.
|
|
DATABASE_URL: str = "postgresql+asyncpg://postgres:postgres@localhost:5432/procurement"
|
|
|
|
# Chats that may use the bot without Casdoor linking (comma separated).
|
|
ADMIN_CHAT_IDS: str = ""
|
|
|
|
# Drafts older than this are marked expired by the sweeper loop.
|
|
DRAFT_TTL_HOURS: int = 24
|
|
|
|
# Observability (phase 1) — silent pipeline recorder (DB only; no external
|
|
# tools, no extra LLM tokens). Data is NEVER deleted.
|
|
OBS_ENABLED: bool = True
|
|
OBS_VOICE_DIR: str = "data/voices" # persistent volume (./bot/data) — keep forever
|
|
OBS_PROMPT_VERSION: str = "" # manual label for the NLU prompt in use
|
|
|
|
# Jev (TypeSafe) entity matching — phases 2-5. Model version is PINNED
|
|
# (phase 0 resolved jev-1.13.0) so upstream updates cannot silently change
|
|
# decisions; every response's actual model is recorded for drift detection.
|
|
TYPESAFE_API_KEY: str = ""
|
|
JEV_MODEL: str = "jev-1.13.0"
|
|
JEV_ENABLED: bool = True
|
|
JEV_TIMEOUT: float = 8.0
|
|
JEV_CONF_EXACT: float = 0.85
|
|
JEV_CONF_FLOOR: float = 0.60
|
|
JEV_MAX_QUESTIONS_PER_FIELD: int = 15
|
|
|
|
LOG_LEVEL: str = "INFO"
|
|
|
|
@property
|
|
def admin_chat_ids(self) -> set[int]:
|
|
out: set[int] = set()
|
|
for part in self.ADMIN_CHAT_IDS.replace(";", ",").split(","):
|
|
part = part.strip()
|
|
if part.isdigit():
|
|
out.add(int(part))
|
|
return out
|
|
|
|
|
|
settings = Settings()
|