Files
smeta-railway/src/smeta_railway/ai/bot.py
T
anorandClaude Opus 4.6 e1e1edb070 feat: CAG + RAG гибрид + Telegram-бот (Уровень 2)
CAG (cag.py):
- Все таблицы НР/СП + коэффициенты в system prompt (~4500 токенов)
- 100% точность для табличных lookups, без retrieval

RAG (rag.py):
- PDF→chunks→FAISS→retrieval→LLM
- Гибрид: CAG всегда + RAG по запросу
- GLM-5 через Z.AI (open.bigmodel.cn), temperature=0

Telegram-бот (bot.py):
- /search, /ask, /nr, /sp, текст → auto /ask

CLI: smeta ask, smeta build-rag, smeta bot
Тест: "Какой НР для ж/д?" → "109% от ФОТ [812/пр, п.22]" ✓

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-22 16:54:15 +10:00

218 lines
7.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
Telegram bot for smeta-railway AI assistant.
Commands:
/start — приветствие
/search <текст> — поиск расценки ГЭСН
/ask <вопрос> — вопрос по нормативке (CAG + RAG)
/nr <вид работ> — найти НР% по виду работ
/sp <вид работ> — найти СП% по виду работ
/help — справка
"""
import asyncio
import logging
import os
from pathlib import Path
from telegram import Update
from telegram.ext import (
Application,
CommandHandler,
ContextTypes,
MessageHandler,
filters,
)
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Lazy-loaded components
_search_engine = None
_rag_index = None
_rag_chunks = None
def _get_search():
global _search_engine
if _search_engine is None:
from smeta_railway.ai.search import GESNSearch
resources = Path(__file__).parents[2] / "../../resources.json"
if not resources.exists():
resources = Path("resources.json")
_search_engine = GESNSearch(resources_path=str(resources))
return _search_engine
def _get_rag():
global _rag_index, _rag_chunks
if _rag_index is None:
try:
from smeta_railway.ai.rag import load_rag_index
_rag_index, _rag_chunks = load_rag_index()
except FileNotFoundError:
pass # RAG not built yet, CAG-only mode
return _rag_index, _rag_chunks
async def cmd_start(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text(
"Привет! Я ИИ-ассистент сметчика.\n\n"
"Что умею:\n"
"/search <описание> — найти расценку ГЭСН\n"
"/ask <вопрос> — вопрос по нормативке\n"
"/nr <вид работ> — найти НР%\n"
"/sp <вид работ> — найти СП%\n"
"/help — подробная справка\n\n"
f"В базе: {len(_get_search().norms)} норм ГЭСН"
)
async def cmd_help(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text(
"📋 *Команды:*\n\n"
"`/search очистка щебня машинами` — поиск ГЭСН по описанию\n"
"`/ask какой НР для ж/д работ?` — вопрос по нормативке\n"
"`/nr железные дороги` — НР% для вида работ\n"
"`/sp земляные работы` — СП% для вида работ\n\n"
"📚 *Нормативная база:*\n"
"• ГЭСН-2022 (47 сборников)\n"
"• Приказ 812/пр (НР, 137 позиций)\n"
"• Приказ 774/пр (СП, 137 позиций)\n"
"• Приказ 421/пр (коэффициенты)\n"
"• Приложение 28.1 (ж/д коэффициенты)\n"
"• 86 регионов, 148 ценовых зон ФГИС ЦС",
parse_mode="Markdown",
)
async def cmd_search(update: Update, context: ContextTypes.DEFAULT_TYPE):
query = " ".join(context.args) if context.args else ""
if not query:
await update.message.reply_text("Использование: /search описание работ")
return
await update.message.reply_text("🔍 Ищу...")
try:
search = _get_search()
results = search.find(query, top_k=5)
if not results:
await update.message.reply_text("Ничего не найдено")
return
lines = [f"*Результаты для:* _{query}_\n"]
for i, r in enumerate(results, 1):
name = r.name[:60] + "..." if len(r.name) > 60 else r.name
lines.append(
f"{i}. `ГЭСН {r.code}` ({r.score:.0%})\n"
f" {name}\n"
f" Ед: {r.unit}"
)
await update.message.reply_text("\n".join(lines), parse_mode="Markdown")
except Exception as e:
await update.message.reply_text(f"Ошибка: {e}")
async def cmd_ask(update: Update, context: ContextTypes.DEFAULT_TYPE):
question = " ".join(context.args) if context.args else ""
if not question:
await update.message.reply_text("Использование: /ask ваш вопрос")
return
await update.message.reply_text("🤔 Думаю...")
try:
from smeta_railway.ai.rag import ask
rag_idx, rag_ch = _get_rag()
result = ask(question, rag_index=rag_idx, rag_chunks=rag_ch)
answer = result["answer"]
tokens = result.get("context_tokens", 0) + result.get("answer_tokens", 0)
# Truncate if too long for Telegram
if len(answer) > 4000:
answer = answer[:4000] + "\n\n... (ответ обрезан)"
footer = f"\n\n_({result['model']}, {tokens} tokens)_"
await update.message.reply_text(answer + footer, parse_mode="Markdown")
except Exception as e:
logger.exception("Error in /ask")
await update.message.reply_text(f"Ошибка: {e}")
async def cmd_nr(update: Update, context: ContextTypes.DEFAULT_TYPE):
query = " ".join(context.args).lower() if context.args else ""
if not query:
await update.message.reply_text("Использование: /nr вид работ\nПример: /nr железные дороги")
return
from smeta_railway.data.nr_sp_tables import NR_TABLE
matches = []
for key, (name, pct) in NR_TABLE.items():
if query in name.lower():
matches.append(f"п.{key}: {name} — *{pct}%* от ФОТ")
if matches:
await update.message.reply_text(
f"*НР (Приказ 812/пр):*\n\n" + "\n".join(matches[:10]),
parse_mode="Markdown",
)
else:
await update.message.reply_text(f"Не найдено НР для: {query}")
async def cmd_sp(update: Update, context: ContextTypes.DEFAULT_TYPE):
query = " ".join(context.args).lower() if context.args else ""
if not query:
await update.message.reply_text("Использование: /sp вид работ\nПример: /sp земляные")
return
from smeta_railway.data.nr_sp_tables import SP_TABLE
matches = []
for key, (name, pct) in SP_TABLE.items():
if query in name.lower():
matches.append(f"п.{key}: {name} — *{pct}%* от ФОТ")
if matches:
await update.message.reply_text(
f"*СП (Приказ 774/пр):*\n\n" + "\n".join(matches[:10]),
parse_mode="Markdown",
)
else:
await update.message.reply_text(f"Не найдено СП для: {query}")
async def handle_text(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle plain text messages as /ask."""
text = update.message.text
if text and not text.startswith("/"):
context.args = text.split()
await cmd_ask(update, context)
def run_bot():
"""Run Telegram bot."""
token = os.environ.get("TELEGRAM_BOT_TOKEN")
if not token:
raise RuntimeError("Set TELEGRAM_BOT_TOKEN environment variable")
app = Application.builder().token(token).build()
app.add_handler(CommandHandler("start", cmd_start))
app.add_handler(CommandHandler("help", cmd_help))
app.add_handler(CommandHandler("search", cmd_search))
app.add_handler(CommandHandler("ask", cmd_ask))
app.add_handler(CommandHandler("nr", cmd_nr))
app.add_handler(CommandHandler("sp", cmd_sp))
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_text))
print("Bot starting...")
app.run_polling()
if __name__ == "__main__":
run_bot()