Spaces:
Sleeping
Sleeping
Create telegram_bot.py
Browse files- telegram_bot.py +145 -0
telegram_bot.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
from telegram import Update
|
| 3 |
+
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes
|
| 4 |
+
|
| 5 |
+
# Enable logging
|
| 6 |
+
logging.basicConfig(
|
| 7 |
+
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
| 8 |
+
level=logging.INFO
|
| 9 |
+
)
|
| 10 |
+
logger = logging.getLogger(__name__)
|
| 11 |
+
|
| 12 |
+
# Global agent instance (will be set by start_telegram_bot)
|
| 13 |
+
agent = None
|
| 14 |
+
|
| 15 |
+
# Command Handlers
|
| 16 |
+
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 17 |
+
"""Send a message when the command /start is issued."""
|
| 18 |
+
user = update.effective_user
|
| 19 |
+
await update.message.reply_text(
|
| 20 |
+
f'Hi {user.first_name}! I am your AI coding assistant. '
|
| 21 |
+
f'Ask me anything and I will solve it step by step!'
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 25 |
+
"""Send a message when the command /help is issued."""
|
| 26 |
+
help_text = """
|
| 27 |
+
I can help you with:
|
| 28 |
+
- Coding questions
|
| 29 |
+
- Web searches
|
| 30 |
+
- Mathematical calculations
|
| 31 |
+
- Data analysis
|
| 32 |
+
- And much more!
|
| 33 |
+
|
| 34 |
+
Just send me your question and I'll work on it!
|
| 35 |
+
"""
|
| 36 |
+
await update.message.reply_text(help_text)
|
| 37 |
+
|
| 38 |
+
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 39 |
+
"""Handle user messages and run agent"""
|
| 40 |
+
user_message = update.message.text
|
| 41 |
+
user_id = update.effective_user.id
|
| 42 |
+
|
| 43 |
+
logger.info(f"User {user_id} asked: {user_message}")
|
| 44 |
+
|
| 45 |
+
# Send "thinking" message
|
| 46 |
+
thinking_msg = await update.message.reply_text("🤔 Thinking...")
|
| 47 |
+
|
| 48 |
+
try:
|
| 49 |
+
# Run agent
|
| 50 |
+
result = agent.run(user_message, reset=False)
|
| 51 |
+
|
| 52 |
+
# Extract final answer
|
| 53 |
+
final_answer = str(result)
|
| 54 |
+
|
| 55 |
+
# Send result
|
| 56 |
+
await thinking_msg.edit_text(f"✅ Answer:\n\n{final_answer}")
|
| 57 |
+
|
| 58 |
+
except Exception as e:
|
| 59 |
+
logger.error(f"Error processing message: {e}")
|
| 60 |
+
await thinking_msg.edit_text(
|
| 61 |
+
f"❌ Sorry, I encountered an error: {str(e)}\n\n"
|
| 62 |
+
f"Please try rephrasing your question."
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
async def handle_streaming_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 66 |
+
"""Handle messages with streaming updates (advanced)"""
|
| 67 |
+
user_message = update.message.text
|
| 68 |
+
|
| 69 |
+
# Send initial message
|
| 70 |
+
status_msg = await update.message.reply_text("🤔 Starting...")
|
| 71 |
+
|
| 72 |
+
try:
|
| 73 |
+
step_count = 0
|
| 74 |
+
for step_log in agent.run(user_message, stream=True, reset=False):
|
| 75 |
+
step_count += 1
|
| 76 |
+
|
| 77 |
+
# Update status for each step
|
| 78 |
+
if hasattr(step_log, 'model_output'):
|
| 79 |
+
await status_msg.edit_text(
|
| 80 |
+
f"📝 Step {step_count}:\n{step_log.model_output[:500]}..."
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
# Send final answer
|
| 84 |
+
final_answer = str(step_log)
|
| 85 |
+
await status_msg.edit_text(f"✅ Final Answer:\n\n{final_answer}")
|
| 86 |
+
|
| 87 |
+
except Exception as e:
|
| 88 |
+
await status_msg.edit_text(f"❌ Error: {str(e)}")
|
| 89 |
+
|
| 90 |
+
def start_telegram_bot(shared_agent, token="8634464564:AAGL7FzFkMN-Uktf97NKtDs1RFPGxec-HFI"):
|
| 91 |
+
"""Start the Telegram bot with a shared agent instance
|
| 92 |
+
|
| 93 |
+
Args:
|
| 94 |
+
shared_agent: The CodeAgent instance to use for processing messages
|
| 95 |
+
token: Telegram bot token (default provided, can be overridden)
|
| 96 |
+
"""
|
| 97 |
+
global agent
|
| 98 |
+
agent = shared_agent
|
| 99 |
+
|
| 100 |
+
# Create application
|
| 101 |
+
application = Application.builder().token(token).build()
|
| 102 |
+
|
| 103 |
+
# Register handlers
|
| 104 |
+
application.add_handler(CommandHandler("start", start))
|
| 105 |
+
application.add_handler(CommandHandler("help", help_command))
|
| 106 |
+
application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
|
| 107 |
+
|
| 108 |
+
# Start bot
|
| 109 |
+
logger.info("Telegram Bot started!")
|
| 110 |
+
application.run_polling(allowed_updates=Update.ALL_TYPES)
|
| 111 |
+
|
| 112 |
+
def main():
|
| 113 |
+
"""Standalone entry point (for backward compatibility)"""
|
| 114 |
+
from smolagents import CodeAgent, LiteLLMModel
|
| 115 |
+
import yaml
|
| 116 |
+
from tools.final_answer import FinalAnswerTool
|
| 117 |
+
|
| 118 |
+
# Use local Ollama model
|
| 119 |
+
model = LiteLLMModel(
|
| 120 |
+
model_id="ollama/qwen2.5-coder:7b",
|
| 121 |
+
api_base="http://localhost:11434",
|
| 122 |
+
max_tokens=2096,
|
| 123 |
+
temperature=0.5
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
# Load prompts
|
| 127 |
+
with open("prompts.yaml", 'r') as stream:
|
| 128 |
+
prompt_templates = yaml.safe_load(stream)
|
| 129 |
+
|
| 130 |
+
# Initialize tools
|
| 131 |
+
final_answer = FinalAnswerTool()
|
| 132 |
+
|
| 133 |
+
# Create agent
|
| 134 |
+
standalone_agent = CodeAgent(
|
| 135 |
+
model=model,
|
| 136 |
+
tools=[final_answer],
|
| 137 |
+
max_steps=6,
|
| 138 |
+
verbosity_level=1,
|
| 139 |
+
prompt_templates=prompt_templates
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
start_telegram_bot(standalone_agent)
|
| 143 |
+
|
| 144 |
+
if __name__ == '__main__':
|
| 145 |
+
main()
|