Spaces:
Sleeping
Sleeping
Upload streamlit_app.py
#1
by Sentic - opened
- streamlit_app.py +53 -0
streamlit_app.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import os
|
| 3 |
+
import google.generativeai as genai
|
| 4 |
+
|
| 5 |
+
# Initialize Gemini-Pro
|
| 6 |
+
genai.configure(api_key=os.getenv("GOOGLE_GEMINI_KEY"))
|
| 7 |
+
model = genai.GenerativeModel('gemini-pro')
|
| 8 |
+
|
| 9 |
+
def role_to_streamlit(role):
|
| 10 |
+
if role == "model":
|
| 11 |
+
return "assistant"
|
| 12 |
+
else:
|
| 13 |
+
return role
|
| 14 |
+
|
| 15 |
+
# Function to convert chat history to text
|
| 16 |
+
def convert_chat_to_text(chat_history):
|
| 17 |
+
text = ""
|
| 18 |
+
for message in chat_history:
|
| 19 |
+
text += f"{role_to_streamlit(message.role)}: {message.parts[0].text}\n"
|
| 20 |
+
return text
|
| 21 |
+
|
| 22 |
+
# Add a Gemini Chat history object to Streamlit session state
|
| 23 |
+
if "chat" not in st.session_state:
|
| 24 |
+
st.session_state.chat = model.start_chat(history=[])
|
| 25 |
+
|
| 26 |
+
st.title("Gemini-Pro CBot#79!")
|
| 27 |
+
|
| 28 |
+
# Display chat messages from history above the current input box
|
| 29 |
+
for message in st.session_state.chat.history:
|
| 30 |
+
with st.chat_message(role_to_streamlit(message.role)):
|
| 31 |
+
st.markdown(message.parts[0].text)
|
| 32 |
+
|
| 33 |
+
# Accept user's next message, add to context, resubmit context to Gemini
|
| 34 |
+
if prompt := st.chat_input("I possess a well of knowledge. What would you like to know?"):
|
| 35 |
+
# Display user's last message
|
| 36 |
+
st.chat_message("user").markdown(prompt)
|
| 37 |
+
|
| 38 |
+
# Send user entry to Gemini and read the response
|
| 39 |
+
response = st.session_state.chat.send_message(prompt)
|
| 40 |
+
with st.chat_message("assistant"):
|
| 41 |
+
st.markdown(response.text)
|
| 42 |
+
|
| 43 |
+
# Add a button to download the chat history as a text file
|
| 44 |
+
if st.button("Download Chat History"):
|
| 45 |
+
chat_text = convert_chat_to_text(st.session_state.chat.history)
|
| 46 |
+
st.download_button(
|
| 47 |
+
label="Download Chat",
|
| 48 |
+
data=chat_text,
|
| 49 |
+
file_name="chat_history.txt",
|
| 50 |
+
key="download_button"
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
|