-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.py
139 lines (112 loc) · 5.7 KB
/
app.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
import os
from flask import Flask, render_template, request, jsonify, redirect, url_for
from openai import OpenAI
from apikey import my_api as apikey
import datetime
from datetime import timedelta
import re
now = datetime.datetime.now()
app = Flask(__name__)
# Load OpenAI API key from environment variable
apikey= os.environ["OPENAI_API_KEY"]
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
# Define the system prompt
system_prompt = """You are a college therapist in the USA. Students are meeting you for counselling and therapy.
Ask them a variety of questions to assess for depression, anxiety, OCD, panic disorder, social anxiety disorder,
suicidal intent, substance abuse, loneliness, and bipolar disorder. Ask one question at a time. After each response, evaluate if you have
gathered enough information to determine the student's condition and its urgency. If you have, provide an
urgency rating on a scale of 1 to 5, with 5 being the most urgent and 1 being the least urgent.
If at any point the student expresses suicidal thoughts or intentions, immediately provide call helpline like 911 and encourage them to seek immediate help. You must flag all suicide expressions as an urgency level 5, always provide crisis hotline numbers and emergency resources.
You must not say you are unable to help because you are the therapist helping the student.
Include [URGENCY_RATING: X] at the very end of your response when you've determined the urgency, where X is the rating.
This will signal the end of the conversation."""
def get_ai_response(messages):
chat_completion = client.chat.completions.create(
messages=messages,
model="gpt-4o",
)
return chat_completion.choices[0].message.content.strip()
def extract_urgency_rating(response):
match = re.search(r'\[URGENCY_RATING: (\d+)\]', response)
if match:
return int(match.group(1)), response.replace(match.group(0), '').strip()
return None, response
def schedule(name, urgent_lvl):
if urgent_lvl == 5: # Emergency
appointment_time = now + timedelta(hours=1)
description = "Emergency appointment scheduled."
elif urgent_lvl == 4: # Medium Emergency (within a week)
appointment_time = now + timedelta(days=7)
description = "Medium emergency appointment scheduled within a week."
elif urgent_lvl == 3: # Less Urgent (within a month)
appointment_time = now + timedelta(days=30)
description = "Appointment scheduled within a month."
else: # Regular (in 3 months)
appointment_time = now + timedelta(days=90)
description = "Regular appointment scheduled in 3 months."
return appointment_time, description
@app.route('/')
def index():
"""Displays the homepage."""
return render_template('index.html')
@app.route('/questionnaire', methods=['GET', 'POST'])
def questionnaire():
if request.method == 'POST':
data = request.get_json()
# Check if this is a message for the AI conversation
if 'message' in data:
user_input = data['message']
messages = data.get('messages', [])
if not messages:
messages = [{"role": "system", "content": system_prompt}]
messages.append({"role": "user", "content": user_input})
ai_response = get_ai_response(messages)
urgency_rating, filtered_response = extract_urgency_rating(ai_response)
messages.append({"role": "assistant", "content": ai_response})
response_data = {
"message": filtered_response,
"urgency_rating": urgency_rating,
"messages": messages
}
# If the urgency rating is 5, schedule an emergency appointment
if urgency_rating == 5:
appointment_time, description = schedule("user", urgency_rating)
response_data["appointment_time"] = appointment_time.strftime("%Y-%m-%d %H:%M")
response_data["message"] += f"\n\n{description} Your appointment is scheduled for {appointment_time.strftime('%Y-%m-%d %H:%M')}"
return jsonify(response_data)
# If it's the final form submission
elif 'name' in data:
print("Not there")
name = data.get('name')
email = data.get('email')
concern = data.get('concern')
# Handle urgency more robustly
urgency_data = data.get('urgency')
if isinstance(urgency_data, str) and urgency_data.isdigit():
urgency = int(urgency_data)
elif isinstance(urgency_data, int):
urgency = urgency_data
else:
# If urgency is not a valid number, default to highest urgency
print(f"Invalid urgency value: {urgency_data}. Defaulting to highest urgency.")
urgency = 5
# Save data to database (implement this part)
# Schedule appointment
appointment_time, description = schedule(name, urgency)
final_response = {
'message': f'{description} Your appointment is scheduled for {appointment_time.strftime("%Y-%m-%d %H:%M")}',
'appointment_time': appointment_time.strftime("%Y-%m-%d %H:%M")
}
return jsonify(final_response)
else:
return jsonify({"error": "Invalid data format"}), 400
return render_template('questionnaire.html')
@app.route('/available_times')
def available_times():
# This route should be implemented to show available appointment times
return "Available Times Page"
# if __name__ == '__main__':
# app.run(debug=True)
if __name__ == '__main__':
port = int(os.environ.get("PORT", 5000))
app.run(host="0.0.0.0", port=port)