Перепиши следующий код так чтобы вывод от модели был красивым(в телеграмме). Вот код, я…
- User
Перепиши следующий код так чтобы вывод от модели был красивым(в телеграмме). Вот код, я хочу чтобы вывод был правильным, по типу выделялось жирным шрифтом заголовки которые выделяет модель, переносы строк и тд: import requests import logging from gradio_client import Client
API_TOKEN = '7921795346:AAEbI6pfqB-FBniI7nhkaZMnF_ucQas4Vc0' # Замените на ваш новый токен BASE_URL = f'https://api.telegram.org/bot{API_TOKEN}/'
logging.basicConfig(level=logging.INFO)
def send_message(chat_id, text): url = BASE_URL + 'sendMessage' payload = { 'chat_id': chat_id, 'text': text, 'parse_mode': 'Markdown' } try: response = requests.post(url, json=payload) if response.status_code != 200: logging.error(f"Failed to send message: {response.text}") except Exception as e: logging.error(f"Error sending message: {e}")
def get_updates(offset=None): url = BASE_URL + 'getUpdates' params = {'timeout': 100, 'offset': offset} try: response = requests.get(url, params=params) if response.status_code != 200: logging.error(f"Failed to get updates: {response.text}") return {} return response.json() except Exception as e: logging.error(f"Error getting updates: {e}") return {}
def handle_updates(updates, client): for update in updates.get('result', []): try: message = update.get('message') if not message: continue
chat_id = message['chat']['id'] text = message.get('text') if text: prompt = text result = client.predict( inputs=prompt, top_p=1, temperature=1, chat_counter=0, chatbot=[], api_name="/predict_1" ) # Проверяем, что result — кортеж и первый элемент — список строк if isinstance(result, tuple) and len(result) > 0 and isinstance(result[0], list): responses = result[0] else: responses = [str(result)] # Исправляем кодировку: предположительно, строки были закодированы в utf-8, но интерпретированы как latin1 corrected_responses = [] for res in responses: if isinstance(res, str): try: # Перекодируем из latin1 обратно в bytes, затем декодируем как utf-8 corrected_text = res.encode('latin1').decode('utf-8') corrected_responses.append(corrected_text) except UnicodeEncodeError: # Если перекодировка не удалась, используем оригинальный текст corrected_responses.append(res) else: corrected_responses.append(str(res)) # Убираем скобочки и кавычки из ответов response_text = "\n".join(corrected_responses).replace('(', '').replace(')', '').replace("'", "") # Убираем вопрос пользователя из ответа if response_text.startswith(prompt): response_text = response_text[len(prompt):].strip() send_message(chat_id, response_text) else: # Обработка сообщений без текста (например, фото, стикеры и т.д.) send_message(chat_id, "Извините, я могу отвечать только на текстовые сообщения.") except Exception as e: logging.error(f"Error handling update {update}: {e}") send_message(chat_id, "Произошла ошибка при обработке вашего запроса.") - Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.