Here’s a detailed guide to creating a complete frontend chat UI for your RAG-powered AI agent, with both React and Streamlit options. You can choose whichever fits your style or stack best.
Creating a Complete Frontend Chat UI
Option 1️⃣ — React Frontend Chat UI
🔧 Setup
-
Make sure you have Node.js installed.
-
Create a new React app:
npx create-react-app rag-chatbot
cd rag-chatbot
npm start
📦 React Chat UI Code
Create a new component Chatbot.jsx:
import React, { useState, useEffect, useRef } from "react";
export default function Chatbot() {
const [messages, setMessages] = useState([
{ sender: "bot", text: "Hello! Ask me anything." },
]);
const [input, setInput] = useState("");
const bottomRef = useRef(null);
// Scroll to bottom on new messages
useEffect(() => {
bottomRef.current?.scrollIntoView({ behavior: "smooth" });
}, [messages]);
async function sendMessage() {
if (!input.trim()) return;
// Add user message
setMessages((msgs) => [...msgs, { sender: "user", text: input }]);
const userInput = input;
setInput("");
try {
const res = await fetch("http://localhost:8000/chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ user_id: "user123", question: userInput }),
});
const data = await res.json();
setMessages((msgs) => [...msgs, { sender: "bot", text: data.answer }]);
} catch (err) {
setMessages((msgs) => [
...msgs,
{ sender: "bot", text: "Error: Unable to connect to server." },
]);
}
}
return (
<div
style={{
maxWidth: 600,
margin: "30px auto",
border: "1px solid #ccc",
borderRadius: 8,
padding: 20,
fontFamily: "Arial, sans-serif",
height: "80vh",
display: "flex",
flexDirection: "column",
}}
>
<h2 style={{ textAlign: "center" }}>RAG AI Chatbot</h2>
<div
style={{
flexGrow: 1,
overflowY: "auto",
border: "1px solid #eee",
padding: 10,
marginBottom: 10,
borderRadius: 4,
backgroundColor: "#fafafa",
}}
>
{messages.map((msg, idx) => (
<div
key={idx}
style={{
textAlign: msg.sender === "user" ? "right" : "left",
marginBottom: 12,
}}
>
<div
style={{
display: "inline-block",
padding: "8px 14px",
borderRadius: 20,
backgroundColor: msg.sender === "user" ? "#0084ff" : "#e5e5ea",
color: msg.sender === "user" ? "white" : "black",
maxWidth: "80%",
wordBreak: "break-word",
}}
>
{msg.text}
</div>
</div>
))}
<div ref={bottomRef} />
</div>
<div style={{ display: "flex" }}>
<input
type="text"
placeholder="Type your message..."
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") sendMessage();
}}
style={{ flexGrow: 1, padding: "10px 15px", fontSize: 16 }}
/>
<button
onClick={sendMessage}
style={{
marginLeft: 8,
padding: "10px 20px",
backgroundColor: "#0084ff",
border: "none",
color: "white",
borderRadius: 4,
cursor: "pointer",
fontSize: 16,
}}
>
Send
</button>
</div>
</div>
);
}
🔗 Integrate with Backend
-
Make sure your backend (e.g., FastAPI at
http://localhost:8000) has a/chatPOST endpoint accepting:
{
"user_id": "string",
"question": "string"
}
and returns
{
"answer": "string"
}
🚀 Run React App
npm start
Open http://localhost:3000 and chat away!
Option 2️⃣ — Streamlit Frontend Chat UI
🔧 Setup
-
Install Streamlit:
pip install streamlit
-
Create a Python file, e.g.
streamlit_chat.py.
🐍 Streamlit Chat UI Code
import streamlit as st
import requests
st.set_page_config(page_title="RAG AI Chatbot", page_icon="🤖")
st.title("🤖 RAG AI Chatbot")
if "messages" not in st.session_state:
st.session_state.messages = [{"sender": "bot", "text": "Hello! Ask me anything."}]
def get_bot_response(question):
url = "http://localhost:8000/chat"
payload = {"user_id": "user123", "question": question}
try:
response = requests.post(url, json=payload)
response.raise_for_status()
return response.json().get("answer", "Sorry, no answer returned.")
except Exception as e:
return f"Error: {e}"
def submit():
user_input = st.session_state.user_input.strip()
if user_input:
st.session_state.messages.append({"sender": "user", "text": user_input})
bot_response = get_bot_response(user_input)
st.session_state.messages.append({"sender": "bot", "text": bot_response})
st.session_state.user_input = ""
st.text_input("Your message:", key="user_input", on_change=submit)
for msg in st.session_state.messages:
if msg["sender"] == "user":
st.markdown(f'<p style="text-align: right; background-color: #0084ff; color: white; padding: 10px; border-radius: 10px;">{msg["text"]}</p>', unsafe_allow_html=True)
else:
st.markdown(f'<p style="text-align: left; background-color: #e5e5ea; color: black; padding: 10px; border-radius: 10px;">{msg["text"]}</p>', unsafe_allow_html=True)
🚀 Run Streamlit Chatbot
streamlit run streamlit_chat.py
Open the given localhost URL and start chatting!
Summary
| Feature | React Version | Streamlit Version |
|---|---|---|
| Setup Complexity | Moderate (Node.js + React) | Low (Python only) |
| UI Flexibility | Very high | Moderate |
| Deployment Options | Static hosting + API | Python server |
| Real-time UX | Smooth, customizable | Simple and quick |
| Audio / Advanced UX | Easier with React | Possible but more complex |
83
