Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import time
|
| 3 |
+
import uuid
|
| 4 |
+
import requests
|
| 5 |
+
import os
|
| 6 |
+
import json
|
| 7 |
+
|
| 8 |
+
chat_url = os.environ['CHAT_URL']
|
| 9 |
+
# Streamed response emulator
|
| 10 |
+
def response_generator(user_input):
|
| 11 |
+
payload = json.dumps({
|
| 12 |
+
"user_query": user_input,
|
| 13 |
+
"thread_id": st.session_state.session_id
|
| 14 |
+
})
|
| 15 |
+
headers = {
|
| 16 |
+
'Content-Type': 'application/json'
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
response = requests.request("POST", chat_url, headers=headers, data=payload)
|
| 20 |
+
|
| 21 |
+
ai_response = response.json()['ai_response']
|
| 22 |
+
|
| 23 |
+
for character in ai_response:
|
| 24 |
+
yield character
|
| 25 |
+
time.sleep(0.004)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
st.title("Bookstore-Assistant")
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
if "session_id" not in st.session_state:
|
| 32 |
+
st.session_state.session_id = str(uuid.uuid4())
|
| 33 |
+
|
| 34 |
+
# Initialize chat history
|
| 35 |
+
if "messages" not in st.session_state:
|
| 36 |
+
st.session_state.messages = []
|
| 37 |
+
|
| 38 |
+
# Display chat messages from history on app rerun
|
| 39 |
+
for message in st.session_state.messages:
|
| 40 |
+
with st.chat_message(message["role"]):
|
| 41 |
+
st.markdown(message["content"])
|
| 42 |
+
|
| 43 |
+
# Accept user input
|
| 44 |
+
if user_input := st.chat_input("What is up?"):
|
| 45 |
+
# Add user message to chat history
|
| 46 |
+
st.session_state.messages.append({"role": "user", "content": user_input.strip()})
|
| 47 |
+
# Display user message in chat message container
|
| 48 |
+
with st.chat_message("user"):
|
| 49 |
+
st.markdown(user_input)
|
| 50 |
+
|
| 51 |
+
# Display assistant response in chat message container
|
| 52 |
+
with st.chat_message("assistant"):
|
| 53 |
+
response = st.write_stream(response_generator(user_input.strip()))
|
| 54 |
+
# Add assistant response to chat history
|
| 55 |
+
st.session_state.messages.append({"role": "assistant", "content": response})
|