SQL_RAG / app.py
Nguyen Thang Phuc
update app.py & rag_multi_turn.py
c2aff69
# app_gradio.py
import gradio as gr
from pathlib import Path
from rag_multi_turn import init_agent
from langchain.agents.agent import AgentExecutor
# Khởi tạo agent 1 lần khi start app
agent = init_agent()
# Đường dẫn file Excel cho người dùng tải xuống
excel_path = Path("data/dữ liệu bán hàng.xlsx")
# Hàm xử lý chat
def chat_fn(message, history):
default_prompt = (
'Trả lời ngắn gọn, súc tích, dễ hiểu, không lặp lại câu hỏi bằng tiếng Việt. '
'Đối với những câu hỏi khó, phức tạp, cần bóc tách ra thành các câu hỏi nhỏ và lần lượt trả lời. '
'Cố gắng tìm ra câu trả lời, đồng thời cần xác minh lại trước khi đưa ra câu trả lời cuối cùng. Nếu thực sự không biết thì nói "Tôi không biết". Không nên để markdown khi không cần thiết.'
)
try:
answer = agent.run(message + "\n" + default_prompt)
except KeyboardInterrupt:
answer = "Quá trình bị gián đoạn."
except AgentExecutor:
answer = "Giới hạn request qua Gemini API."
except Exception:
answer = "Tôi không biết."
history = history or []
history.append((message, answer))
return history, ""
# Tạo giao diện
with gr.Blocks(theme="default") as demo:
gr.Markdown(
"""
<h1 style="text-align:center; color:#2F4F4F;">🤖 Chatbot Hỗ Trợ Truy Vấn Dữ Liệu Bán Hàng</h1>
<p style="text-align:center; font-size:16px; color:#555;">
Chatbot giúp bạn truy vấn dữ liệu bán hàng nhanh chóng. Dữ liệu được lấy từ file Excel nguồn và phân tích bằng RAG.
Ngoài ra, vẫn có công cụ search web để hỗ trợ thêm thông tin bên ngoài.
</p>
"""
)
with gr.Row():
with gr.Column(scale=3):
chatbot_display = gr.Chatbot(height=450)
message_input = gr.Textbox(
placeholder="Nhập câu hỏi của bạn...",
show_label=False,
lines=1
)
send_button = gr.Button("Gửi", elem_id="send-btn")
send_button.click(
fn=chat_fn,
inputs=[message_input, chatbot_display],
outputs=[chatbot_display, message_input]
)
# Nhấn Enter cũng gửi
message_input.submit(
fn=chat_fn,
inputs=[message_input, chatbot_display],
outputs=[chatbot_display, message_input],
)
with gr.Column(scale=1):
gr.Markdown("### 📂 Tệp dữ liệu nguồn")
if excel_path.exists():
gr.File(
value=str(excel_path),
label="Tải xuống Excel",
type="filepath",
interactive=False
)
else:
gr.Markdown("⚠️ Không tìm thấy file dữ liệu.")
# Khối giải thích thêm
gr.Markdown(
"""
**Ví dụ một số câu hỏi bạn có thể hỏi Chatbot:**
- "Có những chi nhánh nào?"
- "NV212 là ai?"
- "Ngày 1-1-2024 ai bán được nhiều hàng nhất?"
⚠️ Lưu ý: Chatbot dùng API free của Gemini, tốc độ phản hồi chậm và chỉ xử lý được giới hạn lượng request/s.
""",
elem_id="excel-explanation"
)
if __name__ == "__main__":
demo.launch()