import os
import openai
import streamlit as st
import json
# Set OpenAI API key
openai.api_key = os.environ["OPENAI_API_KEY"]
# Set page config
st.set_page_config(page_title="JChat Real Estate Investing Chatbot", page_icon="🏘️", layout="wide",)
# Define path for saving chat history
CHAT_HISTORY_PATH = "chat_history.json"
# Define chat history object and counter
chat_history = []
counter = 0
# Load existing chat history if file exists
if os.path.exists(CHAT_HISTORY_PATH):
use_chat_history = st.sidebar.checkbox("Use existing chat history?")
if use_chat_history:
with open(CHAT_HISTORY_PATH, "r") as f:
chat_history = json.load(f)
else:
st.sidebar.info("No chat history found.")
# Define chatbot function
def chatbot(input):
global counter
global chat_history
# Append user input to chat history
if input:
chat_history.append({"role": "user", "content": input})
# Get AI response from OpenAI API
if len(chat_history) >= 2:
prompt = f"{chat_history[-2]['content']}\nUser: {chat_history[-1]['content']}\nAI:"
else:
prompt = f"User: {chat_history[-1]['content']}\nAI:"
response = openai.Completion.create(
engine="text-davinci-002",
prompt=prompt,
max_tokens=100,
n=1,
stop=None,
temperature=0.2,
).choices[0].text
# Append AI response to chat history
chat_history.append({"role": "assistant", "content": response})
counter += 1
# Save chat history to file
with open(CHAT_HISTORY_PATH, "w") as f:
json.dump(chat_history, f)
# Check if it's time to prompt for donation
if counter >= 3:
st.experimental_rerun()
st.write("Thank you for using our chatbot! If you find our service helpful, please consider making a donation to support us: Donate Now", unsafe_allow_html=True)
counter = 0
return response
# Define main function
def main():
if not os.path.isfile(CHAT_HISTORY_PATH):
if st.button("Create chat history file"):
with open(CHAT_HISTORY_PATH, "w") as f:
f.write('')
st.write("Chat history file created successfully!")
else:
st.warning("Without a chat history file, your chat history will not be saved.")
st.sidebar.checkbox("Use existing chat history?", value=True)
st.sidebar.subheader("Chat history:")
for i in range(max(len(chat_history) - 3, 0), len(chat_history)):
if chat_history[i]["role"] == "user":
st.sidebar.text(f"User: {chat_history[i]['content']}")
else:
st.sidebar.text(f"AI: {chat_history[i]['content']}")
# Add custom CSS
st.markdown(
"""
""",
unsafe_allow_html=True,
)
# Add content to your app
st.title("JChat Real Estate Investing Chatbot")
st.write("Ask anything you want about investing in real estate")
input_text = st.text_input("Ask your question")
if input_text:
output_text = chatbot(input_text)
st.write(output_text)
if __name__ == '__main__':
main()