-
Notifications
You must be signed in to change notification settings - Fork 278
Expand file tree
/
Copy pathmain.py
More file actions
3159 lines (2960 loc) · 127 KB
/
main.py
File metadata and controls
3159 lines (2960 loc) · 127 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
"""Micro Adventure Planner ability for OpenHome (no booking flow)."""
import asyncio
import datetime
import json
import re
from typing import Optional
import httpx
from src.agent.capability import MatchingCapability
from src.agent.capability_worker import CapabilityWorker
from src.main import AgentWorker
PREFS_FILE = "micro_adventure_prefs.json"
ITINERARY_FILE = "micro_adventure_itineraries.json"
HISTORY_FILE = "micro_adventure_history.json"
EXIT_WORDS = {
"stop",
"exit",
"quit",
"cancel",
"bye",
"goodbye",
"done",
"no thanks",
"leave",
}
VALID_MODES = {
"plan",
"refine",
"city",
"calendar",
"save",
"history",
"tips",
"notion",
"clarify",
"exit",
}
VALID_FOCUS = {"activities", "lodging", "transport", "food", "sights", "mixed"}
_IDLE_WARN = 2
_IDLE_MAX = 3
CITY_STOP_WORDS = {
"tonight",
"tomorrow",
"today",
"weekend",
"now",
"please",
"under",
"budget",
"low",
"medium",
"high",
"cheap",
"indoor",
"outdoor",
"quiet",
"social",
"active",
"romantic",
"family",
"plan",
"ideas",
"activity",
"activities",
"adventure",
"micro",
"for",
"this",
"next",
}
LODGING_WORDS = {
"hotel",
"hotels",
"motel",
"motels",
"stay",
"stays",
"accommodation",
"hostel",
"resort",
}
TRANSPORT_WORDS = {
"transport",
"transportation",
"bus",
"train",
"flight",
"flights",
"taxi",
"uber",
"car",
"rent",
"rental",
}
FOOD_WORDS = {
"food",
"restaurant",
"restaurants",
"eat",
"eating",
"dining",
"cafe",
"cafes",
"street food",
"cuisine",
"lunch",
"dinner",
"breakfast",
"brunch",
"snack",
}
SIGHTS_WORDS = {
"sights",
"attractions",
"landmarks",
"monument",
"monuments",
"museum",
"museums",
"sightseeing",
"tourist",
"places to see",
"must see",
"must-see",
"iconic",
}
SERPER_API_KEY = "" # Set your key here or in micro_adventure_prefs.json
TICKETMASTER_API_KEY = "" # Set your key here or in micro_adventure_prefs.json
NOTION_API_KEY = "" # Set your key here or in micro_adventure_prefs.json
NOTION_DATABASE_ID = (
"" # Set your Notion database ID here or in micro_adventure_prefs.json
)
NOTION_PAGES_URL = "https://api.notion.com/v1/pages"
NOTION_VERSION = "2022-06-28"
DEFAULT_PREFS = {
"home_city": None,
"home_country_code": "", # ISO 3166-1 alpha-2 (e.g. 'EG', 'US') -- set during IP detection
"home_country_name": "", # Full country name (e.g. 'Saudi Arabia') -- set during IP detection
"home_region_name": "", # Region/governorate (e.g. 'Cairo') -- set during IP detection
"api_key_serper": SERPER_API_KEY,
"api_key_ticketmaster": TICKETMASTER_API_KEY,
"default_budget": "medium",
"default_vibe": "balanced",
"default_indoor": "any",
"notion_api_key": NOTION_API_KEY,
"notion_database_id": NOTION_DATABASE_ID,
}
_INTENT_TEMPLATE = """You classify voice input for a micro-adventure planning assistant.
The input comes from speech-to-text and MAY CONTAIN garbled/misspelled words.
Look past the noise and infer the user's real intent.
Return ONLY valid JSON on one line.
Modes:
- plan: user asks to create/find/suggest activities, food, sights, or plans
- refine: user asks to change previous options (cheaper, indoor, outdoor, closer, quieter, more active, etc.)
- city: user sets/changes their default/home city (e.g. "city is Cairo", "set city to Paris", "I live in London")
- calendar: user asks to add a plan/event to their calendar
- save: user wants to save/bookmark/keep current plans for later
- history: user asks about past trips, saved itineraries, or what they've done before
- tips: user asks for travel tips, packing advice, currency info, language help, or "what to pack"
- notion: user wants to post, share, send, add, or save the plan to Notion.
STT often garbles "Notion" into "no shin", "no sjenn", "no chen", "noshon", "motion", "ocean".
If you see an action word (post/save/send/share/put/add) combined with anything that sounds
like "notion" (even badly mangled), choose mode=notion.
- clarify: genuinely unclear input that you cannot classify
- exit: user wants to stop, leave, quit, or says goodbye
trip_type rules (IMPORTANT - apply these before deciding city):
- Set trip_type to "outing" when the user wants ANY short local activity with NO named travel destination:
Food/drink: "I wanna go eat", "find a restaurant", "grab lunch", "coffee shop", "I'm hungry"
Sports/activity: "I wanna play paddle", "let's go hiking", "find a gym", "go swimming", "play tennis"
Entertainment: "find a movie", "go to a park", "visit a museum", "catch a show", "go bowling"
General: "something to do nearby", "explore locally", "get out of the house", "go somewhere fun"
Rule: if no city is named AND it sounds like a self-contained local outing, use trip_type=outing.
For outing: set city=null (rely on stored home city), time_context="today"
- Set trip_type to "travel" when the user clearly wants to go somewhere away (city named, or overnight/multi-day trip)
- Set trip_type to null when unclear
duration / time_context extraction:
- Extract the user's stated duration as-is into time_context. Examples:
"one week in Rome" → time_context="one week"
"weekend trip to Paris" → time_context="weekend"
"I wanna go to Tokyo for 3 days" → time_context="3 days"
"a month in Bali" → time_context="one month"
"today" / "tonight" → time_context="today"
- If no duration is stated, set time_context=null
User input: "{user_input}"
Last prompt: "{last_prompt}"
Has plans loaded: {has_plans}
Output JSON schema:
{{
"mode": "plan|refine|city|calendar|save|history|tips|notion|clarify|exit",
"city": "city or null",
"trip_type": "outing|travel|null",
"focus": "activities|lodging|transport|food|sights|mixed|null",
"vibe": "quiet|social|active|romantic|family|balanced|null",
"budget": "low|medium|high|null",
"indoor": "indoor|outdoor|any|null",
"time_context": "raw phrase or null",
"reference": "first|second|third|keyword|null"
}}"""
_FOLLOWUP_TEMPLATE = (
"You are a concise planner assistant. The user said: '{user_input}'. "
"Current mode: {mode}. Reply with one short follow-up question."
)
SEARCH_URL = "https://google.serper.dev/search"
SERPER_PLACES_URL = "https://google.serper.dev/places"
TICKETMASTER_URL = "https://app.ticketmaster.com/discovery/v2/events.json"
IP_GEO_URL = "http://ip-api.com/json"
GEOCODE_URL = "https://geocoding-api.open-meteo.com/v1/search"
WEATHER_URL = "https://api.open-meteo.com/v1/forecast"
AIR_URL = "https://air-quality-api.open-meteo.com/v1/air-quality"
# Free routing API -- no key required
OSRM_ROUTE_URL = "http://router.project-osrm.org/route/v1/driving"
# Free country info API -- no key required
RESTCOUNTRIES_URL = "https://restcountries.com/v3.1/capital"
class MicroAdventurePlannerAbility(MatchingCapability):
"""Create nearby short plans using weather + air quality + local discovery."""
# {{register capability}}
worker: AgentWorker = None
capability_worker: CapabilityWorker = None
current_plans: list[dict] = None
_is_running: bool = False
def call(self, worker: AgentWorker):
self.worker = worker
self.capability_worker = CapabilityWorker(self)
if MicroAdventurePlannerAbility._is_running:
# Already active -- silently ignore the re-trigger
return
MicroAdventurePlannerAbility._is_running = True
self.current_plans = []
self._last_plan_context: dict = {}
self._last_narrative: str = "" # last LLM-generated plan narrative for Notion
self._ip_country_code: str = "" # populated by _fetch_ip_city
self.worker.session_tasks.create(self.run())
def _log(self, msg: str):
try:
self.worker.editor_logging_handler.info(f"[MicroAdventure] {msg}")
except Exception:
pass
def _err(self, msg: str):
try:
self.worker.editor_logging_handler.error(f"[MicroAdventure] {msg}")
except Exception:
pass
async def run(self):
try:
prefs = await self._load_prefs()
await self.capability_worker.speak(
"Hey! Ready to plan your next adventure. "
"Just tell me where you want to go and I'll sort everything out for you."
)
if not prefs.get("home_city"):
await self._first_run_city_setup(prefs)
elif not prefs.get("home_country_name"):
# Backfill country/region for users who saved city before these fields existed
ip_result = await self._fetch_ip_city()
if ip_result and ip_result[1]:
prefs["home_country_name"] = ip_result[1]
if ip_result[2]:
prefs["home_region_name"] = ip_result[2]
if not prefs.get("home_country_code") and self._ip_country_code:
prefs["home_country_code"] = self._ip_country_code
await self._save_prefs(prefs)
else:
geo = await self._geocode_city(
prefs["home_city"],
country_code=prefs.get("home_country_code", ""),
)
if geo and geo[2]:
prefs["home_country_name"] = geo[2]
await self._save_prefs(prefs)
prompt = "So, where do you want to go? Or just tell me the vibe -- relaxing, exploring, food, whatever."
idle_count = 0
for _ in range(20):
user_input = await self.capability_worker.run_io_loop(prompt)
if not user_input or not user_input.strip():
idle_count += 1
if idle_count >= _IDLE_MAX:
await self.capability_worker.speak(
"Looks like you stepped away -- talk soon!"
)
break
prompt = (
"Still with me? Just say something like 'restaurants in Paris' or 'weekend in Rome'."
if idle_count >= _IDLE_WARN
else "I'm here whenever you're ready. What sounds good?"
)
continue
idle_count = 0
lowered = user_input.lower().strip()
if lowered in EXIT_WORDS or any(
x in lowered for x in EXIT_WORDS if len(x.split()) > 1
):
await self.capability_worker.speak("Great. Enjoy your day.")
break
intent = await self._classify_intent(user_input, prompt)
mode = intent.get("mode", "clarify")
if mode == "exit":
await self.capability_worker.speak("Great. Enjoy your day.")
break
if mode == "city":
city = (intent.get("city") or "").strip()
if city:
prefs["home_city"] = city
await self._save_prefs(prefs)
await self.capability_worker.speak(
f"Saved. Default city is now {city}."
)
else:
await self.capability_worker.speak(
"Tell me the city name you want to use."
)
prompt = "What should I plan for you?"
continue
if mode == "calendar":
ok = await self._calendar_handoff(intent)
prompt = (
"Want another plan?"
if ok
else "I can build a plan first. What do you want to do?"
)
continue
if mode == "save":
ok = await self._save_itinerary(intent, prefs)
prompt = (
"Saved. Want another plan or check your trip history?"
if ok
else "I need a plan first. What should I search for?"
)
continue
if mode == "history":
await self._speak_trip_history()
prompt = "Want to plan a new adventure?"
continue
if mode == "tips":
city = (intent.get("city") or prefs.get("home_city") or "").strip()
await self._speak_travel_tips(city, prefs)
prompt = "Anything else? I can plan activities or search for food."
continue
if mode == "notion":
ok = await self._post_to_notion(prefs)
prompt = (
"Posted to Notion. Want to plan something else or check travel tips?"
if ok
else "Notion posting failed. Make sure your Notion API key and database ID are set."
)
continue
if mode == "refine" and self.current_plans:
await self._speak_refined(intent)
prompt = (
"Want details on one option, add to calendar, or refine again?"
)
continue
if mode == "clarify":
await self.capability_worker.speak(
"Sorry, I didn't catch that. Could you say that again?"
)
prompt = "What would you like to do? I can plan a trip, find restaurants, or give travel tips."
continue
found = await self._handle_plan(intent, prefs)
prompt = (
"Want to save these, post to Notion, hear travel tips, or refine options?"
if found
else "I can try a different vibe, budget, or city."
)
except Exception as exc:
self._err(f"Fatal run loop error: {exc}")
await self.capability_worker.speak(
"Sorry, something went wrong while planning."
)
finally:
MicroAdventurePlannerAbility._is_running = False
self.capability_worker.resume_normal_flow()
async def _load_prefs(self) -> dict:
exists = await self.capability_worker.check_if_file_exists(PREFS_FILE, False)
if exists:
try:
raw = await self.capability_worker.read_file(PREFS_FILE, False)
loaded = json.loads(raw)
return {**DEFAULT_PREFS, **loaded}
except Exception as exc:
self._err(f"Load prefs failed: {exc}")
return dict(DEFAULT_PREFS)
async def _save_prefs(self, prefs: dict):
if await self.capability_worker.check_if_file_exists(PREFS_FILE, False):
await self.capability_worker.delete_file(PREFS_FILE, False)
await self.capability_worker.write_file(PREFS_FILE, json.dumps(prefs), False)
async def _first_run_city_setup(self, prefs: dict):
ip_result = await self._fetch_ip_city()
city = ip_result[0] if ip_result else None
ip_country = ip_result[1] if ip_result else ""
ip_region = ip_result[2] if ip_result else ""
if city:
# Build display: "Badr, Cairo, Egypt" or "Badr, Egypt"
_parts = [city]
if ip_region:
_parts.append(ip_region)
if ip_country:
_parts.append(ip_country)
location_label = ", ".join(_parts)
ans = await self.capability_worker.run_io_loop(
f"Looks like you're in {location_label} -- want me to use that as your home base?"
)
if ans and any(
x in ans.lower() for x in ("yes", "sure", "ok", "yep", "yeah")
):
prefs["home_city"] = city
prefs["home_country_code"] = self._ip_country_code
prefs["home_country_name"] = ip_country
prefs["home_region_name"] = ip_region
await self._save_prefs(prefs)
return
# User may have said something like "Use Cairo instead" -- try to extract city
alt = self._extract_city_from_text(ans or "")
if alt and alt.lower() != city.lower():
prefs["home_city"] = alt
await self._save_prefs(prefs)
await self.capability_worker.speak(
f"Perfect, I'll go with {alt} as your home base."
)
return
ans = await self.capability_worker.run_io_loop(
"Quick question -- what city should I use as your starting point?"
)
if ans:
# Always extract city name -- avoids storing sentences like 'I plan to go to France.'
extracted = self._extract_city_from_text(ans)
city_to_save = extracted or ans.strip()
prefs["home_city"] = city_to_save
await self._save_prefs(prefs)
await self.capability_worker.speak(
f"Got it -- I'll remember {city_to_save} for you."
)
async def _fetch_ip_city(self) -> Optional[tuple[str, str, str]]:
"""Return (city, country, region) tuple from IP geolocation, or None on failure."""
try:
ip = self.worker.user_socket.client.host
async with httpx.AsyncClient(timeout=5) as client:
resp = await client.get(f"{IP_GEO_URL}/{ip}")
if resp.status_code == 200 and resp.json().get("status") == "success":
data = resp.json()
self._ip_country_code = data.get("countryCode", "")
city = data.get("city") or ""
country = data.get("country") or ""
# Extract short region name: "Cairo Governorate" → "Cairo"
raw_region = data.get("regionName") or ""
region = (
raw_region.replace(" Governorate", "")
.replace(" Province", "")
.replace(" Region", "")
.strip()
)
# Don't store region if it's the same as the city
if region.lower() == city.lower():
region = ""
return (city, country, region) if city else None
except Exception as exc:
self._err(f"IP lookup failed: {exc}")
return None
async def _classify_intent(self, user_input: str, last_prompt: str) -> dict:
lower = user_input.lower()
detected_focus = self._detect_focus(lower)
# ── Fast-path 1: city set (unambiguous, never garbled) ────────────
if any(x in lower for x in ("city is", "set city", "change city", "i live in")):
city_guess = self._extract_city_from_text(user_input)
return {"mode": "city", "city": city_guess}
# ── Everything else: let LLM classify ─────────────────────────────
prompt = _INTENT_TEMPLATE.format(
user_input=user_input,
last_prompt=last_prompt,
has_plans="yes" if self.current_plans else "no",
)
try:
raw = self.capability_worker.text_to_text_response(prompt)
data = json.loads(self._strip_fences(raw))
if data.get("mode") in VALID_MODES:
# Guard: reject 'plan' from LLM if no city and input is very short
# (avoids single noise words triggering plans)
if (
data.get("mode") == "plan"
and not data.get("city")
and len(lower.split()) <= 2
):
return {"mode": "clarify", "raw_input": user_input}
# Normalize focus through the keyword detector if LLM gave junk
focus = (data.get("focus") or "").lower().strip()
if focus not in VALID_FOCUS:
data["focus"] = detected_focus
# If LLM returned a plan with no city and no outing flag, ask a
# follow-up LLM call to decide if it's a local outing (handles STT
# noise like "Travel Dravel go eat").
if (
data.get("mode") == "plan"
and not data.get("city")
and data.get("trip_type") != "outing"
):
verdict = self.capability_worker.text_to_text_response(
f'Voice input (may contain STT noise): "{user_input}"\n'
"Ignoring any garbled words at the start, is the user's real intent to do a "
"LOCAL outing near their current city (eat out, play a sport, visit somewhere nearby) "
"with NO travel destination mentioned?\n"
"Reply with exactly one word: YES or NO."
)
if (verdict or "").strip().upper().startswith("Y"):
data["trip_type"] = "outing"
data["city"] = None
data["time_context"] = data.get("time_context") or "today"
data["raw_input"] = user_input
return data
except Exception as exc:
self._err(f"Intent classify LLM error: {exc}")
# ── Fallback: fuzzy Notion detection for badly garbled STT ────────
# If LLM failed or returned 'clarify', check phonetic Notion match
# as a safety net (e.g. "Past to no sjenn").
if self._looks_like_notion(lower):
return {"mode": "notion"}
return {"mode": "clarify", "raw_input": user_input}
def _detect_focus(self, lower_text: str) -> str:
has_lodging = any(word in lower_text for word in LODGING_WORDS)
has_transport = any(word in lower_text for word in TRANSPORT_WORDS)
has_food = any(word in lower_text for word in FOOD_WORDS)
has_sights = any(word in lower_text for word in SIGHTS_WORDS)
hits = sum([has_lodging, has_transport, has_food, has_sights])
if hits > 1:
return "mixed"
if has_food:
return "food"
if has_sights:
return "sights"
if has_lodging:
return "lodging"
if has_transport:
return "transport"
return "activities"
def _extract_city_from_text(self, user_input: str) -> Optional[str]:
text = (user_input or "").strip()
if not text:
return None
patterns = [
r"(?:travel to|trip to|go to)\s+([A-Za-z][A-Za-z\s\-']{1,60})",
r"(?:in|at|to)\s+([A-Za-z][A-Za-z\s\-']{1,60})",
r"(?:city is|set city to|change city to|my city is|i live in)\s+([A-Za-z][A-Za-z\s\-']{1,60})",
]
for pattern in patterns:
match = re.search(pattern, text, flags=re.IGNORECASE)
if not match:
continue
raw_city = match.group(1).strip(" .,!?:;\"'")
tokens = []
for token in raw_city.split():
lowered = token.lower().strip(" .,!?:;\"'")
if lowered in CITY_STOP_WORDS:
break
tokens.append(token.strip(" .,!?:;\"'"))
city = " ".join(t for t in tokens if t)
if city:
return city
# Fallback for short direct city requests like "Dahab" or "Cairo"
# Guard: reject exclusion phrases -- they name a region to AVOID, not a destination
EXCLUSION_PREFIXES = (
"outside ",
"not ",
"except ",
"beyond ",
"abroad",
"other than",
"international",
"foreign",
"be outside",
)
text_lower = text.lower().strip()
if any(
text_lower.startswith(p) or f" {p}" in text_lower
for p in EXCLUSION_PREFIXES
):
return None
plain = re.sub(r"[^A-Za-z\s\-']", " ", text).strip()
if (
plain
and len(plain.split()) <= 3
and all(t.lower() not in CITY_STOP_WORDS for t in plain.split())
):
# Cap to first 3 tokens to avoid accepting long STT noise
return " ".join(plain.split()[:3])
return None
async def _handle_plan(self, intent: dict, prefs: dict) -> bool:
city_from_intent = (intent.get("city") or "").strip()
city_from_prefs = (prefs.get("home_city") or "").strip()
city = city_from_intent or city_from_prefs
if not city:
await self.capability_worker.speak(
"I need a city first. Tell me where to plan."
)
return False
# ── Detect upfront "recommend a city" intent (no explicit destination given) ──
RECOMMEND_TRIGGERS = (
"recommend",
"suggest",
"where should",
"where can",
"best city",
"good city",
"nice city",
"what city",
"pick a city",
"choose a city",
)
raw_input_lower = (intent.get("raw_input") or "").lower()
wants_recommendation = any(t in raw_input_lower for t in RECOMMEND_TRIGGERS)
# If LLM flagged this as an outing, ensure local_radius is set for nearby search
if intent.get("trip_type") == "outing" and not intent.get("local_radius"):
intent["local_radius"] = 20
# ── When user gave no explicit destination, ask local-or-away ──────────────────
if not city_from_intent and city_from_prefs and not intent.get("trip_type"):
if wants_recommendation:
# User asked for a city suggestion upfront -- skip local-or-away, go straight
ans_lower = raw_input_lower
else:
_home_country = (prefs.get("home_country_name") or "").strip()
_city_label = (
f"{city_from_prefs}, {_home_country}"
if _home_country
else city_from_prefs
)
ans = await self.capability_worker.run_io_loop(
f"Are you looking to explore somewhere near {_city_label}, "
"or do you have a new destination in mind?"
)
ans_lower = (ans or "").lower()
LOCAL_HINTS = (
"near",
"local",
"here",
"close",
"around",
"stay",
"within",
"nearby",
"home",
"yes",
"current",
)
AWAY_RECOMMEND_HINTS = (
"outside",
"abroad",
"international",
"foreign",
"not ",
"except",
"recommend",
"suggest",
"anywhere",
"somewhere",
"other country",
)
if any(w in ans_lower for w in LOCAL_HINTS) and not any(
w in ans_lower for w in AWAY_RECOMMEND_HINTS
):
# Local outing -- keep home city, flag for nearby search
intent["trip_type"] = "outing"
intent["local_radius"] = 20
elif (
any(w in ans_lower for w in AWAY_RECOMMEND_HINTS)
or wants_recommendation
):
# User wants a recommendation -- extract constraints from their input
exclude_country = ""
# Detect "outside X" / "not Egypt" / "except France" patterns
excl_match = re.search(
r"(?:outside|not|except|beyond|other than)\s+([A-Za-z][A-Za-z\s]{1,40})",
ans_lower,
)
if excl_match:
exclude_country = excl_match.group(1).strip().title()
elif prefs.get("home_country_code"):
# Default: exclude home country so we actually go abroad
exclude_country = prefs.get("home_country_code", "")
vibe_hint = self._parse_vibe_text(ans_lower or raw_input_lower)
budget_hint = (
intent.get("budget") or prefs.get("default_budget") or "medium"
)
await self.capability_worker.speak(
"Let me think of the perfect destination for you..."
)
suggested = await self._recommend_city(
vibe=vibe_hint,
budget=budget_hint,
exclude_country=exclude_country,
home_city=city_from_prefs,
)
if not suggested:
await self.capability_worker.speak(
"I couldn't come up with a suggestion right now. Could you name a city you have in mind?"
)
return False
confirm = await self.capability_worker.run_io_loop(
f"How about {suggested}? Does that sound good?"
)
if confirm and any(
x in (confirm or "").lower()
for x in (
"yes",
"sure",
"ok",
"yep",
"yeah",
"great",
"perfect",
"sounds",
"let",
"go",
)
):
city = suggested
city_from_intent = suggested
else:
# User rejected -- ask directly
dest_ans = await self.capability_worker.run_io_loop(
"Where would you like to go instead?"
)
if self._is_correction(dest_ans or ""):
await self.capability_worker.speak(
"No problem -- just let me know what you'd like to do."
)
return False
city = (
self._extract_city_from_text(dest_ans or "")
or (dest_ans or "").strip()
)
if not city or city == city_from_prefs:
await self.capability_worker.speak(
"No problem -- just let me know when you have a place in mind."
)
return False
city_from_intent = city
else:
# User named a specific destination
new_dest = self._extract_city_from_text(
ans if not wants_recommendation else raw_input_lower
)
if new_dest and new_dest.lower() != city_from_prefs.lower():
city = new_dest
city_from_intent = new_dest
else:
dest_ans = await self.capability_worker.run_io_loop(
"Where do you want to go?"
)
if self._is_correction(dest_ans or ""):
await self.capability_worker.speak(
"No problem -- just let me know what you'd like to do."
)
return False
new_dest = (
self._extract_city_from_text(dest_ans or "")
or (dest_ans or "").strip()
)
if new_dest:
city = new_dest
city_from_intent = new_dest
else:
await self.capability_worker.speak(
"No problem -- just tell me when you have a place in mind."
)
return False
# Only show origin when it's genuinely different from the destination.
# Build full origin label: "Badr, Cairo, Egypt" using stored prefs.
if city_from_prefs and city_from_prefs.lower() != city.lower():
_origin_parts = [city_from_prefs]
_region = (prefs.get("home_region_name") or "").strip()
_country = (prefs.get("home_country_name") or "").strip()
if _region:
_origin_parts.append(_region)
if _country:
_origin_parts.append(_country)
origin_city = ", ".join(_origin_parts)
else:
origin_city = ""
# Parse budget from any dollar amounts in the raw intent before asking questions
raw_budget = intent.get("budget") or ""
if raw_budget:
intent["budget"] = self._parse_budget_text(raw_budget)
# Parse vibe if already mentioned
raw_vibe = intent.get("vibe") or ""
if raw_vibe:
intent["vibe"] = self._parse_vibe_text(raw_vibe)
# Gather any missing details conversationally before generating
intent = await self._gather_trip_details(intent, prefs)
# User corrected mid-intake (e.g. "No, I wanna go eat") -- re-classify and restart
if intent.get("_abort"):
abort_text = intent.pop("_abort")
new_intent = await self._classify_intent(abort_text, "")
new_intent.setdefault("raw_input", abort_text)
if new_intent.get("mode") == "plan":
return await self._handle_plan(new_intent, prefs)
# Not a plan -- caller will handle any other mode
return False
budget = (
intent.get("budget") or prefs.get("default_budget") or "medium"
).lower()
vibe = (intent.get("vibe") or prefs.get("default_vibe") or "balanced").lower()
indoor = (intent.get("indoor") or prefs.get("default_indoor") or "any").lower()
time_context = (
intent.get("duration") or intent.get("time_context") or "weekend"
).strip()
focus = (intent.get("focus") or "activities").lower().strip()
if focus not in VALID_FOCUS:
focus = "activities"
if origin_city:
await self.capability_worker.speak(
f"Great, planning your trip from {origin_city} to {city}. One moment."
)
else:
await self.capability_worker.speak(
f"Planning options in {city}. One moment."
)
# Pass country code when geocoding to avoid wrong-country matches (e.g. Badr EG vs SA)
geocode_country = (
prefs.get("home_country_code", "") if not city_from_intent else ""
)
geo = await self._geocode_city(city, country_code=geocode_country)
if not geo:
# If the bad city came from stored prefs, clear it so the user isn't stuck
if not city_from_intent and city_from_prefs:
prefs["home_city"] = None
await self._save_prefs(prefs)
await self.capability_worker.speak(
f"I couldn't locate your saved city '{city}'. "
"Please tell me which city you'd like to use."
)
return False
# Try to recover via LLM city suggestion (handles noisy STT)
suggestion = self._suggest_city(city)
if suggestion and suggestion.lower() != city.lower():
ans = await self.capability_worker.run_io_loop(
f"I couldn't locate '{city}'. Did you mean {suggestion}?"
)
if ans and any(
x in (ans or "").lower()
for x in ("yes", "sure", "ok", "yep", "yeah", "correct", "right")
):
geo = await self._geocode_city(suggestion)
if geo:
city = suggestion
# Update intent city so origin/destination display is correct
if (
not city_from_prefs
or city_from_prefs.lower() == suggestion.lower()
):
origin_city = ""
if not geo:
await self.capability_worker.speak(
f"I still couldn't locate {suggestion}. Please tell me the city name."
)
return False
else:
await self.capability_worker.speak(
"No problem. Tell me which city you'd like to plan for."
)
return False
else:
await self.capability_worker.speak(
f"I couldn't locate '{city}'. Try saying just the city name, like Rome or Cairo."
)
return False
if not geo:
return False
lat, lon, country_name = geo
weather_task = self._fetch_weather(lat, lon)
aqi_task = self._fetch_aqi(lat, lon)
search_task = self._fetch_serper_candidates(
city=city,
time_context=time_context,
focus=focus,
api_key=prefs.get("api_key_serper", ""),
radius_km=int(intent.get("local_radius") or 0),
country_name=country_name,
)
event_task = self._fetch_ticketmaster(
city, time_context, prefs.get("api_key_ticketmaster", "")
)
# Fetch flight price snippets (only for travel trips with an origin)
async def _noop_flight():
return []
flight_task = (
self._fetch_flight_prices(
origin=origin_city,
destination=city,
api_key=prefs.get("api_key_serper", ""),
)
if origin_city and intent.get("trip_type") != "outing"
else _noop_flight()
)
weather, aqi, activities, events, flight_prices = await asyncio.gather(
weather_task,
aqi_task,
search_task,
event_task,
flight_task,
)
candidates = self._build_candidates(
activities=activities,
events=events,
city=city,
focus=focus,
origin_city=origin_city,
)
ranked = self._rank_candidates(
candidates, budget, vibe, indoor, weather, aqi, focus
)
self.current_plans = ranked[:3]
if not self.current_plans:
await self.capability_worker.speak(
"I could not build a solid plan right now. Try a different city or mood."
)