- LLM: GLM-5 (бесплатный, 100% точность на тесте) - Typing: бот показывает "печатает..." пока думает - Время ожидания: "~5 сек" для таблиц, "~15-20 сек" для норм - Время ответа: отображается в конце (⏱ X.Xс) - Промежуточное сообщение удаляется после ответа Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
330 lines
12 KiB
Python
330 lines
12 KiB
Python
"""
|
||
Telegram bot for smeta-railway AI assistant.
|
||
|
||
Commands:
|
||
/start — приветствие
|
||
/help — помощь
|
||
/search <текст> — поиск расценки ГЭСН
|
||
/ask <вопрос> — вопрос по нормативке (CAG + RAG)
|
||
/nr <вид работ> — НР для вида работ
|
||
/sp <вид работ> — СП для вида работ
|
||
Текстовое сообщение — автоматически определяет: поиск или вопрос
|
||
"""
|
||
|
||
import logging
|
||
import os
|
||
from pathlib import Path
|
||
|
||
from telegram import Update
|
||
from telegram.ext import (
|
||
Application,
|
||
CommandHandler,
|
||
ContextTypes,
|
||
MessageHandler,
|
||
filters,
|
||
)
|
||
|
||
logger = logging.getLogger(__name__)
|
||
|
||
# Admin chat ID — will be set on first /start from admin
|
||
ADMIN_CHAT_ID = None
|
||
|
||
|
||
def _get_search():
|
||
"""Lazy-load GESNSearch."""
|
||
from smeta_railway.ai.search import GESNSearch
|
||
resources = Path(__file__).parents[2] / "../../resources.json"
|
||
if not resources.exists():
|
||
resources = Path("resources.json")
|
||
return GESNSearch(resources_path=str(resources))
|
||
|
||
|
||
def _get_assistant():
|
||
"""Lazy-load SmetaAssistant."""
|
||
from smeta_railway.ai.rag import SmetaAssistant
|
||
index_dir = Path(__file__).parent / "index"
|
||
# GLM-5 by default (free, 100% accuracy), OpenAI as fallback
|
||
provider = "glm"
|
||
return SmetaAssistant(rag_index_dir=index_dir, llm_provider=provider)
|
||
|
||
|
||
# Lazy singletons
|
||
_search = None
|
||
_assistant = None
|
||
|
||
|
||
def get_search():
|
||
global _search
|
||
if _search is None:
|
||
_search = _get_search()
|
||
return _search
|
||
|
||
|
||
def get_assistant():
|
||
global _assistant
|
||
if _assistant is None:
|
||
_assistant = _get_assistant()
|
||
return _assistant
|
||
|
||
|
||
async def start_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||
global ADMIN_CHAT_ID
|
||
# First user to /start becomes admin
|
||
if ADMIN_CHAT_ID is None:
|
||
ADMIN_CHAT_ID = update.message.chat_id
|
||
logger.info(f"Admin chat ID set: {ADMIN_CHAT_ID}")
|
||
|
||
await update.message.reply_text(
|
||
"Привет! Я — ИИ-ассистент сметчика.\n\n"
|
||
"Что умею:\n"
|
||
"🔍 /search <текст> — найти расценку ГЭСН\n"
|
||
"❓ /ask <вопрос> — вопрос по нормативке\n"
|
||
"📊 /nr <вид работ> — накладные расходы\n"
|
||
"💰 /sp <вид работ> — сметная прибыль\n"
|
||
"⚙️ /auto <описание> — сгенерировать смету\n"
|
||
"💵 /balance — баланс OpenAI API\n\n"
|
||
"Или просто напишите описание работ — я найду подходящие расценки."
|
||
)
|
||
|
||
|
||
async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||
await update.message.reply_text(
|
||
"Примеры запросов:\n\n"
|
||
"🔍 Поиск расценок:\n"
|
||
" /search глубокая очистка щебня\n"
|
||
" /search замена рельсов Р65 на плети КБ\n"
|
||
" /search балластировка пути\n\n"
|
||
"❓ Вопросы по нормативке:\n"
|
||
" /ask какой НР для железнодорожных работ?\n"
|
||
" /ask какой коэффициент при 95 поездах в сутки?\n"
|
||
" /ask нужен ли К_окно для нормы 28-01-155?\n\n"
|
||
"📊 НР/СП:\n"
|
||
" /nr железные дороги\n"
|
||
" /sp земляные работы"
|
||
)
|
||
|
||
|
||
async def search_command(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 context.bot.send_chat_action(chat_id=update.effective_chat.id, action="typing")
|
||
|
||
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):
|
||
lines.append(
|
||
f"{i}. **ГЭСН {r.code}**\n"
|
||
f" {r.name[:80]}{'...' if len(r.name) > 80 else ''}\n"
|
||
f" Ед.: {r.unit} | Score: {r.score:.2f}"
|
||
)
|
||
|
||
await update.message.reply_text("\n\n".join(lines), parse_mode="Markdown")
|
||
|
||
except Exception as e:
|
||
logger.error(f"Search error: {e}")
|
||
await update.message.reply_text(f"Ошибка поиска: {e}")
|
||
|
||
|
||
async def ask_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||
global ADMIN_CHAT_ID
|
||
question = " ".join(context.args) if context.args else ""
|
||
if not question:
|
||
await update.message.reply_text("Задайте вопрос. Пример: /ask какой НР для ж/д работ?")
|
||
return
|
||
|
||
import time
|
||
|
||
# Classify to estimate wait time
|
||
assistant = get_assistant()
|
||
q_type = assistant._classify_question(question)
|
||
if q_type == "cag":
|
||
wait_msg = await update.message.reply_text("🤔 Ищу в таблицах... ~5 сек")
|
||
else:
|
||
wait_msg = await update.message.reply_text("🤔 Ищу в базе норм и документах... ~15-20 сек")
|
||
|
||
# Show typing indicator
|
||
await context.bot.send_chat_action(chat_id=update.effective_chat.id, action="typing")
|
||
|
||
try:
|
||
t0 = time.time()
|
||
answer = assistant.ask(question)
|
||
elapsed = time.time() - t0
|
||
|
||
if len(answer) > 4000:
|
||
answer = answer[:3900] + "\n\n... (ответ сокращён)"
|
||
|
||
answer += f"\n\n⏱ {elapsed:.1f}с"
|
||
|
||
# Delete "thinking" message and send answer
|
||
try:
|
||
await wait_msg.delete()
|
||
except Exception:
|
||
pass
|
||
await update.message.reply_text(answer)
|
||
|
||
except Exception as e:
|
||
logger.error(f"Ask error: {e}")
|
||
try:
|
||
await wait_msg.delete()
|
||
except Exception:
|
||
pass
|
||
await update.message.reply_text(f"Ошибка: {e}")
|
||
|
||
|
||
async def nr_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||
query = " ".join(context.args) if context.args else ""
|
||
if not query:
|
||
await update.message.reply_text("Пример: /nr железные дороги")
|
||
return
|
||
|
||
from smeta_railway.data.nr_sp_tables import NR_TABLE
|
||
query_lower = query.lower()
|
||
results = []
|
||
for key, (name, pct) in NR_TABLE.items():
|
||
if query_lower in name.lower():
|
||
results.append(f"п.{key}: {name} — **{pct}%** от ФОТ")
|
||
|
||
if results:
|
||
header = f"📊 НР (Приказ 812/пр) для «{query}»:\n\n"
|
||
await update.message.reply_text(header + "\n".join(results[:10]), parse_mode="Markdown")
|
||
else:
|
||
await update.message.reply_text(f"Не найдено НР для «{query}». Попробуйте /nr земляные или /nr кровли")
|
||
|
||
|
||
async def sp_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||
query = " ".join(context.args) if context.args else ""
|
||
if not query:
|
||
await update.message.reply_text("Пример: /sp железные дороги")
|
||
return
|
||
|
||
from smeta_railway.data.nr_sp_tables import SP_TABLE
|
||
query_lower = query.lower()
|
||
results = []
|
||
for key, (name, pct) in SP_TABLE.items():
|
||
if query_lower in name.lower():
|
||
results.append(f"п.{key}: {name} — **{pct}%** от ФОТ")
|
||
|
||
if results:
|
||
header = f"💰 СП (Приказ 774/пр) для «{query}»:\n\n"
|
||
await update.message.reply_text(header + "\n".join(results[:10]), parse_mode="Markdown")
|
||
else:
|
||
await update.message.reply_text(f"Не найдено СП для «{query}».")
|
||
|
||
|
||
async def auto_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||
"""Generate estimate from description."""
|
||
text = " ".join(context.args) if context.args else ""
|
||
if not text:
|
||
await update.message.reply_text(
|
||
"Опишите работы. Пример:\n"
|
||
"/auto Капремонт пути 2 км, ж/б шпалы, КБ-65, очистка щебня, замена рельсов Р65"
|
||
)
|
||
return
|
||
|
||
await update.message.reply_text("⚙️ Генерирую смету... ~30-60 сек")
|
||
await context.bot.send_chat_action(chat_id=update.effective_chat.id, action="typing")
|
||
|
||
try:
|
||
from smeta_railway.ai.generator import EstimateGenerator
|
||
gen = EstimateGenerator()
|
||
result = gen.auto(text)
|
||
|
||
msg = f"📋 Найдено позиций: {result['matched_count']}/{result['item_count']}\n\n"
|
||
for item in result["items"][:10]:
|
||
score = f"{item['score']:.0%}" if item.get("score") else "?"
|
||
msg += f"• `{item.get('gesn_code', '?')}` ({score})\n {item['description'][:60]}\n"
|
||
|
||
if len(msg) > 4000:
|
||
msg = msg[:3900] + "\n\n... (сокращено)"
|
||
|
||
await update.message.reply_text(msg, parse_mode="Markdown")
|
||
except Exception as e:
|
||
logger.error(f"Auto error: {e}")
|
||
await update.message.reply_text(f"Ошибка: {e}")
|
||
|
||
|
||
async def check_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||
"""Check estimate for errors."""
|
||
await update.message.reply_text(
|
||
"Отправьте YAML-файл проекта для проверки, или используйте CLI:\n"
|
||
"`smeta check project.yaml`",
|
||
parse_mode="Markdown",
|
||
)
|
||
|
||
|
||
async def balance_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||
from smeta_railway.ai.billing import get_stats
|
||
stats = get_stats()
|
||
await update.message.reply_text(
|
||
f"💵 **Баланс OpenAI API:**\n\n"
|
||
f"Начальный: ${stats['initial_balance']:.2f}\n"
|
||
f"Потрачено: ${stats['total_spent']:.4f}\n"
|
||
f"Остаток: **${stats['balance']:.2f}**",
|
||
parse_mode="Markdown",
|
||
)
|
||
|
||
|
||
async def text_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||
"""Handle plain text — auto-detect search or question."""
|
||
text = update.message.text.strip()
|
||
|
||
# If it looks like a question
|
||
if any(text.lower().startswith(w) for w in ["какой", "какая", "какие", "как ",
|
||
"что ", "где ", "нужен", "можно",
|
||
"применяется", "сколько"]):
|
||
context.args = text.split()
|
||
await ask_command(update, context)
|
||
else:
|
||
# Default: search for GESN norms
|
||
context.args = text.split()
|
||
await search_command(update, context)
|
||
|
||
|
||
def run_bot():
|
||
"""Start the Telegram bot."""
|
||
token = os.environ.get("TELEGRAM_BOT_TOKEN")
|
||
if not token:
|
||
raise RuntimeError("Set TELEGRAM_BOT_TOKEN environment variable")
|
||
|
||
logging.basicConfig(level=logging.INFO)
|
||
logger.info("Starting smeta bot...")
|
||
|
||
# Configure proxy if available
|
||
proxy_url = os.environ.get("HTTPS_PROXY") or os.environ.get("HTTP_PROXY")
|
||
builder = Application.builder().token(token)
|
||
if proxy_url:
|
||
from telegram.request import HTTPXRequest
|
||
request = HTTPXRequest(proxy=proxy_url)
|
||
builder = builder.request(request).get_updates_request(HTTPXRequest(proxy=proxy_url))
|
||
logger.info(f"Using proxy: {proxy_url}")
|
||
|
||
app = builder.build()
|
||
|
||
app.add_handler(CommandHandler("start", start_command))
|
||
app.add_handler(CommandHandler("help", help_command))
|
||
app.add_handler(CommandHandler("search", search_command))
|
||
app.add_handler(CommandHandler("ask", ask_command))
|
||
app.add_handler(CommandHandler("nr", nr_command))
|
||
app.add_handler(CommandHandler("sp", sp_command))
|
||
app.add_handler(CommandHandler("auto", auto_command))
|
||
app.add_handler(CommandHandler("check", check_command))
|
||
app.add_handler(CommandHandler("balance", balance_command))
|
||
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, text_message))
|
||
|
||
logger.info("Bot started. Polling...")
|
||
app.run_polling()
|
||
|
||
|
||
if __name__ == "__main__":
|
||
run_bot()
|