A chat screen with Streamlit
Shipping AI Apps · 10 questions
Short notes
Key idea
Streamlit builds a web UI from a Python script. Its chat elements and session state give you a working chat screen in about 20 lines, which is good for demos and internal tools.
Syntax
import streamlit as st
st.title("Shop helper")
if "messages" not in st.session_state:
st.session_state.messages = []
for m in st.session_state.messages:
with st.chat_message(m["role"]):
st.write(m["content"])
if prompt := st.chat_input("Ask about your order"):
st.session_state.messages.append({"role": "user", "content": prompt})
with st.chat_message("user"):
st.write(prompt)
reply = get_reply(st.session_state.messages)
st.session_state.messages.append({"role": "assistant", "content": reply})
with st.chat_message("assistant"):
st.write(reply)
Run: streamlit run app.py.
Example
st.write_stream(stream_reply(...)) shows tokens as they arrive instead of waiting for the full answer.
Traps
- The whole script reruns on every interaction; anything not in
session_stateresets. - Creating the model client on each rerun is slow; cache it with
@st.cache_resource. - Secrets go in
.streamlit/secrets.tomlor env vars, never in the script. - Streamlit isn't built for heavy public traffic; use FastAPI + a frontend for that.
Want the full lesson with step-by-step examples, a project and a certificate? Shipping AI Apps course, ₹180 →
- Question 1easy
What happens in a Streamlit app when the user sends a chat message?
- Question 2medium
Each call to script() is one rerun. What does this print?
session_state = {} def script(msg): history = [] session_state.setdefault("history", []) history.append(msg) session_state["history"].append(msg) return len(history), len(session_state["history"]) script("a"); script("b") print(script("c")) - Question 3hard
Write
to_send(history, last)that keeps the lastlastmessages, drops leading messages until the first is a user message, and renames role "assistant" to "model". Storeto_send(history, 4)inresult.Store your answer in
result. - Question 4medium
What does st.write_stream(generator) do?
- Question 5medium
You'll share your Streamlit demo publicly. Why should it call your API instead of Gemini directly?
A chat screen with Streamlit
A chat screen with Streamlit
A chat screen with Streamlit
A chat screen with Streamlit
A chat screen with Streamlit
5 more questions on this topic, with hints, and tests
Sign up free for 21 days of every question and test.