File size: 3,784 Bytes
d243245
a575108
 
03bb072
d243245
 
03bb072
d243245
03bb072
 
 
 
d243245
 
 
03bb072
d243245
 
 
 
 
 
 
 
 
 
 
 
 
 
03bb072
d243245
 
 
03bb072
d243245
786dd87
d243245
8b1e139
d243245
 
 
 
 
 
8b1e139
d243245
 
 
8b1e139
d243245
a575108
 
 
 
d243245
 
 
8b1e139
d243245
a575108
 
 
 
 
 
 
 
 
 
d243245
 
 
8b1e139
d243245
 
 
8b1e139
d243245
 
 
 
8b1e139
d243245
 
a575108
 
 
 
 
 
 
8b1e139
a575108
 
d243245
 
 
 
786dd87
 
8b1e139
a575108
 
8b1e139
a575108
d243245
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
import gradio as gr
import requests
import json

HF_API_KEY = os.getenv("HF_API_KEY")
HF_API_URL = "https://api-inference.huggingface.co/models/Qwen/Qwen2.5-Coder-32B-Instruct/v1/chat/completions"

def query(payload):
    headers = {
        "Authorization": f"Bearer {HF_API_KEY}",
        "Content-Type": "application/json",
    }
    response = requests.post(HF_API_URL, headers=headers, data=json.dumps(payload))
    response.raise_for_status()
    return response.json()

def chat(user_message):
    payload = {
        "model": "Qwen/Qwen2.5-Coder-32B-Instruct",
        "messages": [
            {"role": "user", "content": user_message}
        ],
        "temperature": 0.5,
        "max_tokens": 2048,
        "top_p": 0.7,
        "stream": False,
    }
    response = query(payload)
    reply = response.get("generated_text", "")
    return reply

iface = gr.Interface(fn=chat, inputs="text", outputs="text")
iface.launch()
```

### Адаптация вашего кода бота

Теперь адаптируем ваш код бота, используя структуру из примера:

```python
import os
from telegram import Update
from telegram.ext import ApplicationBuilder, CommandHandler, MessageHandler, filters, ContextTypes
import requests
import json

# Получаем ключи из переменных окружения
HF_API_KEY = os.getenv("HF_API_KEY")
HF_API_URL = "https://api-inference.huggingface.co/models/Qwen/Qwen2.5-Coder-32B-Instruct/v1/chat/completions"

def query(payload):
    headers = {
        "Authorization": f"Bearer {HF_API_KEY}",
        "Content-Type": "application/json",
    }
    response = requests.post(HF_API_URL, headers=headers, data=json.dumps(payload))
    response.raise_for_status()
    return response.json()

def chat(user_message):
    payload = {
        "model": "Qwen/Qwen2.5-Coder-32B-Instruct",
        "messages": [
            {"role": "user", "content": user_message}
        ],
        "temperature": 0.5,
        "max_tokens": 2048,
        "top_p": 0.7,
        "stream": False,
    }
    response = query(payload)
    reply = response.get("generated_text", "")
    return reply

# Обработчик стартовой команды
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text("Привет! Я бот, который отвечает на ваши вопросы. Напишите мне что-нибудь.")

# Обработчик сообщений
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
    user_message = update.message.text
    await update.message.reply_text("Думаю...")

    try:
        reply = chat(user_message)
        await update.message.reply_text(reply if reply else "К сожалению, я не смог ничего придумать.")
    except requests.exceptions.RequestException as e:
        await update.message.reply_text(f"Сетевая ошибка: {e}")
    except json.JSONDecodeError as e:
        await update.message.reply_text(f"Ошибка декодирования JSON: {e}")
    except Exception as e:
        await update.message.reply_text(f"Неизвестная ошибка: {e}")

# Запуск бота
if __name__ == "__main__":
    TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")

    if not TOKEN:
        raise ValueError("Токен бота не установлен. Пожалуйста, установите переменную окружения TELEGRAM_BOT_TOKEN.")

    app = ApplicationBuilder().token(TOKEN).build()

    app.add_handler(CommandHandler("start", start))
    app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))

    print("Бот запущен!")
    app.run_polling()