-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.py
96 lines (68 loc) · 2.38 KB
/
index.py
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
from flask import Flask, render_template, request, session, redirect, url_for, jsonify
import os
from dotenv import load_dotenv
from chatbot import setup_chain
# Load environment variables
load_dotenv()
# Initialize Flask app
app = Flask(__name__)
# Set secret key
app.secret_key = os.getenv('secret_key')
# Initialize chain variable
chain = None
# Define route for home page
@app.route("/")
def hello():
return render_template("home.html")
# Define route for start page
@app.route("/start")
def start():
if "OPENAI_API_KEY" in session:
return redirect(url_for("chat"))
else:
# If not logged in, redirect to the login page
return redirect(url_for("login"))
# Define route for login page
@app.route("/login", methods=["GET", "POST"])
def login():
if request.method == "POST":
# Retrieve the API key from the form data
apikey = request.form.get("apikey")
# Store the API key in the session
session["OPENAI_API_KEY"] = apikey
# Initialize the LLM chain with the user's API key
os.environ["OPENAI_API_KEY"] = apikey
return redirect(url_for("chat"))
return render_template("login.html")
# Define route for chat page
@app.route("/chat", methods=["GET", "POST"])
def chat():
print("Session data:", session) # Print session data
global chain # Access the global chain object
# Check if the API key is in the session
if "OPENAI_API_KEY" not in session:
# If the API key is not in the session, redirect to the login page
return redirect(url_for("login"))
if request.method == "POST":
# Get the chat message from the POST data
message = request.form.get("message")
# Initialize the LLM chain if it has not been initialized yet
if chain is None:
chain = setup_chain()
# Pass the chat message to the LLM chain
response = chain.run(message)
# Return the chatbot response as JSON
return jsonify({"message": message, "bot_reply": response})
else:
# If it's a GET request, render the chat page
return render_template("chat.html")
# Define route for ending the chat
@app.route('/end_chat')
def end_chat():
# Clear the session
session.clear()
# Redirect to the start page
return redirect(url_for('start'))
# Run the Flask app
if __name__ == "__main__":
app.run(debug=True)