Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,4 +1,59 @@
|
|
1 |
import streamlit as st
|
|
|
|
|
2 |
|
3 |
-
|
4 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import streamlit as st
|
2 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
3 |
+
import torch
|
4 |
|
5 |
+
# Load the model and tokenizer
|
6 |
+
model_name = "Qwen/Qwen2.5-1.5B-Instruct"
|
7 |
+
model = AutoModelForCausalLM.from_pretrained(
|
8 |
+
model_name,
|
9 |
+
torch_dtype="auto",
|
10 |
+
device_map="auto"
|
11 |
+
)
|
12 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
13 |
+
|
14 |
+
# Initialize chat history
|
15 |
+
if "messages" not in st.session_state:
|
16 |
+
st.session_state.messages = [
|
17 |
+
{"role": "system", "content": "You are a helpful assistant."}
|
18 |
+
]
|
19 |
+
|
20 |
+
# Display chat messages from history on app rerun
|
21 |
+
for message in st.session_state.messages:
|
22 |
+
with st.chat_message(message["role"]):
|
23 |
+
st.markdown(message["content"])
|
24 |
+
|
25 |
+
# Accept user input
|
26 |
+
if prompt := st.chat_input("Ask me anything about data structures in LeetCode"):
|
27 |
+
# Add user message to chat history
|
28 |
+
st.session_state.messages.append({"role": "user", "content": prompt})
|
29 |
+
# Display user message in chat message container
|
30 |
+
with st.chat_message("user"):
|
31 |
+
st.markdown(prompt)
|
32 |
+
|
33 |
+
# Prepare the chat message for the model
|
34 |
+
messages = st.session_state.messages[-10:] # limit messages to last 10 for performance
|
35 |
+
text = tokenizer.apply_chat_template(
|
36 |
+
messages,
|
37 |
+
tokenize=False,
|
38 |
+
add_generation_prompt=True
|
39 |
+
)
|
40 |
+
model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
|
41 |
+
|
42 |
+
# Generate response from the model
|
43 |
+
generated_ids = model.generate(
|
44 |
+
**model_inputs,
|
45 |
+
max_new_tokens=512
|
46 |
+
)
|
47 |
+
generated_ids = [
|
48 |
+
output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
|
49 |
+
]
|
50 |
+
|
51 |
+
# Decode the response
|
52 |
+
response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
|
53 |
+
|
54 |
+
# Add bot response to chat history
|
55 |
+
st.session_state.messages.append({"role": "assistant", "content": response})
|
56 |
+
|
57 |
+
# Display bot response in chat message container
|
58 |
+
with st.chat_message("assistant"):
|
59 |
+
st.markdown(response)
|