demo_chatbot_streamlit / chatbot_app_v2.py
thenHung's picture
Upload 5 files
4f43049
raw
history blame contribute delete
No virus
2.34 kB
import streamlit as st
import openai
import json
openai.api_key = "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"
# Thay YOUR_API_KEY bằng API key của bạn
st.title("🤖 AI ChatBot")
# Tạo hoặc tải lịch sử chat từ file
def load_chat_history():
try:
with open("chat_history.json", "r") as file:
chat_history = json.load(file)
except FileNotFoundError:
chat_history = []
return chat_history
def save_chat_history(chat_history):
with open("chat_history.json", "w") as file:
json.dump(chat_history, file)
# Hàm để tạo phản hồi từ OpenAI API
def get_response(prompt, chat_history):
chat_history.append({"user": prompt})
response = openai.Completion.create(
engine="davinci",
prompt=generate_prompt(chat_history),
max_tokens=50,
temperature=0.7,
top_p=1.0,
frequency_penalty=0.0,
presence_penalty=0.0,
)
chat_history.append({"bot": response.choices[0].text.strip()})
return chat_history
# Hàm để tạo prompt từ lịch sử chat
def generate_prompt(chat_history):
prompt = ""
for i, message in enumerate(chat_history):
if "user" in message:
prompt += f"User {i+1}: " + message["user"] + "\n"
elif "bot" in message:
prompt += f"Bot {i+1}: " + message["bot"] + "\n"
return prompt
# Giao diện chatbot
def chatbot():
chat_history = load_chat_history()
# Hiển thị lịch sử chat
st.subheader("Chat History")
for i, message in enumerate(chat_history):
if "user" in message:
st.text_area(f"User {i+1}:", message["user"], height=100, key=f"user_{i+1}")
elif "bot" in message:
st.text_area(f"Bot {i+1}:", message["bot"], height=100, key=f"bot_{i+1}")
# Gửi và nhận tin nhắn mới
st.sidebar.subheader("User Input")
user_input = st.sidebar.text_input("User:", "")
# Gửi yêu cầu đến OpenAI API và nhận phản hồi
if st.sidebar.button("Send"):
chat_history = get_response(user_input, chat_history)
save_chat_history(chat_history)
# Nút Clear để xóa lịch sử chat
if st.sidebar.button("Clear"):
chat_history = []
save_chat_history(chat_history)
chatbot()