Certainly! The issue arises because the bot is sending the entire conversation history…
- User
Certainly! The issue arises because the bot is sending the entire conversation history and additional data instead of just the assistant's latest reply. To fix this, you need to extract only the assistant's most recent message from the result returned by the Gradio client.
Here's the corrected code without comments:
import telebot from gradio_client import Client import os import logging
TELEGRAM_BOT_TOKEN = '7280791264:AAFZL8tY_ySd4ueDa3b0e1QO8nHgCRkWzBA'
logging.basicConfig(level=logging.INFO)
bot = telebot.TeleBot(TELEGRAM_BOT_TOKEN)
client = Client('https://yuntian-deng-o1.hf.space/')
@bot.message_handler(func=lambda message: True) def handle_message(message): user_input = message.text chat_id = message.chat.id username = message.from_user.username or message.from_user.first_name
logging.info(f"Received message from {username}: {user_input}")
bot.send_chat_action(chat_id, 'typing')
try: result = client.predict( user_input, api_name="/predict" )
output_text = result[0][-1][1]
if len(output_text) < 4000: bot.send_message(chat_id, output_text) logging.info(f"Sent message to {username}: {output_text}") else: filename = 'output.txt' with open(filename, 'w', encoding='utf-8') as f: f.write(output_text)
with open(filename, 'rb') as f: bot.send_document(chat_id, f) logging.info(f"Sent document to {username}: {filename}")
os.remove(filename)
except Exception as e: error_message = f"An error occurred: {e}" bot.send_message(chat_id, error_message) logging.error(f"Error occurred for {username}: {e}")
if name == "main": logging.info("Starting the bot...") bot.polling() Explanation of the Fix:
-
Extracting the Assistant's Latest Reply: The result returned by client.predict contains the conversation history and other data. To get only the assistant's latest reply, use output_text = result[0][-1][1]. Here's what this indexing does: - result[0] accesses the conversation history list. - result[0][-1] gets the last exchange (a list of [user_message, assistant_reply]). - result[0][-1][1] retrieves the assistant's reply from that exchange.
-
Removed Comments: As per your request, all comments have been removed from the code to make it cleaner.
Now, when you run this code, your bot should respond with only the AI's latest message, fixing the issue you encountered.
-
- Assistant
It looks like you've provided corrected code and an explanation related to extracting the assistant's latest reply from a Gradio client in a Telegram bot. Could you please clarify how I can assist you? Are you encountering any issues with this code, or do you have questions about how it works?