-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathcalendar_tools.py
More file actions
1470 lines (1247 loc) · 61.8 KB
/
calendar_tools.py
File metadata and controls
1470 lines (1247 loc) · 61.8 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
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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Tools for accessing Google Calendar events.
"""
import asyncio
import os
import contextvars
from datetime import datetime, timedelta, timezone
from typing import Optional
import httpx
from langchain_core.tools import tool
from langchain_core.runnables import RunnableConfig
import database.users as users_db
from utils.http_client import get_auth_client
from utils.retrieval.tools.integration_base import (
ensure_capped,
parse_iso_with_tz,
prepare_access,
)
from utils.retrieval.tools.google_utils import google_api_request, GoogleAPIError
# Import shared Google utilities
from utils.retrieval.tools.google_utils import refresh_google_token
from utils.log_sanitizer import sanitize, sanitize_pii
import logging
logger = logging.getLogger(__name__)
# Import the context variable from agentic module
try:
from utils.retrieval.agentic import agent_config_context
except ImportError:
# Fallback if import fails
agent_config_context = contextvars.ContextVar('agent_config', default=None)
async def search_google_contacts(access_token: str, query: str) -> Optional[str]:
"""
Search Google Contacts (People API) for a contact by name and return email address.
Searches both "My Contacts" and "Other Contacts" (auto-created from emails, calendar, etc.).
Args:
access_token: Google access token (can be from Calendar or Contacts)
query: Name to search for (e.g., "Riddhi Gupta")
Returns:
Email address if found, None otherwise
"""
client = get_auth_client()
# First, search in "My Contacts"
try:
response = await client.get(
'https://people.googleapis.com/v1/people:searchContacts',
headers={'Authorization': f'Bearer {access_token}'},
params={
'query': query,
'readMask': 'emailAddresses,names',
'pageSize': 10,
},
)
if response.status_code == 200:
data = response.json()
results = data.get('results', [])
if results:
# Get the first result's email
person = results[0].get('person', {})
email_addresses = person.get('emailAddresses', [])
if email_addresses:
email = email_addresses[0].get('value')
return email
elif response.status_code == 401:
logger.warning(f"❌ Google Contacts API 401 - token expired")
return None
elif response.status_code == 403:
# Will try Other Contacts
pass
else:
error_body = response.text[:200] if response.text else "No error body"
logger.error(f"⚠️ Google Contacts API error {response.status_code}: {sanitize(error_body)}")
except httpx.HTTPError as e:
logger.error(f"⚠️ Network error searching My Contacts: {e}")
except Exception as e:
logger.error(f"⚠️ Error searching My Contacts: {e}")
# If not found in My Contacts, search in "Other Contacts"
try:
# First, warm up the cache with an empty query (recommended by Google)
try:
warmup_response = await client.get(
'https://people.googleapis.com/v1/otherContacts:search',
headers={'Authorization': f'Bearer {access_token}'},
params={
'query': '',
'readMask': 'names,emailAddresses',
},
)
logger.info(f"📇 Other Contacts warm-up response status: {warmup_response.status_code}")
# Wait a moment for cache to update (not strictly necessary but recommended)
await asyncio.sleep(0.5)
except Exception as warmup_error:
logger.error(f"⚠️ Other Contacts warm-up failed (non-critical): {warmup_error}")
# Now perform the actual search
response = await client.get(
'https://people.googleapis.com/v1/otherContacts:search',
headers={'Authorization': f'Bearer {access_token}'},
params={
'query': query,
'readMask': 'names,emailAddresses',
},
)
logger.info(f"📇 Google Contacts API (Other Contacts) response status: {response.status_code}")
if response.status_code == 200:
data = response.json()
results = data.get('results', [])
if results:
# Get the first result's email
person = results[0].get('person', {})
email_addresses = person.get('emailAddresses', [])
if email_addresses:
email = email_addresses[0].get('value')
name = person.get('names', [{}])[0].get('displayName', query)
logger.info(f"✅ Found contact in Other Contacts: {sanitize_pii(name)} -> {sanitize_pii(email)}")
return email
else:
logger.info(f"⚠️ Found contact '{sanitize_pii(query)}' in Other Contacts but no email address")
else:
logger.info(f"⚠️ No contacts found in Other Contacts for: {sanitize_pii(query)}")
elif response.status_code == 401:
logger.warning(f"❌ Google Contacts API 401 - token expired")
return None
elif response.status_code == 403:
logger.info(f"❌ Google Contacts API 403 - insufficient permissions (Other Contacts access required)")
return None
else:
error_body = response.text[:200] if response.text else "No error body"
logger.error(
f"⚠️ Google Contacts API (Other Contacts) error {response.status_code}: {sanitize(error_body)}"
)
except httpx.HTTPError as e:
logger.error(f"⚠️ Network error searching Other Contacts: {e}")
except Exception as e:
logger.error(f"⚠️ Error searching Other Contacts: {e}")
logger.info(f"⚠️ No contacts found in My Contacts or Other Contacts for: {sanitize_pii(query)}")
return None
async def resolve_attendee_to_email(access_token: str, attendee: str) -> Optional[str]:
"""
Resolve an attendee string to an email address.
If it's already an email, return it. If it's a name, search Google Contacts.
Args:
access_token: Google access token
attendee: Either an email address or a name
Returns:
Email address or None if not found
"""
# Check if it's already an email address (simple check)
if '@' in attendee and '.' in attendee.split('@')[1]:
# Looks like an email, return as-is
logger.info(f"📧 '{sanitize_pii(attendee)}' appears to be an email address")
return attendee
# It's a name, search Google Contacts
logger.info(f"👤 '{sanitize_pii(attendee)}' appears to be a name, searching Google Contacts...")
return await search_google_contacts(access_token, attendee)
async def create_google_calendar_event(
access_token: str,
summary: str,
start_time: datetime,
end_time: datetime,
description: Optional[str] = None,
location: Optional[str] = None,
attendees: Optional[list] = None,
) -> dict:
"""
Create a new event in Google Calendar.
Args:
access_token: Google Calendar access token
summary: Event title/summary
start_time: Event start time (datetime with timezone)
end_time: Event end time (datetime with timezone)
description: Optional event description
location: Optional event location
attendees: Optional list of attendee email addresses
Returns:
Created event data
"""
# Convert to UTC if timezone-aware, otherwise assume UTC
if start_time.tzinfo is not None:
start_time_utc = start_time.astimezone(timezone.utc)
else:
start_time_utc = start_time.replace(tzinfo=timezone.utc)
if end_time.tzinfo is not None:
end_time_utc = end_time.astimezone(timezone.utc)
else:
end_time_utc = end_time.replace(tzinfo=timezone.utc)
# Format times in RFC3339 format (UTC)
start_time_str = start_time_utc.strftime('%Y-%m-%dT%H:%M:%SZ')
end_time_str = end_time_utc.strftime('%Y-%m-%dT%H:%M:%SZ')
# Build event body
event_body = {
'summary': summary,
'start': {
'dateTime': start_time_str,
'timeZone': 'UTC',
},
'end': {
'dateTime': end_time_str,
'timeZone': 'UTC',
},
}
if description:
event_body['description'] = description
if location:
event_body['location'] = location
if attendees:
event_body['attendees'] = [{'email': email} for email in attendees]
logger.info(f"📅 Creating Google Calendar event: {summary} from {start_time_str} to {end_time_str}")
event = await google_api_request(
"POST",
'https://www.googleapis.com/calendar/v3/calendars/primary/events',
access_token,
body=event_body,
)
return event
async def get_google_calendar_event(access_token: str, event_id: str) -> dict:
"""
Get a single calendar event by event ID.
Args:
access_token: Google Calendar access token
event_id: Event ID to retrieve
Returns:
Event data
"""
logger.info(f"📅 Getting Google Calendar event: {event_id}")
event_data = await google_api_request(
"GET",
f'https://www.googleapis.com/calendar/v3/calendars/primary/events/{event_id}',
access_token,
)
return event_data
async def update_google_calendar_event(
access_token: str,
event_id: str,
summary: Optional[str] = None,
start_time: Optional[datetime] = None,
end_time: Optional[datetime] = None,
description: Optional[str] = None,
location: Optional[str] = None,
attendees: Optional[list] = None,
) -> dict:
"""
Update an existing calendar event.
Args:
access_token: Google Calendar access token
event_id: Event ID to update
summary: Optional new event title/summary
start_time: Optional new start time (datetime with timezone)
end_time: Optional new end time (datetime with timezone)
description: Optional new description
location: Optional new location
attendees: Optional new list of attendee email addresses (replaces existing attendees)
Returns:
Updated event data
"""
logger.info(f"📅 Updating Google Calendar event: {event_id}")
# Build update body with only provided fields
event_body = {}
if summary is not None:
event_body['summary'] = summary
if start_time is not None:
if start_time.tzinfo is not None:
start_time_utc = start_time.astimezone(timezone.utc)
else:
start_time_utc = start_time.replace(tzinfo=timezone.utc)
start_time_str = start_time_utc.strftime('%Y-%m-%dT%H:%M:%SZ')
event_body['start'] = {
'dateTime': start_time_str,
'timeZone': 'UTC',
}
if end_time is not None:
if end_time.tzinfo is not None:
end_time_utc = end_time.astimezone(timezone.utc)
else:
end_time_utc = end_time.replace(tzinfo=timezone.utc)
end_time_str = end_time_utc.strftime('%Y-%m-%dT%H:%M:%SZ')
event_body['end'] = {
'dateTime': end_time_str,
'timeZone': 'UTC',
}
if description is not None:
event_body['description'] = description
if location is not None:
event_body['location'] = location
if attendees is not None:
event_body['attendees'] = [{'email': email} for email in attendees]
if not event_body:
raise Exception("No fields provided to update")
logger.info(f"📅 Updating event with fields: {list(event_body.keys())}")
updated = await google_api_request(
"PATCH",
f'https://www.googleapis.com/calendar/v3/calendars/primary/events/{event_id}',
access_token,
body=event_body,
)
return updated
async def delete_google_calendar_event(access_token: str, event_id: str) -> bool:
"""
Delete a calendar event by event ID.
Args:
access_token: Google Calendar access token
event_id: Event ID to delete
Returns:
True if deleted successfully, False otherwise
"""
logger.info(f"🗑️ Deleting Google Calendar event: {event_id}")
await google_api_request(
"DELETE",
f'https://www.googleapis.com/calendar/v3/calendars/primary/events/{event_id}',
access_token,
allow_204=True,
)
return True
async def get_google_calendar_events(
access_token: str,
time_min: Optional[datetime] = None,
time_max: Optional[datetime] = None,
max_results: int = 10,
search_query: Optional[str] = None,
) -> list:
"""
Fetch events from Google Calendar API.
Args:
access_token: Google Calendar access token
time_min: Minimum time for events (defaults to now)
time_max: Maximum time for events (defaults to 7 days from now)
max_results: Maximum number of events to return
search_query: Optional search query to filter events by title, description, attendees, etc.
Returns:
List of calendar events
"""
now = datetime.now(timezone.utc)
time_min = (time_min or now).astimezone(timezone.utc)
time_max = (time_max or (time_min + timedelta(days=7))).astimezone(timezone.utc)
# Format times in RFC3339 format (UTC)
time_min_str = time_min.strftime('%Y-%m-%dT%H:%M:%SZ')
time_max_str = time_max.strftime('%Y-%m-%dT%H:%M:%SZ')
params = {
'timeMin': time_min_str,
'timeMax': time_max_str,
'singleEvents': 'true',
'orderBy': 'startTime',
'maxResults': 2500,
}
if search_query:
params['q'] = search_query
events = []
page = None
while True:
if page:
params['pageToken'] = page
data = await google_api_request(
"GET",
'https://www.googleapis.com/calendar/v3/calendars/primary/events',
access_token,
params=params,
)
events.extend(data.get('items', []))
if len(events) >= max_results:
return events[:max_results]
page = data.get('nextPageToken')
if not page:
break
return events[:max_results]
@tool
async def get_calendar_events_tool(
start_date: Optional[str] = None,
end_date: Optional[str] = None,
max_results: int = 10,
search_query: Optional[str] = None,
config: RunnableConfig = None,
) -> str:
"""
Retrieve calendar events from the user's Google Calendar.
Use this tool when:
- User asks "what's on my calendar?" or "show me my events"
- User asks about upcoming meetings or appointments
- User wants to know what they have scheduled for a specific day/week
- User asks "do I have anything scheduled?" or "what's coming up?"
- User mentions checking their calendar or schedule
- **ALWAYS use this tool when the user asks about their calendar or events**
- **When user asks about a specific person (e.g., "when did I meet with Andy?") or topic, use search_query parameter**
Date formatting:
- Dates should be in ISO format with timezone: YYYY-MM-DDTHH:MM:SS+HH:MM
- Example: "2024-01-20T00:00:00-08:00" for January 20, 2024 at midnight in PST
- If start_date is not provided, defaults to now
- If end_date is not provided, defaults to 7 days from start_date
Search query:
- Use search_query when user asks about a specific person, company, or topic
- Examples: "Andy", "Deepgram", "project review", "team meeting"
- Searches in event title, description, and attendees
- For person names, use just the first name or full name (e.g., "Andy" or "Andy Smith")
Args:
start_date: Start date/time for events in ISO format with timezone (YYYY-MM-DDTHH:MM:SS+HH:MM, e.g. "2024-01-20T00:00:00-08:00"). Defaults to now if not provided.
end_date: End date/time for events in ISO format with timezone (YYYY-MM-DDTHH:MM:SS+HH:MM, e.g. "2024-01-27T23:59:59-08:00"). Defaults to 7 days from start_date if not provided.
max_results: Maximum number of events to return (default: 10, max: 50)
search_query: Optional search term to filter events (e.g., person name like "Andy", company name like "Deepgram", or topic). Searches in event title, description, and attendees.
Returns:
Formatted list of calendar events with their details.
"""
uid, integration, access_token, access_err = prepare_access(
config,
'google_calendar',
'Google Calendar',
'Google Calendar is not connected. Please connect your Google Calendar from settings to view your events.',
'Google Calendar access token not found. Please reconnect your Google Calendar from settings.',
'Error checking Google Calendar connection',
)
if access_err:
return access_err
try:
max_results = ensure_capped(max_results, 50, "⚠️ get_calendar_events_tool - max_results capped from {} to {}")
# Parse dates if provided
time_min = None
time_max = None
time_min, err = parse_iso_with_tz(
'start_date',
start_date,
"in format YYYY-MM-DDTHH:MM:SS+HH:MM (e.g., '2024-01-20T00:00:00-08:00')",
)
if err:
return err
time_max, err = parse_iso_with_tz(
'end_date',
end_date,
"in format YYYY-MM-DDTHH:MM:SS+HH:MM (e.g., '2024-01-27T23:59:59-08:00')",
)
if err:
return err
# If search_query is provided, expand date range to ensure we don't miss events
# Default to searching back 1 year if no dates provided, or expand range if dates are too narrow
if search_query:
now = datetime.now(timezone.utc)
if time_max is None:
time_max = now
if time_min is None:
# Default to 1 year back when searching
time_min = time_max - timedelta(days=365)
logger.info(
f"📅 search_query provided, defaulting to 1 year range: {time_min.strftime('%Y-%m-%d')} to {time_max.strftime('%Y-%m-%d')}"
)
else:
# If dates are provided but range is less than 6 months, expand to at least 6 months
days_range = (time_max - time_min).days
if days_range < 180: # Less than 6 months
# Expand backwards from time_max to ensure at least 6 months
time_min = time_max - timedelta(days=180)
logger.info(
f"📅 search_query provided, expanding date range to 6 months: {time_min.strftime('%Y-%m-%d')} to {time_max.strftime('%Y-%m-%d')}"
)
elif days_range < 365: # Less than 1 year, expand to 1 year
time_min = time_max - timedelta(days=365)
logger.info(
f"📅 search_query provided, expanding date range to 1 year: {time_min.strftime('%Y-%m-%d')} to {time_max.strftime('%Y-%m-%d')}"
)
# Fetch events with smart date range handling
try:
# Calculate date range
days_range = (time_max - time_min).days if time_min and time_max else 0
# If search_query is provided, use single API call (server-side filtering is efficient)
# Otherwise, for large date ranges (>30 days), use iterative search
if search_query:
# With search_query, Google Calendar API filters server-side, so we can search entire range at once
logger.info(f"📅 search_query provided, using single API call for {days_range} day range")
events = await get_google_calendar_events(
access_token=access_token,
time_min=time_min,
time_max=time_max,
max_results=max_results,
search_query=search_query,
)
elif days_range > 30:
logger.info(
f"📅 Large date range ({days_range} days), using iterative search starting from most recent"
)
# Start with last 30 days, then expand backwards month by month
all_events = []
search_end = time_max
months_back = 0
max_months = 6 # Don't search more than 6 months back
while months_back < max_months and len(all_events) < max_results:
# Calculate search window: go back 30 days from current end
search_start = search_end - timedelta(days=30)
# Don't go before the original time_min
if time_min and search_start < time_min:
search_start = time_min
logger.info(
f"📅 Searching window {months_back + 1}: {search_start.strftime('%Y-%m-%d')} to {search_end.strftime('%Y-%m-%d')}"
)
# Fetch events for this window
window_events = await get_google_calendar_events(
access_token=access_token,
time_min=search_start,
time_max=search_end,
max_results=max_results, # Fetch enough for this window
search_query=search_query,
)
# Add events to our collection (they're already sorted chronologically)
all_events.extend(window_events)
# If we've reached the original time_min or got enough events, stop
if (time_min and search_start <= time_min) or len(all_events) >= max_results:
break
# Move search window backwards
search_end = search_start
months_back += 1
# Sort all events by start time (most recent first) and take max_results
events_with_time = []
for event in all_events:
start = event.get('start', {})
if 'dateTime' in start:
try:
start_dt = datetime.fromisoformat(start['dateTime'].replace('Z', '+00:00'))
events_with_time.append((start_dt, event))
except:
events_with_time.append((datetime.min.replace(tzinfo=timezone.utc), event))
elif 'date' in start:
try:
start_dt = datetime.fromisoformat(start['date'] + 'T00:00:00+00:00')
events_with_time.append((start_dt, event))
except:
events_with_time.append((datetime.min.replace(tzinfo=timezone.utc), event))
else:
events_with_time.append((datetime.min.replace(tzinfo=timezone.utc), event))
# Sort by start time descending (most recent first) and take max_results
events_with_time.sort(key=lambda x: x[0], reverse=True)
events = [event for _, event in events_with_time[:max_results]]
logger.info(
f"📅 Found {len(events)} most recent events from {len(all_events)} total across {months_back + 1} search windows"
)
else:
# For smaller ranges (<=30 days), fetch normally
logger.info(f"📅 Fetching calendar events with time_min={time_min}, time_max={time_max}")
events = await get_google_calendar_events(
access_token=access_token,
time_min=time_min,
time_max=time_max,
max_results=max_results,
search_query=search_query,
)
except GoogleAPIError as e:
logger.error(f"❌ Google API error fetching calendar events: status={e.status_code}, msg={e.message}")
if e.is_auth_error:
logger.info(f"🔄 Attempting to refresh Google Calendar token...")
new_token = await refresh_google_token(uid, integration)
if new_token:
try:
events = await get_google_calendar_events(
access_token=new_token,
time_min=time_min,
time_max=time_max,
max_results=max_results,
search_query=search_query,
)
except Exception as retry_error:
logger.error(f"❌ Error after token refresh: {retry_error}")
return f"Error fetching calendar events: {retry_error}"
else:
logger.error(f"❌ Token refresh failed")
return (
"Google Calendar authentication expired. Please reconnect your Google Calendar from settings."
)
elif e.is_permission_error:
return "Google Calendar access denied. Please reconnect your Google Calendar from settings with proper permissions."
else:
return f"Error fetching calendar events: {e.message}"
except (httpx.TimeoutException, httpx.ConnectError) as e:
logger.error(f"❌ Network error fetching calendar events: {e}")
return "Unable to reach Google Calendar right now. Please try again in a moment."
except Exception as e:
logger.error(f"❌ Unexpected error fetching calendar events: {e}")
return f"Error fetching calendar events: {e}"
events_count = len(events) if events else 0
if not events:
date_info = ""
if time_min and time_max:
date_info = f" between {time_min.strftime('%Y-%m-%d')} and {time_max.strftime('%Y-%m-%d')}"
elif time_min:
date_info = f" after {time_min.strftime('%Y-%m-%d')}"
elif time_max:
date_info = f" before {time_max.strftime('%Y-%m-%d')}"
return f"No calendar events found{date_info}."
# Format events
result = f"Calendar Events ({len(events)} found):\n\n"
for i, event in enumerate(events, 1):
summary = event.get('summary', 'No title')
result += f"{i}. {summary}\n"
# Parse start time
start = event.get('start', {})
if 'dateTime' in start:
try:
start_dt = datetime.fromisoformat(start['dateTime'].replace('Z', '+00:00'))
result += f" Start: {start_dt.strftime('%Y-%m-%d %H:%M:%S %Z')}\n"
except:
result += f" Start: {start.get('dateTime', 'Unknown')}\n"
elif 'date' in start:
result += f" Date: {start.get('date', 'Unknown')}\n"
# Parse end time
end = event.get('end', {})
if 'dateTime' in end:
try:
end_dt = datetime.fromisoformat(end['dateTime'].replace('Z', '+00:00'))
result += f" End: {end_dt.strftime('%Y-%m-%d %H:%M:%S %Z')}\n"
except:
result += f" End: {end.get('dateTime', 'Unknown')}\n"
elif 'date' in end:
result += f" End Date: {end.get('date', 'Unknown')}\n"
# Add location if available
location = event.get('location')
if location:
result += f" Location: {location}\n"
# Add description if available (truncated)
description = event.get('description', '')
if description:
desc_preview = description[:100] + '...' if len(description) > 100 else description
result += f" Description: {desc_preview}\n"
result += "\n"
return result.strip()
except Exception as e:
logger.error(f"❌ Unexpected error in get_calendar_events_tool: {e}")
import traceback
traceback.print_exc()
return f"Unexpected error fetching calendar events: {str(e)}"
@tool
async def create_calendar_event_tool(
title: str,
start_time: str,
end_time: str,
description: Optional[str] = None,
location: Optional[str] = None,
attendees: Optional[str] = None,
config: RunnableConfig = None,
) -> str:
"""
Create a new calendar event in the user's Google Calendar.
Use this tool when:
- User asks to "create a calendar event" or "schedule a meeting"
- User says "add to my calendar" or "put this on my calendar"
- User wants to "book a meeting" or "set up an appointment"
- User mentions creating an event, meeting, or appointment
- **ALWAYS use this tool when the user wants to create or schedule a calendar event**
Date/time formatting:
- Times should be in ISO format with timezone: YYYY-MM-DDTHH:MM:SS+HH:MM
- Example: "2024-01-20T14:00:00-08:00" for January 20, 2024 at 2:00 PM PST
- Both start_time and end_time are required
Attendees:
- Attendees can be provided as email addresses OR names (e.g., "john@example.com" or "John Smith")
- If names are provided, the system will automatically search Google Contacts to find their email addresses
- Multiple attendees should be comma-separated: "email1@example.com,John Smith,email2@example.com"
- If no attendees, leave as None or empty string
Args:
title: Event title/summary (required)
start_time: Event start time in ISO format with timezone (YYYY-MM-DDTHH:MM:SS+HH:MM, e.g. "2024-01-20T14:00:00-08:00")
end_time: Event end time in ISO format with timezone (YYYY-MM-DDTHH:MM:SS+HH:MM, e.g. "2024-01-20T15:00:00-08:00")
description: Optional event description
location: Optional event location (address or venue name)
attendees: Optional comma-separated list of attendee names or email addresses (e.g., "user1@example.com,John Smith,Riddhi Gupta")
Returns:
Confirmation message with event details if successful, or error message if failed.
"""
logger.info(
f"🔧 create_calendar_event_tool called - title: {title}, "
f"start_time: {start_time}, end_time: {end_time}, location: {location}"
)
uid, integration, access_token, access_err = prepare_access(
config,
'google_calendar',
'Google Calendar',
'Google Calendar is not connected. Please connect your Google Calendar from settings to create events.',
'Google Calendar access token not found. Please reconnect your Google Calendar from settings.',
'Error checking Google Calendar connection',
)
if access_err:
return access_err
try:
# Parse start and end times
try:
start_dt = datetime.fromisoformat(start_time.replace('Z', '+00:00'))
if start_dt.tzinfo is None:
return f"Error: start_time must include timezone in format YYYY-MM-DDTHH:MM:SS+HH:MM (e.g., '2024-01-20T14:00:00-08:00'): {start_time}"
logger.info(f"📅 Parsed start_time '{start_time}' as {start_dt.strftime('%Y-%m-%d %H:%M:%S %Z')}")
except ValueError as e:
return f"Error: Invalid start_time format. Expected YYYY-MM-DDTHH:MM:SS+HH:MM: {start_time} - {str(e)}"
try:
end_dt = datetime.fromisoformat(end_time.replace('Z', '+00:00'))
if end_dt.tzinfo is None:
return f"Error: end_time must include timezone in format YYYY-MM-DDTHH:MM:SS+HH:MM (e.g., '2024-01-20T15:00:00-08:00'): {end_time}"
logger.info(f"📅 Parsed end_time '{end_time}' as {end_dt.strftime('%Y-%m-%d %H:%M:%S %Z')}")
except ValueError as e:
return f"Error: Invalid end_time format. Expected YYYY-MM-DDTHH:MM:SS+HH:MM: {end_time} - {str(e)}"
# Validate that end_time is after start_time
if end_dt <= start_dt:
return f"Error: end_time must be after start_time. Start: {start_dt.strftime('%Y-%m-%d %H:%M:%S')}, End: {end_dt.strftime('%Y-%m-%d %H:%M:%S')}"
# Parse and resolve attendees if provided
attendee_list = None
if attendees:
attendee_strings = [a.strip() for a in attendees.split(',') if a.strip()]
logger.info(f"📅 Parsed {len(attendee_strings)} attendee(s)")
# Resolve each attendee (name or email) to an email address
resolved_emails = []
unresolved_attendees = []
for attendee in attendee_strings:
email = await resolve_attendee_to_email(access_token, attendee)
if email:
resolved_emails.append(email)
else:
unresolved_attendees.append(attendee)
if unresolved_attendees:
return f"Error: Could not find email addresses for the following attendees: {', '.join(unresolved_attendees)}. Please provide email addresses directly (e.g., 'name@example.com') or ensure these contacts exist in your Google Contacts. If you recently connected Google Calendar, you may need to reconnect it to enable contact lookup."
if resolved_emails:
attendee_list = resolved_emails
# Create the event
try:
event = await create_google_calendar_event(
access_token=access_token,
summary=title,
start_time=start_dt,
end_time=end_dt,
description=description,
location=location,
attendees=attendee_list,
)
event_id = event.get('id', 'unknown')
event_link = event.get('htmlLink', '')
result = f"✅ Successfully created calendar event: {title}\n"
result += f" Start: {start_dt.strftime('%Y-%m-%d %H:%M:%S %Z')}\n"
result += f" End: {end_dt.strftime('%Y-%m-%d %H:%M:%S %Z')}\n"
if location:
result += f" Location: {location}\n"
if attendee_list:
result += f" Attendees: {', '.join(attendee_list)}\n"
if event_link:
result += f" View event: {event_link}"
return result.strip()
except GoogleAPIError as e:
logger.error(f"❌ Google API error creating calendar event: status={e.status_code}, msg={e.message}")
if e.is_auth_error:
logger.info(f"🔄 Attempting to refresh Google Calendar token...")
new_token = await refresh_google_token(uid, integration)
if new_token:
try:
event = await create_google_calendar_event(
access_token=new_token,
summary=title,
start_time=start_dt,
end_time=end_dt,
description=description,
location=location,
attendees=attendee_list,
)
event_id = event.get('id', 'unknown')
event_link = event.get('htmlLink', '')
result = f"✅ Successfully created calendar event: {title}\n"
result += f" Start: {start_dt.strftime('%Y-%m-%d %H:%M:%S %Z')}\n"
result += f" End: {end_dt.strftime('%Y-%m-%d %H:%M:%S %Z')}\n"
if location:
result += f" Location: {location}\n"
if attendee_list:
result += f" Attendees: {', '.join(attendee_list)}\n"
if event_link:
result += f" View event: {event_link}"
return result.strip()
except Exception as retry_error:
logger.error(f"❌ Error after token refresh: {retry_error}")
return f"Error creating calendar event: {retry_error}"
else:
logger.error(f"❌ Token refresh failed")
return (
"Google Calendar authentication expired. Please reconnect your Google Calendar from settings."
)
elif e.is_permission_error:
return "Google Calendar write access is not available. Please reconnect your Google Calendar from settings with proper permissions."
else:
return f"Error creating calendar event: {e.message}"
except (httpx.TimeoutException, httpx.ConnectError) as e:
logger.error(f"❌ Network error creating calendar event: {e}")
return "Unable to reach Google Calendar right now. Please try again in a moment."
except Exception as e:
logger.error(f"❌ Unexpected error in create_calendar_event_tool: {e}")
import traceback
traceback.print_exc()
return f"Unexpected error creating calendar event: {str(e)}"
@tool
async def delete_calendar_event_tool(
event_title: Optional[str] = None,
start_date: Optional[str] = None,
end_date: Optional[str] = None,
event_id: Optional[str] = None,
config: RunnableConfig = None,
) -> str:
"""
Delete calendar events from the user's Google Calendar.
Use this tool when:
- User asks to "delete" or "remove" a calendar event
- User says "cancel" a meeting or event
- User wants to "clear" events from their calendar
- User mentions deleting or removing something from their schedule
- **ALWAYS use this tool when the user wants to delete calendar events**
You can delete events by:
1. Event ID (if you have it from a previous search)
2. Event title and date range (searches for matching events and deletes them)
3. Date range only (deletes all events in that range - use carefully)
Date/time formatting:
- Dates should be in ISO format with timezone: YYYY-MM-DDTHH:MM:SS+HH:MM
- Example: "2024-01-20T18:00:00-08:00" for January 20, 2024 at 6:00 PM PST
- If searching by date, provide both start_date and end_date to narrow the search
Args:
event_title: Optional event title to search for (e.g., "business meeting")
start_date: Optional start date/time for search range in ISO format with timezone (YYYY-MM-DDTHH:MM:SS+HH:MM)
end_date: Optional end date/time for search range in ISO format with timezone (YYYY-MM-DDTHH:MM:SS+HH:MM)
event_id: Optional specific event ID to delete (if known from previous search)
Returns:
Confirmation message with details of deleted events, or error message if failed.
"""
logger.info(
f"🔧 delete_calendar_event_tool called - event_title: {event_title}, "
f"start_date: {start_date}, end_date: {end_date}, event_id: {event_id}"
)
uid, integration, access_token, access_err = prepare_access(
config,
'google_calendar',
'Google Calendar',
'Google Calendar is not connected. Please connect your Google Calendar from settings to delete events.',
'Google Calendar access token not found. Please reconnect your Google Calendar from settings.',
'Error checking Google Calendar connection',
)
if access_err:
return access_err
try:
# If event_id is provided, delete directly
if event_id:
try:
await delete_google_calendar_event(access_token, event_id)
return f"✅ Successfully deleted calendar event (ID: {event_id})"
except GoogleAPIError as e:
logger.error(f"❌ Google API error deleting event by ID: status={e.status_code}, msg={e.message}")
if e.is_auth_error:
logger.info(f"🔄 Attempting to refresh Google Calendar token...")
new_token = await refresh_google_token(uid, integration)
if new_token:
try:
await delete_google_calendar_event(new_token, event_id)
return f"✅ Successfully deleted calendar event (ID: {event_id})"
except Exception as retry_error:
return f"Error deleting calendar event: {retry_error}"
else:
return "Google Calendar authentication expired. Please reconnect your Google Calendar from settings."
elif e.is_permission_error: