🎯 Mục tiêu bài học
Streamlit giúp bạn tạo AI web app trong vài phút — không cần biết HTML/CSS/JS.
Sau bài này, bạn sẽ:
✅ Setup Streamlit project ✅ Tạo chatbot interface ✅ Build AI-powered tools ✅ Deploy app nhanh chóng
🔍 Streamlit Basics
1.1 Installation & Setup
1pip install streamlit2streamlit hello # Test installation1.2 First App
1# app.py2import streamlit as st34st.title("🤖 My AI App")5st.write("Hello, world!")67# Run: streamlit run app.py1.3 Core Components
1import streamlit as st23# Text4st.title("Title")5st.header("Header")6st.subheader("Subheader")7st.write("Normal text")8st.markdown("**Bold** and *italic*")910# Input11name = st.text_input("Tên của bạn:")12age = st.slider("Tuổi:", 0, 100, 25)13option = st.selectbox("Model:", ["GPT-4", "Claude", "Gemini"])1415# Display16st.info("ℹ️ Information")17st.success("✅ Success")18st.warning("⚠️ Warning")19st.error("❌ Error")2021# Layout22col1, col2 = st.columns(2)23col1.metric("Users", "1,234", "+12%")24col2.metric("Revenue", "$5,678", "-3%")Checkpoint
Bạn đã cài đặt Streamlit và thử tạo app đầu tiên chưa?
💻 Build AI Chatbot
2.1 Basic Chat Interface
1# chatbot.py2import streamlit as st3from openai import OpenAI45st.title("💬 AI Chatbot")67# Initialize8client = OpenAI(api_key=st.secrets["OPENAI_API_KEY"])910if "messages" not in st.session_state:11 st.session_state.messages = [12 {"role": "system", "content": "Bạn là AI assistant thân thiện, trả lời bằng tiếng Việt."}13 ]1415# Display chat history16for msg in st.session_state.messages:17 if msg["role"] != "system":18 with st.chat_message(msg["role"]):19 st.write(msg["content"])2021# Chat input22if prompt := st.chat_input("Hỏi gì đi..."):23 # Add user message24 st.session_state.messages.append({"role": "user", "content": prompt})25 with st.chat_message("user"):26 st.write(prompt)27 28 # Get AI response29 with st.chat_message("assistant"):30 stream = client.chat.completions.create(31 model="gpt-4-turbo",32 messages=st.session_state.messages,33 stream=True34 )35 response = st.write_stream(stream)36 37 st.session_state.messages.append({"role": "assistant", "content": response})2.2 Secrets Management
1# .streamlit/secrets.toml (gitignored!)2OPENAI_API_KEY = "sk-xxxxxxxxxxxxx"1# Access in code2api_key = st.secrets["OPENAI_API_KEY"]2.3 Chat with Settings Sidebar
1import streamlit as st2from openai import OpenAI34# Sidebar settings5with st.sidebar:6 st.header("⚙️ Settings")7 model = st.selectbox("Model", ["gpt-4-turbo", "gpt-3.5-turbo"])8 temperature = st.slider("Temperature", 0.0, 2.0, 0.7, 0.1)9 max_tokens = st.slider("Max tokens", 100, 4000, 1000, 100)10 11 system_prompt = st.text_area(12 "System Prompt",13 value="Bạn là AI assistant hữu ích.",14 height=10015 )16 17 if st.button("🗑️ Clear Chat"):18 st.session_state.messages = []19 st.rerun()2021st.title(f"💬 Chatbot ({model})")2223# ... (chat logic same as above, use sidebar settings)Checkpoint
Bạn đã xây dựng được chatbot với chat interface và settings sidebar chưa?
🛠️ AI-Powered Tools
3.1 Document Summarizer
1# summarizer.py2import streamlit as st3from openai import OpenAI45st.title("📄 Document Summarizer")67client = OpenAI(api_key=st.secrets["OPENAI_API_KEY"])89uploaded_file = st.file_uploader("Upload text file", type=["txt", "md"])1011if uploaded_file:12 text = uploaded_file.read().decode("utf-8")13 14 st.subheader("📖 Original Text")15 with st.expander("Show full text"):16 st.write(text)17 18 col1, col2 = st.columns(2)19 length = col1.selectbox("Summary length", ["Short (3 câu)", "Medium (1 đoạn)", "Long (chi tiết)"])20 language = col2.selectbox("Ngôn ngữ", ["Tiếng Việt", "English"])21 22 if st.button("✨ Summarize", type="primary"):23 with st.spinner("Đang tóm tắt..."):24 response = client.chat.completions.create(25 model="gpt-4-turbo",26 messages=[27 {"role": "system", "content": f"Tóm tắt văn bản. Length: {length}. Language: {language}."},28 {"role": "user", "content": text}29 ]30 )31 32 st.subheader("📝 Summary")33 st.write(response.choices[0].message.content)34 st.caption(f"Tokens used: {response.usage.total_tokens}")3.2 SQL Query Generator
1# sql_gen.py2import streamlit as st3from openai import OpenAI45st.title("🗃️ SQL Query Generator")67client = OpenAI(api_key=st.secrets["OPENAI_API_KEY"])89# Schema input10schema = st.text_area(11 "Database Schema (paste CREATE TABLE statements):",12 height=150,13 placeholder="CREATE TABLE users (id INT, name VARCHAR, email VARCHAR, created_at DATE);"14)1516question = st.text_input(17 "Question (natural language):",18 placeholder="Tìm 10 users đăng ký gần nhất"19)2021if st.button("🔮 Generate SQL") and schema and question:22 with st.spinner("Generating..."):23 response = client.chat.completions.create(24 model="gpt-4-turbo",25 messages=[26 {"role": "system", "content": f"""27 You are a SQL expert. Given this schema:28 {schema}29 Generate a SQL query. Return ONLY the SQL, no explanation.30 """},31 {"role": "user", "content": question}32 ],33 temperature=034 )35 36 sql = response.choices[0].message.content37 st.code(sql, language="sql")38 39 # Explain query40 if st.button("📖 Explain"):41 explain = client.chat.completions.create(42 model="gpt-4-turbo",43 messages=[44 {"role": "user", "content": f"Giải thích SQL query này bằng tiếng Việt:\n{sql}"}45 ]46 )47 st.write(explain.choices[0].message.content)Checkpoint
Bạn đã thực hành xây dựng Document Summarizer hoặc SQL Query Generator chưa?
⚡ Advanced Streamlit Features
4.1 Session State
1# Session state persists across reruns2if "counter" not in st.session_state:3 st.session_state.counter = 045if st.button("Increment"):6 st.session_state.counter += 178st.write(f"Count: {st.session_state.counter}")4.2 Caching (Performance)
1@st.cache_data(ttl=3600) # Cache for 1 hour2def get_embedding(text):3 """Expensive API call - cache result."""4 response = client.embeddings.create(5 model="text-embedding-3-small",6 input=text7 )8 return response.data[0].embedding910@st.cache_resource # Cache resource (singleton)11def get_client():12 return OpenAI(api_key=st.secrets["OPENAI_API_KEY"])4.3 Multi-page App
1# app.py (main page)2import streamlit as st34st.set_page_config(5 page_title="AI Toolkit",6 page_icon="🤖",7 layout="wide"8)910st.title("🤖 AI Toolkit")11st.write("Choose a tool from the sidebar!")Checkpoint
Bạn đã hiểu Session State, Caching và Multi-page App chưa?
📝 Styling & UX
5.1 Page Config
1st.set_page_config(2 page_title="My AI App",3 page_icon="🤖",4 layout="wide", # or "centered"5 initial_sidebar_state="expanded"6)5.2 Custom CSS
1st.markdown("""2<style>3 .stChatMessage { border-radius: 10px; }4 .main > div { max-width: 800px; margin: auto; }5 [data-testid="stSidebar"] { background-color: #f0f2f6; }6</style>7""", unsafe_allow_html=True)5.3 Loading States
1# Spinner2with st.spinner("🤔 Đang suy nghĩ..."):3 response = get_ai_response(prompt)45# Progress bar6progress = st.progress(0)7for i in range(100):8 progress.progress(i + 1)910# Status11with st.status("Processing...", expanded=True) as status:12 st.write("Step 1: Loading data...")13 st.write("Step 2: Analyzing...")14 status.update(label="Done!", state="complete")Checkpoint
Bạn đã biết cách tùy chỉnh page config, CSS và loading states chưa?
💻 Hands-on Lab
Lab 1: Personal AI Chatbot (30 phút)
Build chatbot với:
- Model selection (sidebar)
- Temperature slider
- System prompt editor
- Chat history
- Clear button
- Token counter
Lab 2: AI Writing Assistant (30 phút)
Build app có 3 tabs:
- Improve: Paste text → AI improve grammar/style
- Translate: EN↔VI translation
- Summarize: Paste article → Get summary
Lab 3: Data Q&A Bot (bonus)
Upload CSV → AI phân tích và trả lời câu hỏi về data.
Checkpoint
Bạn đã thực hành xây dựng AI Chatbot và Writing Assistant chưa?
🎯 Tổng kết
📝 Quiz
-
st.session_state dùng để?
- Style components
- Lưu data giữa các reruns
- Connect database
- Deploy app
-
Secrets (API keys) lưu ở đâu trong Streamlit?
- .env file
- .streamlit/secrets.toml
- config.py
- Hardcode
-
@st.cache_data decorator dùng khi?
- Cache kết quả API call đắt tiền
- Style components
- Create buttons
- Handle errors
Những điểm quan trọng
- Streamlit = Python-only web apps — No HTML/CSS/JS needed
- st.chat_message + st.chat_input — Built-in chat UI
- st.session_state — Persist data across reruns
- st.secrets — Secure API key management
- @st.cache_data — Performance optimization
Câu hỏi tự kiểm tra
- st.session_state giải quyết vấn đề gì trong Streamlit và tại sao cần thiết cho chatbot?
- Cách quản lý API keys an toàn trong Streamlit khác gì so với Python script thông thường?
- @st.cache_data decorator hoạt động như thế nào và khi nào nên sử dụng?
- Streamlit rerun model là gì và ảnh hưởng thế nào đến việc thiết kế ứng dụng chat?
🎉 Tuyệt vời! Bạn đã hoàn thành bài học Streamlit cho AI Apps!
Tiếp theo: Chúng ta sẽ học cách quản lý multi-turn conversations và context windows!
🚀 Bài tiếp theo
Conversation Management — Quản lý multi-turn conversations và context windows!
