Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 2 |
+
import transformers
|
| 3 |
+
import torch
|
| 4 |
+
import streamlit as st
|
| 5 |
+
|
| 6 |
+
model_id = "google/gemma-1.1-2b-it"
|
| 7 |
+
dtype = torch.bfloat16
|
| 8 |
+
|
| 9 |
+
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
| 10 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 11 |
+
model_id,
|
| 12 |
+
device_map="cpu",
|
| 13 |
+
torch_dtype=dtype,
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
st.title("💬 Chatbot")
|
| 22 |
+
st.caption("🚀 A streamlit chatbot powered by Microsoft Phi-3-mini")
|
| 23 |
+
|
| 24 |
+
# Initialize chat history
|
| 25 |
+
if 'messages' not in st.session_state:
|
| 26 |
+
st.session_state['messages'] = [] #[{"role": "assistant", "content": "How can I help you?"}]
|
| 27 |
+
|
| 28 |
+
# Display chat messages from history on app rerun
|
| 29 |
+
for messasge in st.session_state.messages:
|
| 30 |
+
st.chat_message(messasge["role"]).write(messasge["content"])
|
| 31 |
+
|
| 32 |
+
# React to user input
|
| 33 |
+
if prompt := st.chat_input():
|
| 34 |
+
|
| 35 |
+
# Display user message in chat message container
|
| 36 |
+
st.chat_message("user").write(prompt)
|
| 37 |
+
# Add user message to chat history
|
| 38 |
+
st.session_state.messages.append({"role": "user", "content": prompt})
|
| 39 |
+
|
| 40 |
+
messages=st.session_state.messages
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 44 |
+
|
| 45 |
+
##Get response to the message using client
|
| 46 |
+
inputs = tokenizer.encode(text, add_special_tokens=False, return_tensors="pt")
|
| 47 |
+
outputs = model.generate(input_ids=inputs.to(model.device), max_new_tokens=150)
|
| 48 |
+
|
| 49 |
+
msg = outputs #output[0]['generated_text']
|
| 50 |
+
|
| 51 |
+
# Display assistant response in chat message container
|
| 52 |
+
st.chat_message("assistant").write(msg)
|
| 53 |
+
|
| 54 |
+
# Add assistant response to chat history
|
| 55 |
+
st.session_state.messages.append({"role": "assistant", "content": msg})
|