File size: 2,111 Bytes
07b3f15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import asyncio
import aiohttp
from telegram import Update
from telegram.ext import ApplicationBuilder, MessageHandler, ContextTypes, filters
import logging

BOT_TOKEN = ""
LLAMA_API_URL = "http://127.0.0.1:8080/completion"

logging.basicConfig(
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
)

async def get_llama_response(prompt: str) -> str:
    system_prompt = f"User: {prompt}\nAssistant:"
    payload = {
        "prompt": system_prompt,
        "max_tokens": 100,
        "temperature": 0.7,
        "stop": ["</s>", "User:"]
    }
    try:
        timeout = aiohttp.ClientTimeout(total=60)
        async with aiohttp.ClientSession(timeout=timeout) as session:
            async with session.post(LLAMA_API_URL, json=payload) as resp:
                if resp.status == 200:
                    data = await resp.json()
                    return data.get("content", "").strip() or "❔ مدل پاسخی نداد."
                else:
                    text = await resp.text()
                    logging.error(f"خطای مدل: {resp.status} - {text}")
                    return f"❌ خطا از مدل ({resp.status}):\n{text}"
    except asyncio.TimeoutError:
        return "⏱️ مدل دیر پاسخ داد."
    except aiohttp.ClientConnectionError:
        return "🔌 اتصال به مدل برقرار نشد."
    except Exception as e:
        logging.exception("خطای کلی:")
        return f"⚠️ خطای غیرمنتظره: {str(e)}"

async def handle_gemma(update: Update, context: ContextTypes.DEFAULT_TYPE):
    message = update.message
    if message and message.text and "/gemma" in message.text.lower():
        prompt = message.text.replace("/gemma", "").strip()
        await message.chat.send_action("typing")
        response = await get_llama_response(prompt)
        await message.reply_text(response)

def main():
    app = ApplicationBuilder().token(BOT_TOKEN).build()
    app.add_handler(MessageHandler(filters.TEXT & (~filters.COMMAND), handle_gemma))
    app.run_polling()

if __name__ == "__main__":
    main()