import gradio as gr import torch from unsloth import FastLanguageModel from transformers import TextStreamer from unsloth.chat_templates import get_chat_template # Initialize the model max_seq_length = 2048 dtype = None load_in_4bit = True model, tokenizer = FastLanguageModel.from_pretrained( model_name="umair894/llama3", max_seq_length=max_seq_length, dtype=dtype, load_in_4bit=load_in_4bit, ) tokenizer = get_chat_template( tokenizer, chat_template="llama-3", mapping={"role": "from", "content": "value", "user": "human", "assistant": "gpt"}, map_eos_token=True, ) FastLanguageModel.for_inference(model) # Enable native 2x faster inference # VIKK introduction prompt vikk_intro = """Consider you self a legal assistant in USA and your name is VIKK. You are very knowledgeable about all aspects of the law... """ # Function to get chat response def get_response(message, history, system_message, max_tokens, temperature, top_p): messages = [{"role": "system", "content": system_message}] if system_message else [] if not history: history = [{"role": "assistant", "content": vikk_intro}] for msg in history: if msg[0]: messages.append({"role": "user", "content": msg[0]}) if msg[1]: messages.append({"role": "assistant", "content": msg[1]}) messages.append({"role": "user", "content": message}) formatted_messages = [{"from": "assistant", "value": vikk_intro}] for msg in messages[1:]: role = "human" if msg["role"] == "user" else "assistant" formatted_messages.append({"from": role, "value": msg["content"]}) inputs = tokenizer.apply_chat_template( formatted_messages, tokenize=True, add_generation_prompt=True, return_tensors="pt", ).to("cuda") text_streamer = TextStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True) output = "" for out in model.generate(input_ids=inputs["input_ids"], streamer=text_streamer, max_new_tokens=max_tokens, use_cache=True): output += out response = tokenizer.decode(output, skip_special_tokens=True).split(">>> Assistant: ")[-1].strip() return response # Gradio interface with gr.Blocks() as demo: gr.Markdown("# Chatbot Interface") with gr.Row(): with gr.Column(): system_message = gr.Textbox(value="You are a friendly Chatbot.", label="System message") max_tokens = gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens") temperature = gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature") top_p = gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)") with gr.Column(): chatbot = gr.Chatbot() user_input = gr.Textbox(label="You:") send_button = gr.Button("Send") def respond(message, history, system_message, max_tokens, temperature, top_p): response = get_response(message, history, system_message, max_tokens, temperature, top_p) history.append((message, response)) return history send_button.click(respond, [user_input, chatbot, system_message, max_tokens, temperature, top_p], chatbot) if __name__ == "__main__": demo.launch()