|
import streamlit as st |
|
import openai |
|
import json |
|
|
|
openai.api_key = "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" |
|
|
|
|
|
st.title("🤖 AI ChatBot") |
|
|
|
|
|
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) |
|
|
|
|
|
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 |
|
|
|
|
|
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 |
|
|
|
|
|
def chatbot(): |
|
chat_history = load_chat_history() |
|
|
|
|
|
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}") |
|
|
|
|
|
st.sidebar.subheader("User Input") |
|
user_input = st.sidebar.text_input("User:", "") |
|
|
|
|
|
if st.sidebar.button("Send"): |
|
chat_history = get_response(user_input, chat_history) |
|
save_chat_history(chat_history) |
|
|
|
|
|
if st.sidebar.button("Clear"): |
|
chat_history = [] |
|
save_chat_history(chat_history) |
|
|
|
chatbot() |
|
|