Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from transformers import pipeline
|
3 |
+
import streamlit as st
|
4 |
+
|
5 |
+
model_id = "google/gemma-2-2b-it"
|
6 |
+
welcome_message = f"Hello there 👋! Is there anything I can help you with?"
|
7 |
+
|
8 |
+
@st.cache_resource
|
9 |
+
def model_setup(model_id):
|
10 |
+
pipe = pipeline(
|
11 |
+
"text-generation",
|
12 |
+
model=model_id,
|
13 |
+
torch_dtype=torch.bfloat16,
|
14 |
+
device_map="auto",
|
15 |
+
)
|
16 |
+
return pipe
|
17 |
+
|
18 |
+
def runModel(prompt):
|
19 |
+
messages = [
|
20 |
+
{"role": "system", "content": "You are a helpful assistant who politely answers user's questions."},
|
21 |
+
{"role": "user", "content": prompt},
|
22 |
+
]
|
23 |
+
outputs = pipe(
|
24 |
+
messages,
|
25 |
+
max_new_tokens=1024,
|
26 |
+
)
|
27 |
+
return outputs[0]["generated_text"][-1]["content"]
|
28 |
+
|
29 |
+
### load model
|
30 |
+
pipe = model_setup(model_id)
|
31 |
+
|
32 |
+
### initialize chat history
|
33 |
+
if "messages" not in st.session_state:
|
34 |
+
st.session_state.messages = []
|
35 |
+
st.session_state.messages.append({"role": "assistant", "content": welcome_message})
|
36 |
+
|
37 |
+
### display chat messages from history on app rerun
|
38 |
+
for message in st.session_state.messages:
|
39 |
+
with st.chat_message(message["role"]):
|
40 |
+
st.markdown(message["content"])
|
41 |
+
|
42 |
+
### accept user input
|
43 |
+
if prompt := st.chat_input("Type here!",key="question"):
|
44 |
+
|
45 |
+
# display user message in chat message container
|
46 |
+
with st.chat_message("user"):
|
47 |
+
st.markdown(prompt)
|
48 |
+
|
49 |
+
# add user message to chat history
|
50 |
+
st.session_state.messages.append({"role": "user", "content": prompt})
|
51 |
+
|
52 |
+
# run model
|
53 |
+
response = runModel(prompt)
|
54 |
+
|
55 |
+
# display assistant response in chat message container
|
56 |
+
with st.chat_message("assistant"):
|
57 |
+
st.markdown(response)
|
58 |
+
|
59 |
+
# add assistant response to chat history
|
60 |
+
st.session_state.messages.append({"role": "assistant", "content": response})
|