Problem: the dashboard was Jev-centric; NLU/arbiter/fallback DeepSeek, STT
providers and the audio-enhancer were barely visible, and stored texts/voices
had no real access path.
Bot (additive; reply path untouched):
- nlu.result now records latency_ms + the DeepSeek usage tokens
- matching.arbitration/fallback.result fill the model + latency_ms columns
(payload unchanged; SQL coalesces column/payload so old rows still count)
- storage.py: MinIO dual-write layer — every voice (raw + denoised) and user
attachment is mirrored fire-and-forget into bucket bot-media; the blocking
minio SDK runs via asyncio.to_thread (senior-engineer review) so the event
loop is never stalled; empty MINIO_* env = layer off; bucket auto-created
- requirements: minio>=7.2
Backend (admin-gated, read-only):
- GET /bot-metrics/models — one record per model (jev, deepseek-nlu,
deepseek-arbiter, deepseek-fallback, audio-enhancer + dynamic per-provider
STT) with calls/ok-rate/p50/p95/tokens/last-seen + version-drift vs the pin
- GET /bot-metrics/models/{id}/daily — per-model daily calls/fails/tokens/p50
- GET /bot-metrics/stages — every stage tagged with its Persian pipeline
section (صوت/درک پیام/تطبیق/ابهام و انتخاب/پیشنویس)
- /traces now carries input_kind + a 120-char text excerpt (consensus →
input.text → first STT transcript)
- media serving: POST /media-url mints a short-lived HMAC URL (audio/a tags
cannot send Authorization); GET /media streams from MinIO bot-media with
the read-only ./bot/data mount as fallback for pre-MinIO files; hard ref
validation (voices|attachments only, no .., extension whitelist)
- router exempted from the global Bearer dependency (files.py pattern) —
every endpoint keeps its own require_role('admin')
Frontend /bot-monitor (RTL, recharts):
- four tabs: نمای کلی / مدلها (records table + per-model expandable daily
charts: calls/fails, tokens, p50) / بخشها (sections grouped) / پیامها
- message drawer rebuilt: inline <audio controls> for raw + denoised voice,
download links, every STT transcript + consensus side-by-side, user
attachments, then the event timeline
- terminology: «ترس» → «پروندهی پیام» with tooltips + a one-line legend
Grafana: bot-observability gains a «کارکرد مدلها» table (stage→model
mapping for legacy rows); the explorer gains a message text column.
Seed: real (tiny) ogg files written + mirrored to MinIO, NLU usage tokens,
column-level model/latency on matching events.
Verified locally: /models returns all 7 records incl. per-STT and NLU tokens;
media 200 via signed URL (MinIO) and 401 without; ../ and .py rejected (400);
disk fallback serves a legacy file; pm-role 403 on every new endpoint;
bucket auto-created with 14 mirrored objects; tsc + vite build clean;
Grafana re-provisions 24 panels.
procurement_ai_agent — Bale chatbot for the procurement ERP
A Bale messenger bot that turns Persian chat messages and voice notes into procurement actions in the procurement ERP — draft-first: it captures what it understood, tells you what it did and what is still empty, and commits only after you approve with a ✅ button.
you (Bale, text/voice) ┌─────────────────────────────────┐
│ getUpdates (long poll) │ procurement_ai_agent │
▼ │ ffmpeg → STT (Persian) │
┌──────────────────┐ POST {base}/bot<T> │ LLM → intent + entities │
│ tapi.bale.ai │◄───────────────────────►│ fuzzy resolve → draft payload │
└──────────────────┘ sendMessage / buttons │ review + «چه چیزهایی خالی مونده»│
└───────────────┬─────────────────┘
│ HTTP + X-Actor-Id
▼
┌─────────────────────────────────┐
│ ERP api (/api/v1) │
│ quotes · suppliers · materials│
└─────────────────────────────────┘
What it can do
| Activity | Example (voice or text) | Committed via |
|---|---|---|
| Register a supplier quote | «سازان نو برای پروژه برج آسمان ۵۰۰ کیلو میلگرد A3 سایز ۱۴، هر کیلو ۴۵ تومن، پرداخت ۳ فاز» | POST /quotes |
| Add a supplier | «تأمینکننده جدید پروفیل بر، دسته لوله و اتصالات، تلفن ۰۹۱۲…» | POST /suppliers |
| Add a material | «کالای جدید میلگرد A3 سایز ۱۸ با واحد کیلوگرم» | POST /materials |
| Status queries | «استعلامهای در انتظار؟» / «کدامها بهزودی منقضی میشوند؟» | GET /quotes?… |
| Accept a quote | «استعلام سازان نو را قبول کن» | PATCH /quotes/{id}/accept |
| Announce a delivery | «اقلام سازان نو رسید، ۵۰۰ و ۲۰۰» | PATCH /quotes/{id}/arrive-items |
The draft → approve loop
- Send a message or voice note. Voice → ffmpeg → STT; text/STT text → LLM extracts a typed intent + entities (JSON mode, Persian digits normalized).
- Names are fuzzy-matched against the ERP. Several candidates → inline pick buttons; no match → listed as missing.
- The bot replies with a review card: everything captured + a ✅/⚠️/❌ list of what is still empty.
- Keep chatting to refine («قیمت میلگرد ۴۷ شد») — the open draft updates and re-renders. Drafts survive bot restarts (postgres-backed, TTL-swept).
- Nothing is written to the ERP until you tap ✅. After commit you get the created quote id and the fields left empty.
Team access & attribution
Each member links their Bale chat once: /start → Casdoor username → password
(validated via the ERP's real POST /auth/login, used once, never stored).
Every mutating call carries X-Actor-Id: <users.id> so quote_events.actor
records the human who asked.
Commands: /start · /help · /drafts · /cancel · /whoami · /unlink
Quick start (Docker)
cp .env.example .env # fill PROCUREMENT_BOT_BOT_TOKEN + AI_API_KEY
docker build -t procurement-ai-agent .
docker run -d --name procurement-bot --env-file .env \
--add-host host.docker.internal:host-gateway \
procurement-ai-agent
docker logs -f procurement-bot
Or as part of the ERP stack — see integration/
(compose service + the one tiny ERP-side patch).
Full setup, env-var reference, flows and troubleshooting: docs/SETUP.md.
Architecture
app/
├── main.py ensure bot tables → sweeper task → getUpdates long-poll loop
├── config.py pydantic-settings, PROCUREMENT_BOT_ prefix
├── bale/client.py Telegram-compatible Bale API (poll, send, edit, buttons, files)
├── api/client.py ERP /api/v1 client (X-Actor-Id attribution, error envelope)
├── stt.py ffmpeg (OGG/Opus → MP3) → OpenAI-compatible /audio/transcriptions
├── nlu.py Persian intent+entity extraction (JSON-mode chat completions)
├── resolve.py fuzzy name→id matching (difflib over ilike search), TTL caches
├── drafts.py draft store · QuoteCreate payload builder · missing-field logic
├── keyboards.py inline keyboards (callback_data ≤ 64 B op-codes)
├── texts.py Persian message templates
├── runtime.py context, link store, in-memory pending flows
├── models.py bot_links / bot_drafts / bot_messages / bot_meta (own schema)
└── handlers/ dispatch · commands · callbacks · links ·
quote · supplier · material · queries · decisions
Design notes:
- Telegram-compatible Bale API (
tapi.bale.ai): getUpdates long polling — no public port, no webhook, resumable offset persisted across restarts. - Draft-first:
bot_drafts.payloadholds a talking-friendly JSON that is converted into the exactPOST /quotesrequest body (temp_id cross-references) only on approval; the API deliberately tolerates incomplete quotes, so partial commits are explicit, never accidental. - Accept flow echoes the termsheet's existing
schedule_stepsback toPATCH /quotes/{id}/accept(the API replaces steps with what it receives). - Persian-aware matching: Persian/Arabic digit normalization, ZWNJ folding, Arabic ya/ka folding, difflib ranking on top of the API's ilike search.
- Voice notes arrive as OGG/Opus; ffmpeg converts to mono 16 kHz MP3 before STT. The LLM provider and the STT provider are configured independently (e.g. DeepSeek for NLU + any whisper-compatible endpoint for voice).
Testing
An offline end-to-end harness stubs Bale/ERP/AI and drives the real handler pipeline with fake updates — no token, DB or API key needed:
pip install -r requirements.txt
python tools/smoke_test.py # → ALL PASSED: 48 passed