Spaces:
Runtime error
Runtime error
Update telegram_bot.py
Browse files- telegram_bot.py +54 -25
telegram_bot.py
CHANGED
|
@@ -5,13 +5,17 @@ from dotenv import load_dotenv
|
|
| 5 |
from telegram import Update, ReplyKeyboardMarkup, ReplyKeyboardRemove
|
| 6 |
import datetime
|
| 7 |
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes, ConversationHandler
|
|
|
|
|
|
|
| 8 |
import logging
|
| 9 |
|
| 10 |
-
#
|
| 11 |
-
from
|
| 12 |
-
from langchain_community.vectorstores import Chroma
|
| 13 |
|
| 14 |
# Load environment variables
|
|
|
|
|
|
|
| 15 |
load_dotenv()
|
| 16 |
|
| 17 |
# Enable logging
|
|
@@ -30,9 +34,14 @@ class TelegramHomeopathyBot:
|
|
| 30 |
self.logs_dir = "UserChatLogs"
|
| 31 |
os.makedirs(self.logs_dir, exist_ok=True)
|
| 32 |
|
|
|
|
|
|
|
|
|
|
| 33 |
# Initialize embeddings and vector store
|
| 34 |
self.embeddings = HuggingFaceEmbeddings(
|
| 35 |
-
model_name=
|
|
|
|
|
|
|
| 36 |
)
|
| 37 |
self.vector_store = Chroma(
|
| 38 |
persist_directory="./vector_db",
|
|
@@ -43,7 +52,6 @@ class TelegramHomeopathyBot:
|
|
| 43 |
# Store user sessions: includes chat_history
|
| 44 |
self.user_sessions = {}
|
| 45 |
|
| 46 |
-
# FIX 4: Removed duplicate log_chat definition
|
| 47 |
def log_chat(self, user_id: int, username: str, message: str, is_bot: bool = False):
|
| 48 |
"""Log user/bot messages to individual files"""
|
| 49 |
try:
|
|
@@ -62,7 +70,7 @@ class TelegramHomeopathyBot:
|
|
| 62 |
self.user_sessions[user_id] = {
|
| 63 |
'chat_history': [],
|
| 64 |
'consultation_count': 0,
|
| 65 |
-
'last_query': None
|
| 66 |
}
|
| 67 |
return self.user_sessions[user_id]
|
| 68 |
|
|
@@ -71,11 +79,9 @@ class TelegramHomeopathyBot:
|
|
| 71 |
Retrieve relevant context from the vector database using the latest query
|
| 72 |
and the accumulated user history for better RAG results.
|
| 73 |
"""
|
| 74 |
-
# Create a composite query string from previous user inputs and the latest query
|
| 75 |
user_history = [msg['content'] for msg in history if msg['role'] == 'user']
|
| 76 |
history_summary = " ".join(user_history)
|
| 77 |
|
| 78 |
-
# Combine the user's history and current message for a comprehensive retrieval query
|
| 79 |
composite_query = f"Patient's case summary: {history_summary} {query}" if history_summary else query
|
| 80 |
|
| 81 |
docs = self.retriever.invoke(composite_query)
|
|
@@ -114,14 +120,12 @@ class TelegramHomeopathyBot:
|
|
| 114 |
]
|
| 115 |
|
| 116 |
data = {
|
| 117 |
-
# FIX 3: Changed to the working model that resolved the 404 error in the console bot
|
| 118 |
"model": "meituan-longcat/LongCat-Flash-Chat-FP8",
|
| 119 |
"messages": messages,
|
| 120 |
"temperature": 0.2,
|
| 121 |
"max_tokens": 500
|
| 122 |
}
|
| 123 |
|
| 124 |
-
# FIX 2: Corrected API URL to the one that successfully connected
|
| 125 |
api_url = "https://llm.chutes.ai/v1/chat/completions"
|
| 126 |
|
| 127 |
try:
|
|
@@ -139,7 +143,7 @@ class TelegramHomeopathyBot:
|
|
| 139 |
error_message = error_data.get("error", {}).get("message", "No detailed error message.")
|
| 140 |
|
| 141 |
if response.status_code == 401:
|
| 142 |
-
logger.error("π¨ CRITICAL API ERROR (401 Unauthorized) π¨: The CHUTEAI_API_KEY is likely invalid or missing. Please check your .
|
| 143 |
|
| 144 |
logger.error(f"Chute.ai Error {response.status_code}: {error_message}")
|
| 145 |
return f"β I'm having technical difficulties. Please try again later. (Error: {response.status_code})"
|
|
@@ -149,11 +153,20 @@ class TelegramHomeopathyBot:
|
|
| 149 |
return f"β Connection error. Please try again. Error: {str(e)}"
|
| 150 |
|
| 151 |
# Create bot instance
|
| 152 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
|
| 154 |
-
# Telegram Bot Handlers
|
| 155 |
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 156 |
"""Send welcome message when the command /start is issued."""
|
|
|
|
|
|
|
|
|
|
|
|
|
| 157 |
user = update.effective_user
|
| 158 |
welcome_text = f"""
|
| 159 |
π Hello *{user.first_name}*! I'm your AI Homeopathy Doctor π€
|
|
@@ -187,6 +200,10 @@ Type your symptoms below to begin...
|
|
| 187 |
|
| 188 |
async def handle_symptoms(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 189 |
"""Handle user's symptom description and continue the diagnosis."""
|
|
|
|
|
|
|
|
|
|
|
|
|
| 190 |
user_id = update.effective_user.id
|
| 191 |
user_input = update.message.text
|
| 192 |
|
|
@@ -261,8 +278,6 @@ async def handle_quick_actions(update: Update, context: ContextTypes.DEFAULT_TYP
|
|
| 261 |
user_input = update.message.text
|
| 262 |
|
| 263 |
if user_input in ["π Describe more symptoms or answer questions", "Reset please"]:
|
| 264 |
-
# If the bot has prescribed a remedy, the user might be ready to start fresh,
|
| 265 |
-
# so this is a good opportunity to offer the reset.
|
| 266 |
if len(homeopathy_bot.get_user_session(update.effective_user.id)['chat_history']) >= 4: # If 2 turns have passed
|
| 267 |
await update.message.reply_text("Please provide any additional details or clarify the Doctor's previous questions...")
|
| 268 |
else:
|
|
@@ -334,34 +349,48 @@ async def error_handler(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
|
| 334 |
|
| 335 |
def check_dependencies():
|
| 336 |
"""Checks for required environment variables and the vector database."""
|
| 337 |
-
if not os.getenv("TELEGRAM_BOT_TOKEN"):
|
| 338 |
-
print("β TELEGRAM_BOT_TOKEN not found in .env file. Please set it to run the bot.")
|
| 339 |
-
return False
|
| 340 |
|
| 341 |
if not os.path.exists("./vector_db"):
|
| 342 |
-
print("β Vector database not found. Please
|
| 343 |
return False
|
| 344 |
|
| 345 |
-
# FIX 5: Changed dependency check to look for CHUTEAI_API_KEY
|
| 346 |
if not os.getenv("CHUTEAI_API_KEY"):
|
| 347 |
-
print("β CHUTEAI_API_KEY not found in .
|
| 348 |
-
return
|
| 349 |
|
| 350 |
return True
|
| 351 |
|
| 352 |
def main():
|
| 353 |
"""Start the bot."""
|
| 354 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 355 |
if not check_dependencies():
|
| 356 |
return
|
| 357 |
|
| 358 |
print("π Starting Telegram Homeopathy Bot...")
|
| 359 |
|
| 360 |
-
#
|
| 361 |
-
|
|
|
|
|
|
|
|
|
|
| 362 |
|
| 363 |
# Create Application
|
| 364 |
-
application =
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 365 |
|
| 366 |
# Add conversation handler
|
| 367 |
conv_handler = ConversationHandler(
|
|
|
|
| 5 |
from telegram import Update, ReplyKeyboardMarkup, ReplyKeyboardRemove
|
| 6 |
import datetime
|
| 7 |
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes, ConversationHandler
|
| 8 |
+
# NEW IMPORT: Necessary to explicitly configure the request object
|
| 9 |
+
from telegram.request import HTTPXRequest
|
| 10 |
import logging
|
| 11 |
|
| 12 |
+
# Using the dedicated packages as recommended by LangChain warnings
|
| 13 |
+
from langchain_huggingface import HuggingFaceEmbeddings
|
| 14 |
+
from langchain_community.vectorstores import Chroma # Chroma is still in community
|
| 15 |
|
| 16 |
# Load environment variables
|
| 17 |
+
# NOTE: load_dotenv() is mainly for local development. In deployment,
|
| 18 |
+
# environment variables are set by the hosting platform (Hugging Face Secrets).
|
| 19 |
load_dotenv()
|
| 20 |
|
| 21 |
# Enable logging
|
|
|
|
| 34 |
self.logs_dir = "UserChatLogs"
|
| 35 |
os.makedirs(self.logs_dir, exist_ok=True)
|
| 36 |
|
| 37 |
+
# Switched to a standard, reliable embedding model.
|
| 38 |
+
TINY_EMBEDDING_MODEL = "sentence-transformers/all-MiniLM-L6-v2"
|
| 39 |
+
|
| 40 |
# Initialize embeddings and vector store
|
| 41 |
self.embeddings = HuggingFaceEmbeddings(
|
| 42 |
+
model_name=TINY_EMBEDDING_MODEL,
|
| 43 |
+
# Explicitly set device to 'cpu' for memory constrained environments
|
| 44 |
+
model_kwargs={'device': 'cpu'}
|
| 45 |
)
|
| 46 |
self.vector_store = Chroma(
|
| 47 |
persist_directory="./vector_db",
|
|
|
|
| 52 |
# Store user sessions: includes chat_history
|
| 53 |
self.user_sessions = {}
|
| 54 |
|
|
|
|
| 55 |
def log_chat(self, user_id: int, username: str, message: str, is_bot: bool = False):
|
| 56 |
"""Log user/bot messages to individual files"""
|
| 57 |
try:
|
|
|
|
| 70 |
self.user_sessions[user_id] = {
|
| 71 |
'chat_history': [],
|
| 72 |
'consultation_count': 0,
|
| 73 |
+
'last_query': None
|
| 74 |
}
|
| 75 |
return self.user_sessions[user_id]
|
| 76 |
|
|
|
|
| 79 |
Retrieve relevant context from the vector database using the latest query
|
| 80 |
and the accumulated user history for better RAG results.
|
| 81 |
"""
|
|
|
|
| 82 |
user_history = [msg['content'] for msg in history if msg['role'] == 'user']
|
| 83 |
history_summary = " ".join(user_history)
|
| 84 |
|
|
|
|
| 85 |
composite_query = f"Patient's case summary: {history_summary} {query}" if history_summary else query
|
| 86 |
|
| 87 |
docs = self.retriever.invoke(composite_query)
|
|
|
|
| 120 |
]
|
| 121 |
|
| 122 |
data = {
|
|
|
|
| 123 |
"model": "meituan-longcat/LongCat-Flash-Chat-FP8",
|
| 124 |
"messages": messages,
|
| 125 |
"temperature": 0.2,
|
| 126 |
"max_tokens": 500
|
| 127 |
}
|
| 128 |
|
|
|
|
| 129 |
api_url = "https://llm.chutes.ai/v1/chat/completions"
|
| 130 |
|
| 131 |
try:
|
|
|
|
| 143 |
error_message = error_data.get("error", {}).get("message", "No detailed error message.")
|
| 144 |
|
| 145 |
if response.status_code == 401:
|
| 146 |
+
logger.error("π¨ CRITICAL API ERROR (401 Unauthorized) π¨: The CHUTEAI_API_KEY is likely invalid or missing. Please check your setup.")
|
| 147 |
|
| 148 |
logger.error(f"Chute.ai Error {response.status_code}: {error_message}")
|
| 149 |
return f"β I'm having technical difficulties. Please try again later. (Error: {response.status_code})"
|
|
|
|
| 153 |
return f"β Connection error. Please try again. Error: {str(e)}"
|
| 154 |
|
| 155 |
# Create bot instance
|
| 156 |
+
# We wrap the initialization in a try/except block to catch memory-related failures early
|
| 157 |
+
try:
|
| 158 |
+
homeopathy_bot = TelegramHomeopathyBot()
|
| 159 |
+
except Exception as e:
|
| 160 |
+
logger.error(f"Failed to initialize TelegramHomeopathyBot (likely due to memory): {e}")
|
| 161 |
+
homeopathy_bot = None
|
| 162 |
|
| 163 |
+
# Telegram Bot Handlers (start, handle_symptoms, etc. functions remain the same)
|
| 164 |
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 165 |
"""Send welcome message when the command /start is issued."""
|
| 166 |
+
if not homeopathy_bot:
|
| 167 |
+
await update.message.reply_text("β Initialization Error: The AI service failed to start due to resource constraints. Please check the logs.")
|
| 168 |
+
return ConversationHandler.END
|
| 169 |
+
|
| 170 |
user = update.effective_user
|
| 171 |
welcome_text = f"""
|
| 172 |
π Hello *{user.first_name}*! I'm your AI Homeopathy Doctor π€
|
|
|
|
| 200 |
|
| 201 |
async def handle_symptoms(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 202 |
"""Handle user's symptom description and continue the diagnosis."""
|
| 203 |
+
if not homeopathy_bot:
|
| 204 |
+
await update.message.reply_text("β Service is unavailable due to an earlier initialization failure. Please try later.")
|
| 205 |
+
return ConversationHandler.END
|
| 206 |
+
|
| 207 |
user_id = update.effective_user.id
|
| 208 |
user_input = update.message.text
|
| 209 |
|
|
|
|
| 278 |
user_input = update.message.text
|
| 279 |
|
| 280 |
if user_input in ["π Describe more symptoms or answer questions", "Reset please"]:
|
|
|
|
|
|
|
| 281 |
if len(homeopathy_bot.get_user_session(update.effective_user.id)['chat_history']) >= 4: # If 2 turns have passed
|
| 282 |
await update.message.reply_text("Please provide any additional details or clarify the Doctor's previous questions...")
|
| 283 |
else:
|
|
|
|
| 349 |
|
| 350 |
def check_dependencies():
|
| 351 |
"""Checks for required environment variables and the vector database."""
|
|
|
|
|
|
|
|
|
|
| 352 |
|
| 353 |
if not os.path.exists("./vector_db"):
|
| 354 |
+
print("β Vector database not found. Please ensure 'vector_db' folder is uploaded.")
|
| 355 |
return False
|
| 356 |
|
|
|
|
| 357 |
if not os.getenv("CHUTEAI_API_KEY"):
|
| 358 |
+
print("β CHUTEAI_API_KEY not found in environment. AI queries will fail.")
|
| 359 |
+
return True # Allow start, but AI will fail
|
| 360 |
|
| 361 |
return True
|
| 362 |
|
| 363 |
def main():
|
| 364 |
"""Start the bot."""
|
| 365 |
|
| 366 |
+
# π¨ CRITICAL CHECK: Ensure the token is available
|
| 367 |
+
TELEGRAM_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
|
| 368 |
+
if not TELEGRAM_TOKEN:
|
| 369 |
+
print("FATAL ERROR: TELEGRAM_BOT_TOKEN is missing from environment secrets. Cannot initialize the Telegram client.")
|
| 370 |
+
return
|
| 371 |
+
|
| 372 |
+
# NEW: Sanity check to confirm the token is read and has a valid length
|
| 373 |
+
if len(TELEGRAM_TOKEN) < 40:
|
| 374 |
+
print(f"WARNING: TELEGRAM_BOT_TOKEN has suspicious length ({len(TELEGRAM_TOKEN)}). Double-check the secret value.")
|
| 375 |
+
|
| 376 |
if not check_dependencies():
|
| 377 |
return
|
| 378 |
|
| 379 |
print("π Starting Telegram Homeopathy Bot...")
|
| 380 |
|
| 381 |
+
# NEW: Explicitly configure the request object to use the correct base URL
|
| 382 |
+
# This often bypasses environmental DNS resolution failures.
|
| 383 |
+
custom_request = HTTPXRequest(
|
| 384 |
+
base_url='https://api.telegram.org/bot'
|
| 385 |
+
)
|
| 386 |
|
| 387 |
# Create Application
|
| 388 |
+
application = (
|
| 389 |
+
Application.builder()
|
| 390 |
+
.token(TELEGRAM_TOKEN)
|
| 391 |
+
.request(custom_request) # Inject the custom request object
|
| 392 |
+
.build()
|
| 393 |
+
)
|
| 394 |
|
| 395 |
# Add conversation handler
|
| 396 |
conv_handler = ConversationHandler(
|