import gradio as gr from transformers import AutoModelForCausalLM, AutoTokenizer import torch # Load the TinyLlama model model_name = "TinyLlama/TinyLlama-1.1B-Chat-v1.0" tokenizer = AutoTokenizer.from_pretrained(model_name) model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.float32) # Define chatbot function def chat_with_tinyllama(user_input): # Add context to the prompt to guide the model prompt = f"Question: {user_input}\nAnswer:" # Tokenize input inputs = tokenizer(prompt, return_tensors="pt").to("cpu") # Generate a response outputs = model.generate( **inputs, max_new_tokens=150, # Limit response length do_sample=True, temperature=0.7, top_p=0.9, repetition_penalty=1.2 ) # Decode the output response = tokenizer.decode(outputs[0], skip_special_tokens=True) # Extract the answer part (removing repeated prompt) if "Answer:" in response: response = response.split("Answer:")[1].strip() # Ensure the model gives an actual answer if response.strip().lower() == user_input.strip().lower(): return "I don't have an answer for that yet. Can you ask another way?" return response # Create Gradio UI chatbot = gr.Interface( fn=chat_with_tinyllama, inputs=gr.Textbox(lines=2, placeholder="Ask me a question..."), outputs="text", title="💬 TinyLlama Chatbot", description="A chatbot powered by TinyLlama." ) # Launch app chatbot.launch()