/
streamlit_app.py
57 lines (43 loc) · 1.73 KB
/
streamlit_app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import uuid
import application as chatbot_application
import streamlit as st
import burr.core
from burr.core.action import StreamingResultContainer
def render_chat_message(chat_item: dict):
content = chat_item["content"]
content_type = chat_item["type"]
role = chat_item["role"]
with st.chat_message(role):
if content_type == "image":
st.image(content)
elif content_type == "code":
st.code(content)
elif content_type == "text":
st.write(content)
def render_streaming_chat_message(stream: StreamingResultContainer):
with st.chat_message("assistant"):
st.write_stream(item["response"]["content"] for item in stream)
def initialize_app() -> burr.core.Application:
if "burr_app" not in st.session_state:
st.session_state.burr_app = chatbot_application.application(
app_id=f"chat_streaming:{str(uuid.uuid4())[0:6]}"
)
return st.session_state.burr_app
def main():
st.title("Streaming chatbot with Burr")
app = initialize_app()
prompt = st.chat_input("Ask me a question!", key="chat_input")
for chat_message in app.state.get("chat_history", []):
render_chat_message(chat_message)
if prompt:
render_chat_message({"role": "user", "content": prompt, "type": "text"})
with st.spinner(text="Waiting for response..."):
action, streaming_container = app.stream_result(
halt_after=chatbot_application.TERMINAL_ACTIONS, inputs={"prompt": prompt}
)
if action.streaming:
render_streaming_chat_message(streaming_container)
else:
render_chat_message(streaming_container.get()[0]["response"])
if __name__ == "__main__":
main()