Search Tutorials
--Ads--Building a RAG Web Interface with Streamlit and Gradio
Give your RAG pipeline a chat web interface with Streamlit or Gradio, including sources and streaming.
A RAG pipeline becomes useful to colleagues once it has a web interface. Two Python libraries make this a matter of minutes: Streamlit, for small apps with layout and state, and Gradio, whose ChatInterface creates a complete chat UI from one function. This lesson wraps the same RAG function in both, with streaming and source display.
What you will learn
- How to build a streaming chat interface with Streamlit's chat elements
- How to build the same interface with Gradio's ChatInterface
- How to show sources, keep history and cache heavy resources
- When to move to a separate frontend and API
Prerequisites
- A working retriever, for example from The Two Phases of RAG
pip install streamlit gradio anthropic numpy sentence-transformers
The shared RAG core
Both interfaces use the same module: a retriever and a generator that yields text pieces as they stream.
import json
from pathlib import Path
import anthropic
import numpy as np
from rag_helpers import embed
client = anthropic.Anthropic()
records = json.loads(Path("index/chunks.json").read_text(encoding="utf-8")) # from Module 1
vectors = np.load("index/vectors.npy")
def retrieve(question: str, k: int = 4) -> list[dict]:
scores = vectors @ embed(question, query=True)[0]
return [records[i] | {"score": float(scores[i])} for i in np.argsort(-scores)[:k]]
def stream_answer(question: str, history: list[dict], hits: list[dict]):
sources = "\n\n".join(f'<source id="{n}" file="{h["source"]}">\n{h["text"]}\n</source>'
for n, h in enumerate(hits, start=1))
messages = history[-6:] + [{"role": "user", "content": f"<sources>\n{sources}\n</sources>\n\n{question}"}]
with client.messages.stream(
model="claude-opus-5-5", max_tokens=1500, output_config={"effort": "low"},
system="Answer from the sources only and cite them like [1]. Say so if the answer is missing.",
messages=messages,
) as stream:
yield from stream.text_stream
History items are plain {"role", "content"} dictionaries holding the user's question and the assistant's answer, without the sources, to keep requests small.
Option 1: Streamlit
import streamlit as st
from rag_core import retrieve, stream_answer
st.set_page_config(page_title="Policy Assistant", page_icon="??")
st.title("?? Policy Assistant")
if "history" not in st.session_state:
st.session_state.history = [] # list of {"role", "content"}
for msg in st.session_state.history:
with st.chat_message(msg["role"]):
st.markdown(msg["content"])
if question := st.chat_input("Ask about company policies"):
with st.chat_message("user"):
st.markdown(question)
hits = retrieve(question)
with st.chat_message("assistant"):
answer = st.write_stream(stream_answer(question, st.session_state.history, hits))
with st.expander("Sources"):
for n, h in enumerate(hits, start=1):
st.markdown(f"**[{n}] {h['source']}** (score {h['score']:.2f})")
st.caption(h["text"][:400])
st.session_state.history += [{"role": "user", "content": question},
{"role": "assistant", "content": answer}]
streamlit run app_streamlit.py
Streamlit reruns the whole script on every interaction, so state lives in st.session_state. Load heavy objects (models, indexes) inside functions decorated with @st.cache_resource so they load once.
Option 2: Gradio
Gradio's ChatInterface calls your function with the new message and the history (a list of role/content messages). Yielding growing text streams the answer into the chat window:
import gradio as gr
from rag_core import retrieve, stream_answer
def as_text(content) -> str:
"""Gradio may store message content as text or as a list of content parts."""
if isinstance(content, str):
return content
return " ".join(part.get("text", "") for part in content if isinstance(part, dict))
def respond(message: str, history: list[dict]):
clean_history = [{"role": m["role"], "content": as_text(m["content"])} for m in history]
hits = retrieve(message)
text = ""
for piece in stream_answer(message, clean_history, hits):
text += piece
yield text # Gradio shows the growing answer
sources = "\n".join(f"[{n}] {h['source']}" for n, h in enumerate(hits, start=1))
yield f"{text}\n\n**Sources**\n{sources}"
demo = gr.ChatInterface(fn=respond, title="Policy Assistant",
examples=["Can I work from home on Fridays?", "What is the hotel limit?"])
if __name__ == "__main__":
demo.launch()
python app_gradio.py
Open the local URL printed in the terminal. demo.launch(share=True) creates a temporary public link; do not use it for confidential data.
Streamlit or Gradio?
| Streamlit | Gradio | |
|---|---|---|
| Fastest chat UI | A few lines with chat elements | One line with ChatInterface |
| Custom layouts, dashboards | Strong | Good (Blocks API) |
| Hugging Face Spaces hosting | Supported | Native |
| Best for | Internal tools with several views | Demos and model-centric apps |
Going to production
These frameworks are ideal for prototypes and internal tools. For public or large-scale applications, put the RAG pipeline behind an API (FastAPI) with authentication and rate limits, and build the frontend separately (React Frontend for RAG).
Common errors and troubleshooting
- The app reloads models on every message (Streamlit): wrap loading in
@st.cache_resource. - History disappears (Streamlit): store it in
st.session_state, not a normal variable. - Gradio history format surprises: print
historyonce; content can be a string or a list of parts, whichas_texthandles. - Port already in use: stop the old process, or pass another port (
streamlit run app.py --server.port 8502,demo.launch(server_port=7861)).
Key takeaways
- Keep the RAG logic in one module and put thin UIs on top.
- Streamlit:
st.chat_input,st.chat_message,st.write_streamandst.session_state. - Gradio:
gr.ChatInterface(fn)withfn(message, history)yielding partial text. - Always show sources; move to an API and dedicated frontend for production.
Frequently asked questions
Can several users use the app at once?
Yes, both support multiple sessions. For many concurrent users, run the model calls through an API service and scale it separately.
How do I add login?
Both frameworks offer authentication options; for company apps, put them behind your single sign-on proxy.
Practice exercises
- Add a sidebar in Streamlit that filters retrieval by department.
- Add thumbs-up and thumbs-down buttons and log feedback to a file (Feedback Loops).