TECHNOLOGIESTieInn Technologies

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_state resets.
  • Creating the model client on each rerun is slow; cache it with @st.cache_resource.
  • Secrets go in .streamlit/secrets.toml or 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 →

Questions

Open in Code Lab5 free questions
5 questions

    A chat screen with Streamlit

  1. Question 1easy

    What happens in a Streamlit app when the user sends a chat message?

  2. A chat screen with Streamlit

  3. 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"))
  4. A chat screen with Streamlit

  5. Question 3hard

    Write to_send(history, last) that keeps the last last messages, drops leading messages until the first is a user message, and renames role "assistant" to "model". Store to_send(history, 4) in result.

    Store your answer in result.

  6. A chat screen with Streamlit

  7. Question 4medium

    What does st.write_stream(generator) do?

  8. A chat screen with Streamlit

  9. Question 5medium

    You'll share your Streamlit demo publicly. Why should it call your API instead of Gemini directly?

5 more questions on this topic, with hints, and tests

Sign up free for 21 days of every question and test.