import gradio as gr from transformers import AutoModelForCausalLM, AutoTokenizer import torch # Initialize the model and tokenizer model_name = "microsoft/DialoGPT-medium" model = AutoModelForCausalLM.from_pretrained(model_name) tokenizer = AutoTokenizer.from_pretrained(model_name) chat_history_ids = None def chat(message, history): global chat_history_ids message = str(message) history = str(history) # Encode the new user input, add the eos_token, and return a tensor in PyTorch new_user_input_ids = tokenizer.encode(message + tokenizer.eos_token, return_tensors='pt') # Append the new user input tokens to the chat history bot_input_ids = torch.cat([chat_history_ids, new_user_input_ids], dim=-1) if chat_history_ids is not None else new_user_input_ids # Generate a response while limiting the total chat history to 1000 tokens chat_history_ids = model.generate(bot_input_ids, max_length=1000, pad_token_id=tokenizer.eos_token_id) # Decode and return the bot's response response = tokenizer.decode(chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True) return response # Create and launch the Gradio interface iface = gr.ChatInterface( fn=chat, title="UrFriendly Chatbot", theme="soft", description="Chat with me!", examples=[ "Howdy!", "Tell me a joke.", "Explain quantum computing in simple terms.", "How are you?", "What is an exponent in mathematics?", "Does money buy happiness?" ] ) iface.launch()