-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
87 lines (74 loc) · 2.49 KB
/
Copy pathmain.py
File metadata and controls
87 lines (74 loc) · 2.49 KB
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
from flask import Flask, request, session, jsonify, render_template
from flask_pymongo import PyMongo
from dotenv import load_dotenv
import openai
import uuid
import re
import os
load_dotenv()
# Create Flask application instance
app = Flask(__name__)
# Flask-PyMongo configuration
app.config["MONGO_URI"] = os.getenv('MONGO_URI')
app.secret_key = os.getenv('SECRET_KEY')
mongo = PyMongo(app)
openai.api_key = os.getenv('OPENAI_API_KEY')
@app.route("/")
def index():
"""
Home route that initializes a user session and displays the chat interface.
"""
user_id = session.get('userID')
# Create a new user session if one does not exist
if not user_id:
user_id = str(uuid.uuid4())
session['userID'] = user_id
# Insert a new user into the database if they do not exist
if not mongo.db.users.find_one({"user_id": user_id}):
mongo.db.users.insert_one({"user_id": user_id, "chats": []})
# Retrieve the user's chat history
my_chats = mongo.db.users.find_one({"user_id": user_id}).get('chats', [])
return render_template("index.html", myChats=my_chats)
@app.route("/api", methods=["POST"])
def qa():
"""
API endpoint for processing a question and generating an answer using OpenAI.
"""
user_id = session.get('userID')
question = clean_text(request.json['question'])
# Generate a response using OpenAI
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{
"role": "user",
"content": question
}
],
temperature=1,
max_tokens=256,
top_p=1,
frequency_penalty=0,
presence_penalty=0
)
# Extract answer from response and store the question and answer in the database
answer_content = response["choices"][0]["message"]["content"]
data = {"question": question, "answer": response["choices"][0]["message"]}
mongo.db.users.update_one(
{"user_id": user_id},
{"$push" : {"chats": [question, answer_content]}}
)
return jsonify(data)
def clean_text(text):
"""
Cleans the input text to ensure better processing by OpenAI.
:param text: The text to be cleaned.
:return: The cleaned text.
"""
text = text.strip()
text = re.sub(r'\s+', ' ', text)
text = text.replace("\\'", "'").replace("→", "")
return text
if __name__ == "__main__":
# This should only be run when executing the script directly, not when running through Gunicorn
app.run()