File size: 1,451 Bytes
0bbe8e9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import streamlit as st
import requests

API_URL = "http://localhost:8000/chat"  # FastAPI server của bạn

st.set_page_config(page_title="Coca-Cola Chatbot", page_icon="🥤", layout="wide")
st.title("🥤 Coca-Cola Vietnam Chatbot")

if "messages" not in st.session_state:
    st.session_state["messages"] = []

# Hiển thị lịch sử chat
for msg in st.session_state["messages"]:
    with st.chat_message(msg["role"]):
        st.markdown(msg["content"])

# Input từ người dùng
if user_input := st.chat_input("Nhập tin nhắn..."):
    # Hiển thị ngay trên UI
    st.session_state["messages"].append({"role": "user", "content": user_input})
    with st.chat_message("user"):
        st.markdown(user_input)

    # Gửi request đến FastAPI
    try:
        response = requests.post(API_URL, json={"message": user_input}, params={"session_id": "default"}, timeout=60)
        if response.status_code == 200:
            data = response.json()
            bot_reply = data.get("response", "⚠️ Không có phản hồi")
        else:
            bot_reply = f"❌ Lỗi API: {response.status_code}"

    except Exception as e:
        bot_reply = f"⚠️ Không kết nối được API: {e}"

    # Hiển thị phản hồi bot
    st.session_state["messages"].append({"role": "assistant", "content": bot_reply})
    with st.chat_message("assistant"):
        st.markdown(bot_reply)