feat: OpenAI GPT-4o по умолчанию + биллинг + алерт $5
- rag.py: добавлен provider "openai" (GPT-4o), по умолчанию - billing.py: трекинг расходов по токенам, get_balance() - telegram_bot.py: - /ask через GPT-4o (было GLM-5) - /balance — показать остаток OpenAI - Алерт админу при balance < $5 - Admin chat ID = первый кто нажмёт /start Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,96 @@
|
||||
"""
|
||||
OpenAI billing tracker + admin alerts.
|
||||
|
||||
Tracks cumulative spend based on token usage.
|
||||
Sends Telegram alert when balance drops below threshold.
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
BILLING_FILE = Path(__file__).parent / "billing.json"
|
||||
|
||||
# Pricing per 1M tokens (USD), as of March 2026
|
||||
PRICING = {
|
||||
"gpt-4o": {"input": 2.50, "output": 10.00},
|
||||
"gpt-4o-mini": {"input": 0.15, "output": 0.60},
|
||||
"text-embedding-3-small": {"input": 0.02, "output": 0.0},
|
||||
"text-embedding-3-large": {"input": 0.13, "output": 0.0},
|
||||
}
|
||||
|
||||
|
||||
def _load_state() -> dict:
|
||||
if BILLING_FILE.exists():
|
||||
with open(BILLING_FILE) as f:
|
||||
return json.load(f)
|
||||
return {"initial_balance": 14.0, "total_spent": 0.0, "alert_sent_at": 0.0}
|
||||
|
||||
|
||||
def _save_state(state: dict):
|
||||
with open(BILLING_FILE, "w") as f:
|
||||
json.dump(state, f, indent=2)
|
||||
|
||||
|
||||
def track_usage(model: str, input_tokens: int, output_tokens: int):
|
||||
"""Track token usage and calculate cost."""
|
||||
pricing = PRICING.get(model, PRICING.get("gpt-4o-mini"))
|
||||
cost = (input_tokens * pricing["input"] + output_tokens * pricing["output"]) / 1_000_000
|
||||
|
||||
state = _load_state()
|
||||
state["total_spent"] = round(state["total_spent"] + cost, 6)
|
||||
_save_state(state)
|
||||
|
||||
return cost
|
||||
|
||||
|
||||
def get_balance() -> float:
|
||||
"""Get estimated remaining balance."""
|
||||
state = _load_state()
|
||||
return round(state["initial_balance"] - state["total_spent"], 2)
|
||||
|
||||
|
||||
def get_stats() -> dict:
|
||||
"""Get billing statistics."""
|
||||
state = _load_state()
|
||||
balance = round(state["initial_balance"] - state["total_spent"], 2)
|
||||
return {
|
||||
"initial_balance": state["initial_balance"],
|
||||
"total_spent": round(state["total_spent"], 4),
|
||||
"balance": balance,
|
||||
}
|
||||
|
||||
|
||||
def set_initial_balance(amount: float):
|
||||
"""Set or update initial balance."""
|
||||
state = _load_state()
|
||||
state["initial_balance"] = amount
|
||||
_save_state(state)
|
||||
|
||||
|
||||
async def check_and_alert(bot, admin_chat_id: int, threshold: float = 5.0):
|
||||
"""Check balance and send Telegram alert if below threshold."""
|
||||
state = _load_state()
|
||||
balance = state["initial_balance"] - state["total_spent"]
|
||||
|
||||
if balance <= threshold and state.get("alert_sent_at", 0) < state["total_spent"]:
|
||||
try:
|
||||
await bot.send_message(
|
||||
chat_id=admin_chat_id,
|
||||
text=(
|
||||
f"⚠️ **Внимание: баланс OpenAI низкий!**\n\n"
|
||||
f"Остаток: **${balance:.2f}**\n"
|
||||
f"Потрачено: ${state['total_spent']:.4f}\n"
|
||||
f"Порог: ${threshold:.2f}\n\n"
|
||||
f"Пополните баланс на platform.openai.com"
|
||||
),
|
||||
parse_mode="Markdown",
|
||||
)
|
||||
state["alert_sent_at"] = state["total_spent"]
|
||||
_save_state(state)
|
||||
logger.warning(f"Balance alert sent: ${balance:.2f} remaining")
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to send balance alert: {e}")
|
||||
@@ -98,6 +98,20 @@ class SmetaAssistant:
|
||||
)
|
||||
return response.choices[0].message.content or ""
|
||||
|
||||
def _call_openai(self, messages: list[dict]) -> str:
|
||||
"""Call GPT-4o via OpenAI API."""
|
||||
from openai import OpenAI
|
||||
|
||||
api_key = os.environ.get("OPENAI_API_KEY")
|
||||
client = OpenAI(api_key=api_key)
|
||||
response = client.chat.completions.create(
|
||||
model="gpt-4o",
|
||||
messages=messages,
|
||||
temperature=0,
|
||||
max_tokens=4096,
|
||||
)
|
||||
return response.choices[0].message.content or ""
|
||||
|
||||
def _call_anthropic(self, messages: list[dict]) -> str:
|
||||
"""Call Claude via Anthropic API."""
|
||||
from anthropic import Anthropic
|
||||
@@ -138,7 +152,9 @@ class SmetaAssistant:
|
||||
]
|
||||
|
||||
# Call LLM
|
||||
if self.llm_provider == "glm":
|
||||
if self.llm_provider == "openai":
|
||||
return self._call_openai(messages)
|
||||
elif self.llm_provider == "glm":
|
||||
return self._call_glm(messages)
|
||||
elif self.llm_provider == "anthropic":
|
||||
return self._call_anthropic(messages)
|
||||
|
||||
@@ -26,6 +26,9 @@ from telegram.ext import (
|
||||
|
||||
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."""
|
||||
@@ -40,7 +43,9 @@ def _get_assistant():
|
||||
"""Lazy-load SmetaAssistant."""
|
||||
from smeta_railway.ai.rag import SmetaAssistant
|
||||
index_dir = Path(__file__).parent / "index"
|
||||
return SmetaAssistant(rag_index_dir=index_dir, llm_provider="glm")
|
||||
# Use OpenAI GPT-4o for quality (fallback to GLM-5 if no key)
|
||||
provider = "openai" if os.environ.get("OPENAI_API_KEY") else "glm"
|
||||
return SmetaAssistant(rag_index_dir=index_dir, llm_provider=provider)
|
||||
|
||||
|
||||
# Lazy singletons
|
||||
@@ -63,13 +68,21 @@ def get_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\n"
|
||||
"💰 /sp <вид работ> — сметная прибыль\n"
|
||||
"⚙️ /auto <описание> — сгенерировать смету\n"
|
||||
"💵 /balance — баланс OpenAI API\n\n"
|
||||
"Или просто напишите описание работ — я найду подходящие расценки."
|
||||
)
|
||||
|
||||
@@ -123,6 +136,7 @@ async def search_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||||
|
||||
|
||||
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 какой НР для ж/д работ?")
|
||||
@@ -133,10 +147,15 @@ async def ask_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||||
try:
|
||||
assistant = get_assistant()
|
||||
answer = assistant.ask(question)
|
||||
# Truncate long answers for Telegram
|
||||
if len(answer) > 4000:
|
||||
answer = answer[:3900] + "\n\n... (ответ сокращён)"
|
||||
await update.message.reply_text(answer)
|
||||
|
||||
# Track billing + alert
|
||||
from smeta_railway.ai.billing import track_usage, check_and_alert
|
||||
track_usage("gpt-4o", 5000, 500) # approximate tokens
|
||||
if ADMIN_CHAT_ID:
|
||||
await check_and_alert(context.bot, ADMIN_CHAT_ID, threshold=5.0)
|
||||
except Exception as e:
|
||||
logger.error(f"Ask error: {e}")
|
||||
await update.message.reply_text(f"Ошибка: {e}")
|
||||
@@ -222,6 +241,18 @@ async def check_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||||
)
|
||||
|
||||
|
||||
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()
|
||||
@@ -266,6 +297,7 @@ def run_bot():
|
||||
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...")
|
||||
|
||||
Reference in New Issue
Block a user