simran0608 commited on
Commit
71d6a35
1 Parent(s): 2324959

Upload 10 files

Browse files
Files changed (10) hide show
  1. Readme.md +32 -0
  2. app.py +107 -0
  3. bot.py +44 -0
  4. credentials.json +4 -0
  5. doctor_specialization_dummy_data.csv +13 -0
  6. functions.py +489 -0
  7. model.py +41 -0
  8. requirements.txt +91 -0
  9. schemas.py +24 -0
  10. token.json +1 -0
Readme.md ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Appointment Booking Bot for Virtual Doctor Appointments
2
+
3
+ ## Project Overview
4
+
5
+ The Appointment Booking Bot is a comprehensive solution for managing virtual doctor appointments. It integrates with Google Calendar to automate appointment scheduling tasks, provides symptom analysis, and offers doctor recommendations based on user input. The system operates efficiently to improve patient experience and streamline healthcare provider operations.
6
+
7
+ ## Key Features
8
+
9
+ - **Symptom Analysis:** Analyze user symptoms and suggest relevant doctors.
10
+ - **Appointment Management:** Book, reschedule, delete, and check availability of appointments.
11
+ - **Real-Time Updates:** Check doctor availability and book appointments instantly.
12
+ - **Data Insights:** Provides actionable insights into appointment trends and patient preferences.
13
+
14
+ ## Tech Stack
15
+
16
+ - **LangChain Framework:** Utilized for building the agent with multiple tools.
17
+ - **Google Calendar API:** For managing appointment-related actions.
18
+ - **Model:** Llama-3.1-70B-Versatile using Groq hardware for symptom analysis and health advice.
19
+ - **Python:** Backend programming.
20
+ - **Streamlit:** For user interface integration.
21
+ - **MongoDB:** For secure data storage.
22
+
23
+ ## Files and Their Functions
24
+
25
+ - **`functions.py`**: Contains information on all the tools and functions used in the project.
26
+ - **`schema.py`**: Defines the input schema for all tools.
27
+ - **`bot.py`**: Command-line interface (CLI) application for managing appointments and interacting with the bot.
28
+ - **`app.py`**: Streamlit integration file that connects the model with the user interface for a seamless experience.
29
+ - **`model.py`**: Contains the agent used for the system.
30
+ - **`requirements.txt`**: Contains all the necessary libraries for development of this project.
31
+
32
+
app.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ from model import create_agent
4
+
5
+ # Set page config at the very beginning
6
+ st.set_page_config(page_title="Appointment Booking Bot", page_icon="🏥")
7
+ # Load doctor data
8
+ @st.cache_data
9
+ def load_doctor_data():
10
+ return pd.read_csv('doctor_specialization_dummy_data.csv')
11
+
12
+ doctor_df = load_doctor_data()
13
+ API_KEY = "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"
14
+
15
+ # General prompt template
16
+ general_prompt_template = """
17
+ You are a healthcare assistant AI. Your primary responsibilities are:
18
+
19
+ - Keep the conversation friendly and provide required details too.
20
+ - Suggesting a doctor based on the user's symptoms.
21
+ - Managing doctor-related appointments (book, reschedule, delete), adhering to specific rules.
22
+ - Provide general assistance, such as greetings, if the user starts with a hello or introduction.
23
+
24
+ Appointment Rules:
25
+ - Appointments can only be scheduled/reschedule from Monday to Friday, between 10 AM and 7 PM.
26
+ - Appointments must be booked/reschedule within the next 7 days.
27
+ - Book/Reschedule the appointment for 60 minutes/1 hr.
28
+ - You are not allowed to handle appointments outside these constraints.
29
+
30
+ If the user says something like "hello," "hi," "hey," or a similar greeting, respond appropriately.
31
+ If the user provides symptoms, suggest a doctor based on those symptoms.
32
+ If user asks details of doctor or book appointment slots without specifying symptoms, ask the user what symptoms they have.
33
+ """
34
+
35
+ # Initialize the agent
36
+ @st.cache_resource
37
+ def get_agent():
38
+ return create_agent(general_prompt_template)
39
+
40
+ agent = get_agent()
41
+
42
+ # Streamlit app
43
+ st.title("Appointment Booking Bot")
44
+
45
+ # Initialize chat history
46
+ if "messages" not in st.session_state:
47
+ st.session_state.messages = []
48
+
49
+ # Display chat messages from history on app rerun
50
+ for message in st.session_state.messages:
51
+ with st.chat_message(message["role"]):
52
+ st.markdown(message["content"])
53
+
54
+ # React to user input
55
+ if prompt := st.chat_input("What is your query?"):
56
+ # Display user message in chat message container
57
+ st.chat_message("user").markdown(prompt)
58
+ # Add user message to chat history
59
+ st.session_state.messages.append({"role": "user", "content": prompt})
60
+
61
+ response = agent({"input": prompt})['output']
62
+
63
+ # Display assistant response in chat message container
64
+ with st.chat_message("assistant"):
65
+ st.markdown(response)
66
+ # Add assistant response to chat history
67
+ st.session_state.messages.append({"role": "assistant", "content": response})
68
+
69
+ # Main function to run the app
70
+ def main():
71
+ st.sidebar.title("About")
72
+ st.sidebar.info("""
73
+ 🏥 **Appointment Booking Bot**
74
+
75
+ 🩺 Virtual Doctors Appointment Managing
76
+
77
+ 🔑 **Key Features:**
78
+ - Symptom analysis and health advice
79
+ - Medical information lookup
80
+ - Appointment management:
81
+ 📅 Book appointments
82
+ 🔄 Reschedule appointments
83
+ 🗑️ Delete appointments
84
+
85
+ ⏰ **Appointment Availability:**
86
+ - Monday to Friday
87
+ - 10 AM to 7 PM
88
+ - Book up to 7 days in advance
89
+
90
+ ⚠️ **Important Note:**
91
+ This app is for informational purposes only and does not replace professional medical advice. Always consult with a qualified healthcare provider for medical concerns.
92
+
93
+ 💡 Start by describing your symptoms or managing your appointments!
94
+ """)
95
+ # Display a horizontal line, emoji, and the name "SIMRAN"
96
+ col1, col2 = st.sidebar.columns([2, 1])
97
+
98
+ # Display emoji and name in the first column
99
+ with col1:
100
+ st.markdown("👤 **SIMRAN**") # Profile emoji next to the name
101
+
102
+ # Display red logout button in the second column
103
+ with col2:
104
+ logout_button = st.button("Logout", key="logout", help="Click to logout", use_container_width=True)
105
+
106
+ if __name__ == "__main__":
107
+ main()
bot.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from model import create_agent
2
+ import pandas as pd
3
+
4
+ doctor_df = pd.read_csv('doctor_specialization_dummy_data.csv')
5
+ API_KEY = "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"
6
+
7
+ # General prompt template with fallback included
8
+ general_prompt_template = """
9
+ You are a healthcare assistant AI. Your primary responsibilities are:
10
+
11
+ - Keep the conversation friendly and provide require details too.
12
+ - Suggesting a doctor based on the user's symptoms.
13
+ - Managing doctor-related appointments (book, reschedule, delete), adhering to specific rules.
14
+ - Provide general assistance, such as greetings, if the user starts with a hello or introduction.
15
+
16
+ Appointment Rules:
17
+ - Appointments can only be scheduled from Monday to Friday, between 10 AM and 7 PM.
18
+ - Appointments must be booked within the next 7 days.
19
+ - Book the appointment for 60 minutes/1 hr.
20
+ - You are not allowed to handle appointments outside these constraints.
21
+
22
+ If the user says something like "hello," "hi," "hey," or a similar greeting, respond appropriately.
23
+ If the user provides symptoms, suggest a doctor based on those symptoms.
24
+ If user ask details of doctor or book appointment slots without specify symptoms ask to user that which symptoms they have
25
+
26
+ """
27
+
28
+ # Initialize the agent with tools and the general prompt
29
+ agent = create_agent(general_prompt_template)
30
+
31
+ # Updated interactive function to handle user queries with proper tool invocation
32
+ def interactive_ai_doctor_advisor():
33
+ print("Welcome to the AI Doctor Advisor!")
34
+ print("I am here to suggest you a doctor based on your symptoms and help with managing your appointments.")
35
+
36
+ while True:
37
+ query = input("\nYour Query: ")
38
+ if query.lower() == 'exit':
39
+ break
40
+ response = agent({"input": query})['output']
41
+ print(response)
42
+
43
+ # Example Usage: Run the interactive advisor
44
+ interactive_ai_doctor_advisor()
credentials.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {"installed":{"client_id":"123736158724-1hf7onqa73dtlirlljc8nq17ecjlmash.apps.googleusercontent.com",
2
+ "project_id":"ethereal-app-434922-g3","auth_uri":"https://accounts.google.com/o/oauth2/auth",
3
+ "token_uri":"https://oauth2.googleapis.com/token","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs",
4
+ "client_secret":"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","redirect_uris":["http://localhost"]}}
doctor_specialization_dummy_data.csv ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Doctor Name,Specialization,Contact Number,Address
2
+ Dr. John Doe,Dentist,123-456-7890,"123 Main St, Cityville"
3
+ Dr. Sarah White,Cardiologist,123-555-7890,"456 Oak St, Townsville"
4
+ Dr. Michael Smith,Neurologist,123-678-9012,"789 Pine St, Metropolis"
5
+ Dr. Emily Davis,Orthopedist,321-456-1234,"101 Maple St, Springfield"
6
+ Dr. David Brown,Pediatrician,987-654-3210,"202 Birch St, Villagetown"
7
+ Dr. Jennifer Taylor,Dermatologist,555-123-4567,"303 Cedar St, Cityplace"
8
+ Dr. Christopher Wilson,Ophthalmologist,222-333-4444,"404 Elm St, Riverdale"
9
+ Dr. Amanda Moore,Psychiatrist,888-555-1234,"505 Walnut St, Capitalcity"
10
+ Dr. Robert Johnson,Gynecologist,999-888-7777,"606 Chestnut St, Boroughburg"
11
+ Dr. Linda Green,Oncologist,111-222-3333,"707 Poplar St, Urbantown"
12
+ Dr. Green Smith,Gastro,123-432-1221,"21,Apk apartments,San Franciso"
13
+ Dr. New Rasal,Primary Care,987-234-987,"32,Awert, LA"
functions.py ADDED
@@ -0,0 +1,489 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import timedelta
2
+ from datetime import datetime
3
+ import os.path
4
+ from google.auth.transport.requests import Request
5
+ from google.oauth2.credentials import Credentials
6
+ from google_auth_oauthlib.flow import InstalledAppFlow
7
+ from googleapiclient.discovery import build
8
+ from googleapiclient.errors import HttpError
9
+ import smtplib
10
+ from email.mime.multipart import MIMEMultipart
11
+ from email.mime.text import MIMEText
12
+ import pandas as pd
13
+ from langchain.prompts import PromptTemplate
14
+ from langchain.chains import LLMChain
15
+ from langchain_groq import ChatGroq
16
+ from langchain.agents import tool
17
+ from schemas import symptoms,bookSlot,deleteSlot,reschedule_event,listevent,checkevent
18
+
19
+ API_KEY="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"
20
+
21
+ llm = ChatGroq(
22
+ model="llama3-8b-8192",
23
+ temperature=0,
24
+ max_tokens=None,
25
+ timeout=None,
26
+ max_retries=2,
27
+ api_key=API_KEY
28
+ )
29
+ SCOPES = ["https://www.googleapis.com/auth/calendar"]
30
+ doctor_df = pd.read_csv('doctor_specialization_dummy_data.csv')
31
+
32
+ EMAIL_SENDER = "kothariyash360@gmail.com"
33
+ EMAIL_PASSWORD = "wlxf poqr wgsh qvqs"
34
+
35
+ def get_service():
36
+ """Create and return the Google Calendar API service."""
37
+ print('this function is called.')
38
+ creds = None
39
+ if os.path.exists("token.json"):
40
+ creds = Credentials.from_authorized_user_file("token.json", SCOPES)
41
+ if not creds or not creds.valid:
42
+ if creds and creds.expired and creds.refresh_token:
43
+ creds.refresh(Request())
44
+ else:
45
+ flow = InstalledAppFlow.from_client_secrets_file("credentials.json", SCOPES)
46
+ creds = flow.run_local_server(port=0)
47
+ with open("token.json", "w") as token:
48
+ token.write(creds.to_json())
49
+
50
+ return build("calendar", "v3", credentials=creds)
51
+
52
+ def send_email(to_email, subject, body):
53
+ """Send an email notification to the participants."""
54
+ try:
55
+ msg = MIMEMultipart()
56
+ msg['From'] = EMAIL_SENDER
57
+ msg['To'] = to_email
58
+ msg['Subject'] = subject
59
+ msg.attach(MIMEText(body, 'plain'))
60
+
61
+ server = smtplib.SMTP('smtp.gmail.com', 587)
62
+ server.starttls()
63
+ server.login(EMAIL_SENDER, EMAIL_PASSWORD)
64
+ text = msg.as_string()
65
+ server.sendmail(EMAIL_SENDER, to_email, text)
66
+ server.quit()
67
+
68
+ print(f"Email sent to {to_email}")
69
+ except Exception as e:
70
+ print(f"Failed to send email: {e}")
71
+
72
+
73
+ def is_valid_booking_time(start_time):
74
+ # Convert string to datetime object
75
+ start_time_dt = datetime.strptime(start_time, "%Y-%m-%dT%H:%M:%S%z")
76
+
77
+ # Ensure the booking is within the next 7 days
78
+ today = datetime.now(start_time_dt.tzinfo)
79
+ if start_time_dt < today or start_time_dt > (today + timedelta(days=7)):
80
+ return False, "You can only book appointments within the next 7 days."
81
+
82
+ # Ensure the booking is on a weekday and within 10 AM to 7 PM
83
+ if start_time_dt.weekday() >= 5: # 0 = Monday, 6 = Sunday
84
+ return False, "Appointments can only be booked Monday to Friday."
85
+
86
+ if not (10 <= start_time_dt.hour < 19): # Ensure the time is between 10 AM to 7 PM
87
+ return False, "Appointments can only be scheduled between 10 AM and 7 PM."
88
+
89
+ return True, None
90
+ import pytz
91
+ @tool("check-event", args_schema=checkevent, return_direct=True)
92
+ def check_slots(date):
93
+ """
94
+ This function is to check available slot for a given date, excluding times when events are booked.
95
+ It only returns valid slots that fall on weekdays (Mon-Fri) between 10 AM to 7 PM.
96
+
97
+ Args:
98
+ date (str): The date for which to check availability (e.g., '2024-09-17').
99
+
100
+ Returns:
101
+ str: Formatted string of available 1-hour slots or a message if no slots are available.
102
+ """
103
+ # Define the start and end time for the day
104
+ start_time = f"{date}T10:00:00+05:30" # Start at 10 AM
105
+ end_time = f"{date}T19:00:00+05:30" # End at 7 PM
106
+ service = get_service()
107
+
108
+ # Check if the date is valid (weekday, and within 10 AM to 7 PM)
109
+ valid, message = is_valid_booking_time(start_time)
110
+ if not valid:
111
+ return message
112
+
113
+ # Query for events between start and end time
114
+ events_result = service.events().list(
115
+ calendarId='primary',
116
+ timeMin=start_time,
117
+ timeMax=end_time,
118
+ singleEvents=True,
119
+ orderBy='startTime'
120
+ ).execute()
121
+
122
+ events = events_result.get('items', [])
123
+
124
+ # Define the working hours (10 AM to 7 PM)
125
+ work_start = datetime.fromisoformat(f"{date}T10:00:00+05:30")
126
+ work_end = datetime.fromisoformat(f"{date}T19:00:00+05:30")
127
+ available_slots = []
128
+
129
+ # Add all the slots starting from work_start until work_end
130
+ current_time = work_start
131
+
132
+ for event in events:
133
+ event_start = datetime.fromisoformat(event['start']['dateTime'])
134
+ event_end = datetime.fromisoformat(event['end']['dateTime'])
135
+
136
+ # Find all available 1-hour slots between current_time and the event start
137
+ while current_time + timedelta(hours=1) <= event_start:
138
+ slot_start = current_time
139
+ slot_end = current_time + timedelta(hours=1)
140
+
141
+ # Ensure the slot is a valid booking time
142
+ valid, message = is_valid_booking_time(slot_start.isoformat())
143
+ if valid:
144
+ available_slots.append((slot_start, slot_end))
145
+ current_time += timedelta(hours=1)
146
+
147
+ # Move current_time to the end of the event
148
+ current_time = max(current_time, event_end)
149
+
150
+ # Add slots from the last event to the end of the working day
151
+ while current_time + timedelta(hours=1) <= work_end:
152
+ slot_start = current_time
153
+ slot_end = current_time + timedelta(hours=1)
154
+
155
+ # Ensure the slot is a valid booking time
156
+ valid, message = is_valid_booking_time(slot_start.isoformat())
157
+ if valid:
158
+ available_slots.append((slot_start, slot_end))
159
+ current_time += timedelta(hours=1)
160
+
161
+ # Return available slots in a properly formatted string
162
+ if available_slots:
163
+ formatted_output = f"📅 **Available Slots for {date}:\n**\n\n"
164
+ for slot in available_slots:
165
+ start_time = slot[0].strftime('%I:%M %p')
166
+ end_time = slot[1].strftime('%I:%M %p')
167
+ formatted_output += f"\n🕒 {start_time} - {end_time}\n"
168
+
169
+ formatted_output += "\n✨ Each slot is for a 1-hour appointment."
170
+ formatted_output += "\n\n💡 To book an appointment, please specify your preferred time slot."
171
+
172
+ return formatted_output
173
+ else:
174
+ return "😔 I'm sorry, but there are no available slots for the requested date. Would you like to check another date?"
175
+
176
+
177
+ def check_slot_availability(start_time, end_time):
178
+ # Define the Asia/Kolkata timezone
179
+ kolkata_tz = pytz.timezone('Asia/Kolkata')
180
+
181
+ # Parse and localize the start_time and end_time into Asia/Kolkata timezone
182
+ start_time_dt = datetime.strptime(start_time, "%Y-%m-%dT%H:%M:%S%z")
183
+ end_time_dt = datetime.strptime(end_time, "%Y-%m-%dT%H:%M:%S%z")
184
+
185
+ # Ensure the times are correctly converted to ISO format without adding "Z"
186
+ time_min = start_time_dt.isoformat() # Already includes the timezone info
187
+ time_max = end_time_dt.isoformat() # Already includes the timezone info
188
+ service=get_service()
189
+ # Fetch events within the given time range in Asia/Kolkata timezone
190
+ events_result = service.events().list(
191
+ calendarId="primary",
192
+ timeMin=time_min,
193
+ timeMax=time_max,
194
+ singleEvents=True,
195
+ orderBy="startTime"
196
+ ).execute()
197
+
198
+ events = events_result.get("items", [])
199
+ return len(events) == 0 # Returns True if the slot is free
200
+
201
+ def find_event_by_time(start_time):
202
+ """
203
+ Finds an event by its start time in the user's Google Calendar.
204
+
205
+ Args:
206
+ start_time (str): The start time of the event in ISO format (e.g., '2024-09-17T14:30:00+05:30').
207
+
208
+ Returns:
209
+ dict or None: The event details if found, otherwise None.
210
+ """
211
+ try:
212
+ print(f"Searching for event starting at {start_time}")
213
+ service=get_service()
214
+ # Calculate the end time (assuming 1-hour event window)
215
+ start_time_dt = datetime.fromisoformat(start_time)
216
+ end_time_dt = start_time_dt + timedelta(hours=1)
217
+ end_time = end_time_dt.isoformat()
218
+
219
+ # Query Google Calendar API for events in this time window
220
+ events_result = service.events().list(
221
+ calendarId="primary",
222
+ timeMin=start_time,
223
+ timeMax=end_time,
224
+ singleEvents=True,
225
+ orderBy="startTime",
226
+ ).execute()
227
+
228
+ events = events_result.get("items", [])
229
+ print(f"Events found: {events}")
230
+
231
+ # Return the first event that matches the time exactly
232
+ for event in events:
233
+ event_start = event['start'].get('dateTime')
234
+ if event_start == start_time:
235
+ print(f"Matching event found: {event['summary']} at {event_start}")
236
+ return event
237
+
238
+ print(f"No event found starting at {start_time}")
239
+ return None
240
+
241
+ except HttpError as error:
242
+ print(f"An error occurred: {error}")
243
+ return None
244
+ except Exception as e:
245
+ print(f"Unexpected error: {e}")
246
+ return None
247
+
248
+
249
+
250
+
251
+ @tool("list_event", args_schema=listevent, return_direct=True)
252
+ def list_upcoming_events(target_date):
253
+ """
254
+ Lists the upcoming events on the user's calendar for a specific date.
255
+
256
+ Args:
257
+ target_date (str): The date to filter events on, in 'YYYY-MM-DD' format.
258
+
259
+ Returns:
260
+ string: Summary of the events
261
+ """
262
+ service=get_service()
263
+ # Parse the target date to create timeMin and timeMax bounds
264
+ # Convert the target date string to a datetime object
265
+ target_date_obj = datetime.strptime(target_date, "%Y-%m-%d")
266
+
267
+ # Set timeMin to the beginning of the day and timeMax to the end of the day
268
+ time_min = target_date_obj.isoformat() + "Z" # Beginning of the day in UTC
269
+ time_max = (target_date_obj + timedelta(days=1)).isoformat() + "Z" # End of the day in UTC
270
+
271
+ print(f"Getting events for {target_date}")
272
+
273
+ try:
274
+ events_result = (
275
+ service.events()
276
+ .list(
277
+ calendarId="primary",
278
+ timeMin=time_min,
279
+ timeMax=time_max,
280
+ singleEvents=True,
281
+ orderBy="startTime",
282
+ )
283
+ .execute()
284
+ )
285
+ events = events_result.get("items", [])
286
+
287
+ if not events:
288
+ print(f"No events found for {target_date}.")
289
+ else:
290
+ for event in events:
291
+ start = event["start"].get("dateTime", event["start"].get("date"))
292
+ result=start, event["summary"]
293
+ return result
294
+ except HttpError as error:
295
+ print(f"An error occurred: {error}")
296
+
297
+ @tool("book-slot-tool", args_schema=bookSlot, return_direct=True)
298
+ def book_slot(start_time, end_time, summary):
299
+ """
300
+ This functions is to boos a appointment/slot for user by creating an event on the calendar.
301
+
302
+ Args:
303
+ start_time (str): The start time of the slot (e.g., '2024-09-16T14:00:00+05:30').
304
+ end_time (str): The end time of the slot (e.g., '2024-09-16T15:00:00+05:30').
305
+ summary (str): Summary or title of the event.
306
+
307
+ Returns:
308
+ str: Confirmation message if the event is created or an error message if booking fails.
309
+ """
310
+ service = get_service()
311
+ is_valid, error_message = is_valid_booking_time(start_time)
312
+
313
+ if not is_valid:
314
+ # Return the error message with proper formatting
315
+ formatted_output = "❌ **Invalid Booking Time**\n\n"
316
+ formatted_output += f"{error_message}\n"
317
+ formatted_output += "\nAppointments can only be scheduled:\n"
318
+ formatted_output += "📅 Monday to Friday\n"
319
+ formatted_output += "🕒 Between 10 AM and 7 PM\n"
320
+ formatted_output += "📆 Within the next 7 days\n"
321
+ return formatted_output
322
+ if not check_slot_availability(start_time, end_time):
323
+ formatted_output = "❌ **Slot Unavailable**\n\n"
324
+ formatted_output += "\nThe requested slot is not available.\n"
325
+ formatted_output += "\nPlease choose another time."
326
+ return formatted_output
327
+
328
+ # Create the event object
329
+ event = {
330
+ 'summary': summary,
331
+ 'start': {
332
+ 'dateTime': start_time, # ISO 8601 format
333
+ 'timeZone': 'Asia/Kolkata', # Use appropriate timezone
334
+ },
335
+ 'end': {
336
+ 'dateTime': end_time,
337
+ 'timeZone': 'Asia/Kolkata',
338
+ },
339
+ }
340
+
341
+ try:
342
+ # Insert the event into the primary calendar
343
+ event_result = service.events().insert(calendarId='primary', body=event).execute()
344
+ formatted_output = "✅ **Event Created Successfully!**\n\n"
345
+ formatted_output += f"\n📌 **Summary:** {summary}\n"
346
+ formatted_output += f"\n🕒 **Start Time:** {start_time}\n"
347
+ formatted_output += f"\n🕒 **End Time:** {end_time}\n\n"
348
+ formatted_output += "\n📅 The event has been added to your primary calendar."
349
+ return formatted_output
350
+ except HttpError as error:
351
+ return f"❌ **An error occurred:** {error}\n\nPlease try again or contact support if the issue persists."
352
+
353
+ @tool("delete-slot-tool", args_schema=deleteSlot, return_direct=True)
354
+ def delete_event(start_time):
355
+ """
356
+ Deletes an event by start time on the user's calendar.
357
+
358
+ Args:
359
+ start_time (str): The start time of the event (e.g., '2024-09-20T15:30:00+05:30').
360
+
361
+ Returns:
362
+ str: Confirmation message if the event is deleted.
363
+ """
364
+ service = get_service()
365
+ event = find_event_by_time(start_time)
366
+
367
+ if event:
368
+ try:
369
+ service.events().delete(calendarId='primary', eventId=event['id']).execute()
370
+ formatted_output = "\n🗑️ **Event Deleted Successfully!**\n\n"
371
+ formatted_output += f"\n📌 **Summary:** {event['summary']}\n"
372
+ formatted_output += f"\n🕒 **Start Time:** {event['start']['dateTime']}\n\n"
373
+ formatted_output += "\nThe event has been removed from your primary calendar."
374
+ return formatted_output
375
+ except HttpError as error:
376
+ return f"❌ **An error occurred:** {error}\n\nPlease try again or contact support if the issue persists."
377
+ else:
378
+ formatted_output = "❓ **No Event Found**\n\n"
379
+ formatted_output += f"🕒 **\nRequested Start Time:** {start_time}\n\n"
380
+ formatted_output += "\nNo event was found for the specified time. Please check the time and try again."
381
+ return formatted_output
382
+
383
+
384
+ @tool("reschedule-event-tool", args_schema=reschedule_event, return_direct=True)
385
+ def reschedule_event(start_time, new_start_time, new_end_time):
386
+ """
387
+ Reschedules an existing event by providing new start and end times.
388
+
389
+ Args:
390
+ start_time (str): The start time of the existing event (e.g., '2024-09-18T14:00:00+05:30').
391
+ new_start_time (str): The new start time of the event (e.g., '2024-09-18T12:00:00+05:30').
392
+ new_end_time (str): The new end time of the event (e.g., '2024-09-18T14:00:00+05:30').
393
+
394
+ Returns:
395
+ str: Confirmation message if the event is rescheduled or an error message if rescheduling fails.
396
+ """
397
+ service = get_service()
398
+ if not is_valid_booking_time(start_time):
399
+ formatted_output = "❌ **Invalid Booking Time**\n\n"
400
+ formatted_output += "\nAppointments can only be scheduled:\n"
401
+ formatted_output += "\n📅 Monday to Friday\n"
402
+ formatted_output += "\n🕒 Between 10 AM and 7 PM\n"
403
+ formatted_output += "\n📆 Within the next 7 days\n"
404
+ return formatted_output
405
+
406
+ if not check_slot_availability(new_start_time, new_end_time):
407
+ formatted_output = "❌ **Slot Unavailable**\n\n"
408
+ formatted_output += "\nThe requested slot is not available.\n"
409
+ formatted_output += "\nPlease choose another time."
410
+ return formatted_output
411
+
412
+ try:
413
+ event = find_event_by_time(start_time)
414
+
415
+ if not event:
416
+ formatted_output = "❓ **No Event Found**\n\n"
417
+ formatted_output += f"\n🕒 **Requested Start Time:** {start_time}\n\n"
418
+ formatted_output += "\nNo event was found for the specified time. Please check the time and try again."
419
+ return formatted_output
420
+
421
+ event['start']['dateTime'] = new_start_time
422
+ event['end']['dateTime'] = new_end_time
423
+
424
+ updated_event = service.events().update(calendarId='primary', eventId=event['id'], body=event).execute()
425
+
426
+ formatted_output = "✅ **Event Rescheduled Successfully!**\n\n"
427
+ formatted_output += f"\n🔄 **Original Start Time:** {start_time}\n"
428
+ formatted_output += f"\n🆕 **New Start Time:** {new_start_time}\n"
429
+ formatted_output += f"\n🆕 **New End Time:** {new_end_time}\n\n"
430
+ formatted_output += "\nYour appointment has been updated in the calendar."
431
+ return formatted_output
432
+
433
+ except HttpError as error:
434
+ return f"❌ **An error occurred:** {error}\n\nPlease try again or contact support if the issue persists."
435
+
436
+
437
+ @tool("suggest-doctors-tool", return_direct=True)
438
+ def suggest_specialization(symptoms):
439
+ """This function understands user's symptoms and suggests specialization and doctor details.
440
+ Args:
441
+ symptoms (string): symptoms of patients/user
442
+ Returns:
443
+ string: Formatted string with specialization and doctor details
444
+ """
445
+ prompt_template = """
446
+ You are a highly knowledgeable Healthcare AI specialized in directing patients to the appropriate medical professionals.
447
+ Greet the user politely. Based on the symptoms provided below, suggest the most suitable doctor's specialization for the patient to visit.
448
+ Respond with only the name of the specialization in one word, without any additional explanations.
449
+
450
+ Here are a few examples for reference:
451
+ - Symptoms: skin rash, itching, dryness → Answer: "Dermatologist"
452
+ - Symptoms: chest pain, shortness of breath → Answer: "Cardiologist"
453
+ - Symptoms: joint pain, stiffness, swelling → Answer: "Rheumatologist"
454
+ - Symptoms: persistent cough, fever, sore throat → Answer: "Pulmonologist"
455
+ - Symptoms: frequent headaches, dizziness, vision problems → Answer: "Neurologist"
456
+
457
+ Now, based on the symptoms below, provide the specialization in one word.
458
+ Symptoms: {symptoms}
459
+ """
460
+ prompt = PromptTemplate(input_variables=["symptoms"], template=prompt_template)
461
+ chain = LLMChain(llm=llm, prompt=prompt)
462
+
463
+ try:
464
+ result = chain.run(symptoms=symptoms)
465
+ specialization = result.split('\n')[-1].strip().lower()
466
+
467
+ # Check if we have a match for the specialization in our doctor data
468
+ relevant_doctors = doctor_df[doctor_df['Specialization'].str.contains(specialization, case=False, na=False)]
469
+
470
+ if relevant_doctors.empty:
471
+ # If no match, fallback to suggesting a General Practitioner
472
+ return ("Based on your symptoms, I recommend consulting a General Practitioner. "
473
+ "Unfortunately, no specific doctors matching your symptoms were found in our database.")
474
+
475
+ # If doctors are found, format the details
476
+ formatted_output = f"Based on your symptoms, I recommend consulting an {specialization.capitalize()}.\n\n"
477
+ formatted_output += "Here are the details of a suitable doctor:\n\n"
478
+
479
+ doctor = relevant_doctors.iloc[0] # Get the first matching doctor
480
+ formatted_output += f"👨‍⚕️ **Doctor**: {doctor['Doctor Name']}\n"
481
+ formatted_output += f"\n🏥 **Specialization**: {doctor['Specialization']}\n"
482
+ formatted_output += f"\n📞 **Contact**: {doctor['Contact Number']}\n"
483
+ formatted_output += f"\n🏢 **Address**: {doctor['Address']}\n"
484
+
485
+ return formatted_output
486
+
487
+ except Exception as e:
488
+ # Fallback if an error occurs
489
+ return "I apologize, but I encountered an issue while processing your request. Please try describing your symptoms again, or consider consulting a General Practitioner for a comprehensive evaluation."
model.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from langchain_core.utils.function_calling import convert_to_openai_function
2
+ from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder
3
+ from langchain.memory import ConversationBufferWindowMemory
4
+ from langchain.schema.runnable import RunnablePassthrough
5
+ from langchain.agents.format_scratchpad import format_to_openai_functions
6
+ from langchain.agents.output_parsers import OpenAIFunctionsAgentOutputParser
7
+ from langchain.agents import AgentExecutor
8
+ from langchain_groq import ChatGroq
9
+ from functions import book_slot , check_slots , suggest_specialization , reschedule_event,delete_event
10
+
11
+ def create_agent(general_prompt_template):
12
+ # print("get user Id**********************",user_id)
13
+
14
+ API_KEY = "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"
15
+ tools = [book_slot , delete_event , check_slots , suggest_specialization , reschedule_event]
16
+ functions = [convert_to_openai_function(f) for f in tools]
17
+
18
+ llm = ChatGroq(
19
+ model="llama-3.1-70b-versatile",
20
+ temperature=0,
21
+ max_tokens=None,
22
+ timeout=None,
23
+ max_retries=2,
24
+ api_key=API_KEY
25
+ ).bind_functions(functions=functions)
26
+
27
+ prompt = ChatPromptTemplate.from_messages([("system", general_prompt_template),
28
+ MessagesPlaceholder(variable_name="chat_history"), ("user", "{input}"),
29
+ MessagesPlaceholder(variable_name="agent_scratchpad")])
30
+
31
+
32
+
33
+ memory = ConversationBufferWindowMemory(memory_key="chat_history" , return_messages=True, k=5)
34
+
35
+ chain = RunnablePassthrough.assign(agent_scratchpad=lambda x: format_to_openai_functions(x["intermediate_steps"])) | prompt | llm | OpenAIFunctionsAgentOutputParser()
36
+
37
+ agent_executor = AgentExecutor(
38
+ agent=chain, tools=tools, memory=memory, verbose=True)
39
+
40
+ return agent_executor
41
+ # give me available slots at 17 september 2024 , book schedule at 10:30 AM 17 september 2024 ,
requirements.txt ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ aiohappyeyeballs==2.4.0
2
+ aiohttp==3.10.5
3
+ aiosignal==1.3.1
4
+ altair==5.4.1
5
+ annotated-types==0.7.0
6
+ anyio==4.4.0
7
+ async-timeout==4.0.3
8
+ attrs==24.2.0
9
+ blinker==1.8.2
10
+ cachetools==5.5.0
11
+ certifi==2024.8.30
12
+ charset-normalizer==3.3.2
13
+ click==8.1.7
14
+ dataclasses-json==0.6.7
15
+ distro==1.9.0
16
+ exceptiongroup==1.2.2
17
+ frozenlist==1.4.1
18
+ gitdb==4.0.11
19
+ GitPython==3.1.43
20
+ google-api-core==2.19.2
21
+ google-api-python-client==2.144.0
22
+ google-auth==2.34.0
23
+ google-auth-httplib2==0.2.0
24
+ google-auth-oauthlib==1.2.1
25
+ googleapis-common-protos==1.65.0
26
+ greenlet==3.0.3
27
+ groq==0.11.0
28
+ h11==0.14.0
29
+ httpcore==1.0.5
30
+ httplib2==0.22.0
31
+ httpx==0.27.2
32
+ idna==3.8
33
+ Jinja2==3.1.4
34
+ jsonpatch==1.33
35
+ jsonpointer==3.0.0
36
+ jsonschema==4.23.0
37
+ jsonschema-specifications==2023.12.1
38
+ langchain==0.2.16
39
+ langchain-community==0.2.16
40
+ langchain-core==0.2.38
41
+ langchain-experimental==0.0.65
42
+ langchain-groq==0.1.9
43
+ langchain-text-splitters==0.2.4
44
+ langsmith==0.1.116
45
+ markdown-it-py==3.0.0
46
+ MarkupSafe==2.1.5
47
+ marshmallow==3.22.0
48
+ mdurl==0.1.2
49
+ multidict==6.0.5
50
+ mypy-extensions==1.0.0
51
+ narwhals==1.7.0
52
+ numpy==1.26.4
53
+ oauthlib==3.2.2
54
+ orjson==3.10.7
55
+ packaging==24.1
56
+ pandas==2.2.2
57
+ pillow==10.4.0
58
+ proto-plus==1.24.0
59
+ protobuf==5.28.0
60
+ pyarrow==17.0.0
61
+ pyasn1==0.6.0
62
+ pyasn1_modules==0.4.0
63
+ pydantic==2.9.0
64
+ pydantic_core==2.23.2
65
+ pydeck==0.9.1
66
+ Pygments==2.18.0
67
+ pyparsing==3.1.4
68
+ python-dateutil==2.9.0.post0
69
+ pytz==2024.1
70
+ PyYAML==6.0.2
71
+ referencing==0.35.1
72
+ requests==2.32.3
73
+ requests-oauthlib==2.0.0
74
+ rich==13.8.1
75
+ rpds-py==0.20.0
76
+ rsa==4.9
77
+ six==1.16.0
78
+ smmap==5.0.1
79
+ sniffio==1.3.1
80
+ SQLAlchemy==2.0.34
81
+ streamlit==1.38.0
82
+ tenacity==8.5.0
83
+ toml==0.10.2
84
+ tornado==6.4.1
85
+ typing-inspect==0.9.0
86
+ typing_extensions==4.12.2
87
+ tzdata==2024.1
88
+ uritemplate==4.1.1
89
+ urllib3==2.2.2
90
+ watchdog==4.0.2
91
+ yarl==1.11.0
schemas.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from langchain.pydantic_v1 import BaseModel, Field
2
+
3
+ class symptoms(BaseModel):
4
+ symptoms: str = Field(description="query of user")
5
+
6
+ class bookSlot(BaseModel):
7
+ start_time: str = Field(description="starting time of the slot with date use this format '2024-09-20T15:30:00+05:30'.")
8
+ end_time: str = Field(description="ending time of the slot with date use this format '2024-09-20T15:30:00+05:30'.")
9
+ summary: str = Field(description="summary of the event with title.")
10
+
11
+ class deleteSlot(BaseModel):
12
+ start_time: str = Field(description="starting time of the slot with date use this format '2024-09-20T15:30:00+05:30'.")
13
+
14
+ class reschedule_event(BaseModel):
15
+ start_time: str = Field(description="starting time of the slot with date that need to be reschedule use this format '2024-09-20T15:30:00+05:30'.")
16
+ new_start_time: str = Field(description="new starting time of the slot with date that need to be reschedule use this format '2024-09-20T15:30:00+05:30'.")
17
+ new_end_time: str = Field(description="ending time of the slot with date that need to be reschedule use this format '2024-09-20T15:30:00+05:30'.")
18
+
19
+ class listevent(BaseModel):
20
+ target_date: str = Field(description="Target date for which we want to list the events.")
21
+
22
+ class checkevent(BaseModel):
23
+ date: str = Field(description="Target date for which we want to check the events.")
24
+
token.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"token": "ya29.a0AcM612yIlulctbhGx8D-WJTGtWm9bjLUCZuQ54Uyhxr7PdrOmNBhUo8CYawxiNOq5ytT_5Y1m80vp_6hduLX4HDGlR-y6r3wrbWyoXTP5nMuyLAbNEGiW7IQogHLxdWTAspkBHZC_zZ1Cb3cvtftVfs6eaHbr8wiBLYZKhQyEAaCgYKAcUSARMSFQHGX2Mi5HFU3Yxjp6ukrkYA8I8ofA0177", "refresh_token": "1//0g1aFUrhQNn-WCgYIARAAGBASNwF-L9Ir_svA7VEve3hAfhp4Z9s1x1UIUpTvipEIXD_t9vcX9HSpN3_GW8IoKGlFVS9KKbZmz4I", "token_uri": "https://oauth2.googleapis.com/token", "client_id": "123736158724-1hf7onqa73dtlirlljc8nq17ecjlmash.apps.googleusercontent.com", "client_secret": "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", "scopes": ["https://www.googleapis.com/auth/calendar"], "universe_domain": "googleapis.com", "account": "", "expiry": "2024-09-17T07:31:09.908854Z"}