import os os.system("pip install --upgrade pip") import streamlit as st import openai import json from io import StringIO openai.api_key = "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" # YOUR_API_KEY 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="text-davinci-003", 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 ############################################### #######<<< generate_prompt >>>################# ############################################### def generate_prompt(chat_history): prompt = "" user_count = 1 bot_count = 1 for message in chat_history: if "user" in message: prompt += f"User {user_count}: " + message["user"] + "\n" user_count += 1 elif "bot" in message: prompt += f"Bot {bot_count}: " + message["bot"] + "\n" bot_count += 1 return prompt ############################################### ##########<<< chatbot >>>############## ###############################################\ def chatbot(): chat_history = load_chat_history() user_input = st.text_input("User Input:", max_chars=100) col1, col2, col3 = st.columns([1, 1, 7]) if col1.button("Send"): chat_history = get_response(user_input, chat_history) save_chat_history(chat_history) if col2.button("Clear"): chat_history = [] save_chat_history(chat_history) if col3.button("Download"): chat_history_json = json.dumps(chat_history) st.download_button( "Download Chat History", data=StringIO(chat_history_json).read(), file_name="chat_history.json", mime="application/json" ) st.subheader("Chat History") user_count = 1 bot_count = 1 for message in chat_history: if "user" in message: st.text_area(f"User {user_count}:", message["user"], height=100) user_count += 1 elif "bot" in message: st.markdown(f"**Bot {bot_count}:** {message['bot']}", unsafe_allow_html=True) bot_count += 1 chatbot()