Teacher_Vu_Bot / app.py
NV9523's picture
Update app.py
c5e49f7 verified
import streamlit as st
from transformers import AutoModelForCausalLM, AutoTokenizer, TextStreamer
from peft import PeftModel
import torch
# Định nghĩa tên mô hình gốc và adapter
BASE_MODEL_NAME = "unsloth/deepseek-r1-distill-llama-8b-unsloth-bnb-4bit"
ADAPTER_MODEL_PATH = "lora_model"
# Load mô hình gốc
base_model = AutoModelForCausalLM.from_pretrained(BASE_MODEL_NAME, torch_dtype=torch.float16, device_map="auto")
# Áp dụng adapter LoRA
model = PeftModel.from_pretrained(base_model, ADAPTER_MODEL_PATH)
tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL_NAME)
def generate_response(prompt):
"""Generate a response from the model."""
inputs = tokenizer(prompt, return_tensors="pt").to("cuda")
streamer = TextStreamer(tokenizer)
with torch.no_grad():
model.generate(**inputs, streamer=streamer, max_length=512)
return ""
# Streamlit UI
st.set_page_config(page_title="Chatbot", page_icon="🤖")
st.title("🤖 AI Chatbot")
# Initialize chat history if not exists
if "messages" not in st.session_state:
st.session_state.messages = []
# Display chat messages
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.markdown(message["content"])
# User input
user_input = st.chat_input("Nhập tin nhắn...")
if user_input:
# Append user message
st.session_state.messages.append({"role": "user", "content": user_input})
with st.chat_message("user"):
st.markdown(user_input)
# Generate response
with st.chat_message("assistant"):
response = generate_response(user_input)
st.markdown(response)
# Append assistant response
st.session_state.messages.append({"role": "assistant", "content": response})