AI Tools7 min read

Build AI Apps with Streamlit: Chat, Caching and Deploys

Build a streaming LLM chat app in Streamlit with chat elements, session state and secrets, cache models correctly, and deploy it to Community Cloud.

By AI Agents DirectoryLast checked
White humanoid robot holding out its open hand

Streamlit turns a plain Python script into a web app, which makes it a common choice for putting a language model in front of users without writing any frontend code. This guide builds one working chat app, then covers the three things that decide whether it holds up: how Streamlit reruns your script, how to cache models and data, and how to ship it to Streamlit Community Cloud with your API key kept out of Git. Everything here is checked against the Streamlit documentation and the official GitHub repository.

Streamlit at a glance

What it isOpen-source Python library for data apps, dashboards and chat apps
LicenceApache-2.0
Installpip install streamlit, then streamlit hello to test
Run an appstreamlit run app.py starts a local server and opens a browser tab
Chat elementsst.chat_message, st.chat_input, st.write_stream
HostingStreamlit Community Cloud, Snowflake, or your own server or container

How Streamlit runs your code

The one idea to understand before building anything: by default, Streamlit executes your whole script again, top to bottom, every time a user touches a widget. Saving the source file also triggers a rerun prompt, which gives you a fast edit-and-refresh loop while developing.

That model is simple, but it has two side effects for AI apps. Ordinary variables reset on every rerun, so a chat history kept in a normal list disappears after each message. And anything slow, such as loading a model or calling an API, runs again unless you cache it.

Streamlit gives you a tool for each problem:

  • Session State (st.session_state) is a dictionary-like store that keeps values across reruns for one browser tab. Each tab gets its own session.
  • Caching decorators (st.cache_data and st.cache_resource) store the results of slow functions so they run once.

The chat elements

CommandWhat it does
st.chat_message(name)Returns a container for one message. Pass "user" or "assistant" to get preset avatars and styling. Any Streamlit element can go inside it.
st.chat_input(placeholder)Shows a message box pinned to the bottom of the page. Returns the text the user sent, or None if nothing was sent on this run.
st.write_stream(stream)Writes a generator or stream to the page as it arrives, then returns the complete text. It understands OpenAI streams (Chat Completions and Responses APIs) and LangChain streams directly.

st.chat_input can also accept files or audio recordings, in which case it returns a ChatInputValue object instead of a string. Its submit_mode="disable" option greys out the box while a response is streaming, so a user can’t fire off a second prompt mid-reply.

Build a streaming chat app

This follows the pattern in Streamlit’s official tutorial, Build a basic LLM chat app, which uses the OpenAI Python library. The same structure works with any provider; only the API call changes.

1. Install the dependencies.

pip install streamlit openai

2. Store the key in a secrets file. Create .streamlit/secrets.toml next to your app and add it to .gitignore straight away:

# .streamlit/secrets.toml
OPENAI_API_KEY = "your-api-key"
OPENAI_MODEL = "a-chat-model-your-account-can-use"

Putting the model name in secrets as well means you can switch models later without editing code.

3. Write the app as app.py:

import streamlit as st
from openai import OpenAI

st.title("LLM chat")

client = OpenAI(api_key=st.secrets["OPENAI_API_KEY"])

# Create the history once; later reruns reuse it
if "messages" not in st.session_state:
    st.session_state.messages = []

# Redraw the conversation on every rerun
for msg in st.session_state.messages:
    with st.chat_message(msg["role"]):
        st.markdown(msg["content"])

if prompt := st.chat_input("Ask something", submit_mode="disable"):
    st.session_state.messages.append({"role": "user", "content": prompt})
    with st.chat_message("user"):
        st.markdown(prompt)

    with st.chat_message("assistant"):
        stream = client.chat.completions.create(
            model=st.secrets["OPENAI_MODEL"],
            messages=st.session_state.messages,
            stream=True,
        )
        reply = st.write_stream(stream)
    st.session_state.messages.append({"role": "assistant", "content": reply})

4. Run it with streamlit run app.py.

Here is what happens when a user sends a message. The script reruns from the top. The if guard leaves the existing history alone, and the loop draws every earlier message. st.chat_input now returns the new prompt, so the walrus operator (:=) assigns it and the block runs: the prompt is saved and displayed, the full history goes to the model with stream=True, and st.write_stream shows the reply token by token. Because it returns the finished text, you can append the reply to the history in one line.

If you use a provider whose stream st.write_stream can’t parse, wrap it in a small generator that yields plain text:

def text_only(raw_stream):
    for chunk in raw_stream:
        yield extract_text(chunk)  # your provider-specific parsing

reply = st.write_stream(text_only(raw_stream))

If you are comparing hosted model APIs for the backend, our OpenAI API entry and the LLM infrastructure hub list options.

Caching models and data

Streamlit has two caching decorators, and picking the right one matters more for AI apps than for most.

st.cache_datast.cache_resource
Use forSerializable results: DataFrames, arrays, strings, API responses, query resultsUnserializable shared objects: ML models, database connections
What callers getA fresh copy each call, so mutations can’t leak between usersThe same object for every rerun and session
Main caveatReturn values are pickled, so only cache trusted dataThe cached object must be thread-safe

A local model is the textbook case for st.cache_resource. This comes from the Streamlit caching docs and loads a Hugging Face pipeline once, when the app starts:

import streamlit as st
from transformers import pipeline

@st.cache_resource
def load_model():
    return pipeline("sentiment-analysis")

model = load_model()
query = st.text_input("Your query", value="I love Streamlit!")
if query:
    st.write(model(query)[0])

Two settings help on long-running apps. ttl expires cached values after a set number of seconds, which you should use for anything pulled from an API or database so results don’t go stale. max_entries caps the number of stored entries to limit memory. Function parameters must be hashable; prefix one with an underscore (_client) to leave it out of the cache key.

One trap in older tutorials: the original @st.cache decorator no longer exists. Streamlit added the two newer decorators in 1.18.0 and removed st.cache in 1.62.0, so code using it needs updating.

Deploying to Community Cloud

Streamlit Community Cloud builds your app from the files in its repository, and most apps are live within a few minutes.

  1. List your dependencies. Put a requirements.txt in the repository root or beside your entrypoint file. Streamlit itself is preinstalled, so you only need to add it if you want to pin a version. Leave out standard-library modules such as json or random. For the chat app above, a single line reading openai is enough. If you need system packages, list them one per line in packages.txt; the platform runs on Debian Linux.
  2. Keep secrets out of the repository. Never commit secrets.toml. During deployment, open Advanced settings and paste the file’s contents into the Secrets field. You can change them later from the app’s settings. Your code keeps reading st.secrets unchanged.
  3. Match Python versions. Develop on the same Python version you deploy with.
  4. Deploy. In your workspace, click Create app, follow the prompts to describe your app, then click Deploy.

Missing dependencies are the most common reason a build fails, so check requirements.txt against every import first. To deploy somewhere else, the Streamlit docs cover other platforms; when running in Docker, set a WORKDIR because Streamlit won’t run an app from a Linux root directory.

Limits to plan for

  • Session State is temporary. A brief network drop reconnects to the same session (the server keeps it for 120 seconds by default), but reloading or closing the tab, or a server crash, loses everything. Store conversations elsewhere if they matter.
  • Every rerun repeats the work. Anything slow that isn’t cached runs again on each interaction.
  • Shared cache means shared state. An object from st.cache_resource is visible to all users, so don’t store per-user data in it or mutate it carelessly.
  • Accessing a missing secret raises an error: a FileNotFoundError with no secrets file, or a KeyError for an unknown key.

For other front ends for chat models, browse the chat interfaces and developer tools hubs.

#Streamlit#Python#LLM apps#Chatbots#Deployment
AI

Written by AI Agents Directory

Editorial team

Facts in this guide are checked against official documentation and repositories, which are linked in the article.