MinAI - Về trang chủ
Lý thuyết
7/1350 phút
Đang tải...

Streamlit for AI Apps

Xây dựng giao diện AI chatbot và tools với Streamlit

0

🎯 Mục tiêu bài học

TB5 min

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

1

🔍 Streamlit Basics

TB5 min

1.1 Installation & Setup

Bash
1pip install streamlit
2streamlit hello # Test installation

1.2 First App

python.py
1# app.py
2import streamlit as st
3
4st.title("🤖 My AI App")
5st.write("Hello, world!")
6
7# Run: streamlit run app.py

1.3 Core Components

python.py
1import streamlit as st
2
3# Text
4st.title("Title")
5st.header("Header")
6st.subheader("Subheader")
7st.write("Normal text")
8st.markdown("**Bold** and *italic*")
9
10# Input
11name = 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"])
14
15# Display
16st.info("ℹ️ Information")
17st.success("✅ Success")
18st.warning("⚠️ Warning")
19st.error("❌ Error")
20
21# Layout
22col1, 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?

2

💻 Build AI Chatbot

TB5 min

2.1 Basic Chat Interface

python.py
1# chatbot.py
2import streamlit as st
3from openai import OpenAI
4
5st.title("💬 AI Chatbot")
6
7# Initialize
8client = OpenAI(api_key=st.secrets["OPENAI_API_KEY"])
9
10if "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 ]
14
15# Display chat history
16for msg in st.session_state.messages:
17 if msg["role"] != "system":
18 with st.chat_message(msg["role"]):
19 st.write(msg["content"])
20
21# Chat input
22if prompt := st.chat_input("Hỏi gì đi..."):
23 # Add user message
24 st.session_state.messages.append({"role": "user", "content": prompt})
25 with st.chat_message("user"):
26 st.write(prompt)
27
28 # Get AI response
29 with st.chat_message("assistant"):
30 stream = client.chat.completions.create(
31 model="gpt-4-turbo",
32 messages=st.session_state.messages,
33 stream=True
34 )
35 response = st.write_stream(stream)
36
37 st.session_state.messages.append({"role": "assistant", "content": response})

2.2 Secrets Management

toml
1# .streamlit/secrets.toml (gitignored!)
2OPENAI_API_KEY = "sk-xxxxxxxxxxxxx"
python.py
1# Access in code
2api_key = st.secrets["OPENAI_API_KEY"]

2.3 Chat with Settings Sidebar

python.py
1import streamlit as st
2from openai import OpenAI
3
4# Sidebar settings
5with 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=100
15 )
16
17 if st.button("🗑️ Clear Chat"):
18 st.session_state.messages = []
19 st.rerun()
20
21st.title(f"💬 Chatbot ({model})")
22
23# ... (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?

3

🛠️ AI-Powered Tools

TB5 min

3.1 Document Summarizer

python.py
1# summarizer.py
2import streamlit as st
3from openai import OpenAI
4
5st.title("📄 Document Summarizer")
6
7client = OpenAI(api_key=st.secrets["OPENAI_API_KEY"])
8
9uploaded_file = st.file_uploader("Upload text file", type=["txt", "md"])
10
11if 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

python.py
1# sql_gen.py
2import streamlit as st
3from openai import OpenAI
4
5st.title("🗃️ SQL Query Generator")
6
7client = OpenAI(api_key=st.secrets["OPENAI_API_KEY"])
8
9# Schema input
10schema = 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)
15
16question = st.text_input(
17 "Question (natural language):",
18 placeholder="Tìm 10 users đăng ký gần nhất"
19)
20
21if 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=0
34 )
35
36 sql = response.choices[0].message.content
37 st.code(sql, language="sql")
38
39 # Explain query
40 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?

4

⚡ Advanced Streamlit Features

TB5 min

4.1 Session State

python.py
1# Session state persists across reruns
2if "counter" not in st.session_state:
3 st.session_state.counter = 0
4
5if st.button("Increment"):
6 st.session_state.counter += 1
7
8st.write(f"Count: {st.session_state.counter}")

4.2 Caching (Performance)

python.py
1@st.cache_data(ttl=3600) # Cache for 1 hour
2def get_embedding(text):
3 """Expensive API call - cache result."""
4 response = client.embeddings.create(
5 model="text-embedding-3-small",
6 input=text
7 )
8 return response.data[0].embedding
9
10@st.cache_resource # Cache resource (singleton)
11def get_client():
12 return OpenAI(api_key=st.secrets["OPENAI_API_KEY"])

4.3 Multi-page App

📁my_app/
🐍app.py — Main page
📂pages/
🐍1_💬_Chatbot.py
🐍2_📄_Summarizer.py
🐍3_🗃️_SQL_Gen.py
📂.streamlit/
📄config.toml
📄secrets.toml
📄requirements.txt
python.py
1# app.py (main page)
2import streamlit as st
3
4st.set_page_config(
5 page_title="AI Toolkit",
6 page_icon="🤖",
7 layout="wide"
8)
9
10st.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?

5

📝 Styling & UX

TB5 min

5.1 Page Config

python.py
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

python.py
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

python.py
1# Spinner
2with st.spinner("🤔 Đang suy nghĩ..."):
3 response = get_ai_response(prompt)
4
5# Progress bar
6progress = st.progress(0)
7for i in range(100):
8 progress.progress(i + 1)
9
10# Status
11with 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?

6

💻 Hands-on Lab

TB5 min

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:

  1. Improve: Paste text → AI improve grammar/style
  2. Translate: EN↔VI translation
  3. 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?

7

🎯 Tổng kết

TB5 min

📝 Quiz

  1. st.session_state dùng để?

    • Style components
    • Lưu data giữa các reruns
    • Connect database
    • Deploy app
  2. Secrets (API keys) lưu ở đâu trong Streamlit?

    • .env file
    • .streamlit/secrets.toml
    • config.py
    • Hardcode
  3. @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

  1. Streamlit = Python-only web apps — No HTML/CSS/JS needed
  2. st.chat_message + st.chat_input — Built-in chat UI
  3. st.session_state — Persist data across reruns
  4. st.secrets — Secure API key management
  5. @st.cache_data — Performance optimization

Câu hỏi tự kiểm tra

  1. st.session_state giải quyết vấn đề gì trong Streamlit và tại sao cần thiết cho chatbot?
  2. Cách quản lý API keys an toàn trong Streamlit khác gì so với Python script thông thường?
  3. @st.cache_data decorator hoạt động như thế nào và khi nào nên sử dụng?
  4. 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!