-
Notifications
You must be signed in to change notification settings - Fork 280
Expand file tree
/
Copy pathmain.py
More file actions
2912 lines (2605 loc) · 117 KB
/
main.py
File metadata and controls
2912 lines (2605 loc) · 117 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
import asyncio
import json
import re
import uuid
from datetime import datetime, timedelta
import requests
from src.agent.capability import MatchingCapability
from src.agent.capability_worker import CapabilityWorker
from src.main import AgentWorker
# ===========================================================================
# Activity Log Service
# ===========================================================================
class ActivityLogService:
def __init__(self, worker, max_log_entries=500):
self.worker = worker
self.max_log_entries = max_log_entries
def add_activity(
self, activity_log, pet_name, activity_type, details="", value=None
):
entry = {
"pet_name": pet_name,
"type": activity_type,
"timestamp": datetime.now().isoformat(),
"details": details,
}
if value is not None:
entry["value"] = value
activity_log.append(entry)
if len(activity_log) > self.max_log_entries:
removed = len(activity_log) - self.max_log_entries
activity_log = activity_log[-self.max_log_entries:]
self.worker.editor_logging_handler.warning(
f"[PetCare] Activity log size limit reached. Removed {removed} old entries."
)
return activity_log
def get_recent_activities(
self, activity_log, pet_name=None, activity_type=None, limit=10
):
filtered = activity_log
if pet_name:
filtered = [a for a in filtered if a.get("pet_name") == pet_name]
if activity_type:
filtered = [a for a in filtered if a.get("type") == activity_type]
return list(reversed(filtered[-limit:]))
# ===========================================================================
# Pet Data Service
# ===========================================================================
class PetDataService:
def __init__(self, capability_worker, worker):
self.capability_worker = capability_worker
self.worker = worker
async def load_json(self, filename, default=None):
backup_filename = f"{filename}.backup"
if await self.capability_worker.check_if_file_exists(filename, False):
try:
raw = await self.capability_worker.read_file(filename, False)
if not raw or not raw.strip():
return default if default is not None else {}
return json.loads(raw)
except json.JSONDecodeError:
self.worker.editor_logging_handler.error(
f"[PetCare] Corrupt file {filename}, trying backup."
)
await self.capability_worker.delete_file(filename, False)
if await self.capability_worker.check_if_file_exists(backup_filename, False):
try:
raw = await self.capability_worker.read_file(backup_filename, False)
if raw and raw.strip():
data = json.loads(raw)
self.worker.editor_logging_handler.info(
f"[PetCare] Recovered {filename} from backup."
)
await self.capability_worker.write_file(
filename, json.dumps(data), False
)
await self.capability_worker.delete_file(backup_filename, False)
return data
except (json.JSONDecodeError, Exception) as e:
self.worker.editor_logging_handler.error(
f"[PetCare] Backup {backup_filename} also corrupt: {e}"
)
await self.capability_worker.delete_file(backup_filename, False)
return default if default is not None else {}
async def save_json(self, filename, data):
backup_filename = f"{filename}.backup"
try:
if await self.capability_worker.check_if_file_exists(filename, False):
content = await self.capability_worker.read_file(filename, False)
await self.capability_worker.write_file(backup_filename, content, False)
self.worker.editor_logging_handler.info(
f"[PetCare] Created backup: {backup_filename}"
)
await self.capability_worker.delete_file(filename, False)
await self.capability_worker.write_file(filename, json.dumps(data), False)
if await self.capability_worker.check_if_file_exists(
backup_filename, False
):
await self.capability_worker.delete_file(backup_filename, False)
self.worker.editor_logging_handler.info(
f"[PetCare] Successfully saved {filename}, backup cleaned up"
)
except Exception as e:
self.worker.editor_logging_handler.error(
f"[PetCare] Failed to save {filename}: {e}"
)
if await self.capability_worker.check_if_file_exists(
backup_filename, False
):
self.worker.editor_logging_handler.warning(
f"[PetCare] Backup file {backup_filename} retained for recovery"
)
raise
def resolve_pet(self, pet_data, pet_name=None):
pets = pet_data.get("pets", [])
if not pets:
return None
if len(pets) == 1:
return pets[0]
if pet_name:
name_lower = pet_name.lower().strip()
for p in pets:
if p["name"].lower() == name_lower:
return p
for p in pets:
if p["name"].lower().startswith(name_lower) or name_lower.startswith(
p["name"].lower()
):
return p
return pets[0]
async def resolve_pet_async(self, pet_data, pet_name=None, is_exit_fn=None):
pets = pet_data.get("pets", [])
if not pets:
await self.capability_worker.speak("You don't have any pets set up yet.")
return None
if len(pets) == 1:
return pets[0]
if pet_name:
name_lower = pet_name.lower().strip()
for p in pets:
if p["name"].lower() == name_lower:
return p
for p in pets:
if p["name"].lower().startswith(name_lower) or name_lower.startswith(
p["name"].lower()
):
return p
names = " or ".join(p["name"] for p in pets)
await self.capability_worker.speak(f"Which pet? {names}?")
response = await self.capability_worker.user_response()
if response and (not is_exit_fn or not is_exit_fn(response)):
return self.resolve_pet(pet_data, response)
return None
# ===========================================================================
# LLM Service
# ===========================================================================
_FORCE_EXIT_PHRASES = [
"exit petcare",
"close petcare",
"shut down pets",
"petcare out",
]
_EXIT_COMMANDS = ["exit", "stop", "quit", "cancel"]
_EXIT_RESPONSES = [
"no",
"nope",
"done",
"bye",
"goodbye",
"thanks",
"thank you",
"no thanks",
"nothing else",
"all good",
"i'm good",
"that's all",
"that's it",
"i'm done",
"we're done",
]
_CLASSIFY_PROMPT = (
"You are an intent classifier for a pet care assistant. "
"The user manages one or more pets. Known pets: {pet_names}.\n\n"
"CRITICAL INSTRUCTIONS:\n"
"1. Input comes from speech-to-text and WILL be garbled, noisy, or incomplete. "
"Always try to infer the most plausible intent, even from fragments.\n"
"2. Only return mode 'unknown' if you truly cannot extract ANY plausible intent "
"after trying hard. When in doubt, pick the closest match.\n"
"3. Ignore filler words, background noise, repeated words, or STT artifacts.\n"
"4. If the input sounds like an information request — contains words like 'give me', "
"'tell me', 'show me', 'get me', 'what', 'when', 'how', 'information', 'info', "
"'details', 'data', 'history', 'record' — classify as 'lookup', NOT 'unknown'.\n"
"5. If the input sounds like reporting an activity (feeding, walk, weight, medication, "
"grooming) — classify as 'log', NOT 'unknown'.\n"
"6. IMPORTANT - past vs future distinction:\n"
" - PAST events (already happened): 'I fed', 'we walked', 'she ate', 'went to vet', "
"'got groomed' -> 'log'\n"
" - FUTURE plans (haven't happened yet): 'I wanna go', 'need to go', 'going to', "
"'have an appointment', 'scheduled for', 'plan to', 'want to take', 'next Monday', "
"'tomorrow', 'next week', 'this Friday' -> 'reminder' with action 'set'\n"
" - If the input mentions a future time reference AND an activity, it is a REMINDER, not a LOG.\n\n"
"Return ONLY valid JSON with no markdown fences.\n\n"
"Possible modes:\n"
'- {{"mode": "log", "pet_name": "<name or null>", "activity_type": "feeding|medication|walk|weight|vet_visit|grooming|other", "details": "<short description>", "value": null}}\n'
'- {{"mode": "lookup", "pet_name": "<name or null>", "query": "<the user\'s question>"}}\n'
'- {{"mode": "emergency_vet"}}\n'
'- {{"mode": "weather", "pet_name": "<name or null>"}}\n'
'- {{"mode": "food_recall"}}\n'
'- {{"mode": "edit_pet", "action": "add_pet|update_pet|change_vet|update_weight|remove_pet|clear_log|reset_all", "pet_name": "<name or null>", "details": "<what to change>"}}\n'
'- {{"mode": "reminder", "action": "set|list|delete", "pet_name": "<name or null>", "activity": "<feeding|medication|walk|other>", "time_description": "<raw time the user said>"}}\n'
'- {{"mode": "greeting"}}\n'
'- {{"mode": "exit"}}\n'
'- {{"mode": "unknown"}}\n\n'
"Rules:\n"
"- 'I fed', 'ate', 'breakfast', 'dinner', 'kibble', 'food' => log feeding\n"
"- 'medicine', 'medication', 'pill', 'flea', 'heartworm', 'dose' => log medication\n"
"- 'walk', 'walked', 'run', 'jog', 'hike' => log walk\n"
"- 'weighs', 'pounds', 'lbs', 'kilos', 'weight is' => log weight (extract numeric value)\n"
"- 'vet visit', 'went to vet', 'checkup' => log vet_visit\n"
"- 'groom', 'bath', 'nails', 'haircut' => log grooming\n"
"- 'when did', 'last time', 'how many', 'has had', 'check on', 'tell me about' => lookup\n"
"- 'emergency vet', 'find a vet', 'vet near me', 'need a vet' => emergency_vet\n"
"- 'safe outside', 'weather', 'too hot', 'too cold', 'can I walk', 'go outside' => weather\n"
"- 'food recall', 'recall check', 'food safe' => food_recall\n"
"- 'add a pet', 'new pet', 'update', 'change vet', 'edit pet' => edit_pet\n"
"- 'remove pet', 'delete pet' => edit_pet with action remove_pet\n"
"- 'clear log', 'clear activity log', 'delete all logs', 'clear history' => edit_pet with action clear_log\n"
"- 'start over', 'reset everything', 'delete everything', 'wipe all data', 'fresh start' => edit_pet with action reset_all\n"
"- 'what pets', 'do I have any pets', 'any animals', 'list my pets', 'how many pets' => lookup with query 'list registered pets'\n"
"- 'remind me', 'set a reminder', 'alert me' => reminder with action set\n"
"- 'my reminders', 'list reminders', 'what reminders' => reminder with action list\n"
"- 'delete reminder', 'cancel reminder', 'remove reminder' => reminder with action delete\n"
"- 'stop', 'done', 'quit', 'exit', 'bye' => exit\n"
"- Trigger phrases with no specific action ('pet care', 'hello', 'hey', 'hi') => greeting\n"
"- If only one pet exists and no name is mentioned, use that pet's name.\n"
"- If multiple pets and no name mentioned, set pet_name to null.\n\n"
"Examples:\n"
'"I just fed Luna" -> {{"mode": "log", "pet_name": "Luna", "activity_type": "feeding", "details": "fed", "value": null}}\n'
'"Luna weighs 48 pounds now" -> {{"mode": "log", "pet_name": "Luna", "activity_type": "weight", "details": "48 lbs", "value": 48}}\n'
'"When did I last feed Luna?" -> {{"mode": "lookup", "pet_name": "Luna", "query": "when was last feeding"}}\n'
'"Find an emergency vet" -> {{"mode": "emergency_vet"}}\n'
'"Is it safe for Luna outside?" -> {{"mode": "weather", "pet_name": "Luna"}}\n'
'"Any pet food recalls?" -> {{"mode": "food_recall"}}\n'
'"Start over" -> {{"mode": "edit_pet", "action": "reset_all", "pet_name": null, "details": "reset all data"}}\n'
'"Remind me to feed Luna in 2 hours" -> {{"mode": "reminder", "action": "set", "pet_name": "Luna", "activity": "feeding", "time_description": "in 2 hours"}}\n'
'"pet care" -> {{"mode": "greeting"}}\n'
)
def _strip_llm_fences(text):
text = text.strip()
text = re.sub(r"^```(?:json)?\s*", "", text)
text = re.sub(r"\s*```$", "", text)
return text.strip()
class LLMService:
def __init__(self, capability_worker, worker, pet_data):
self.capability_worker = capability_worker
self.worker = worker
self.pet_data = pet_data
def classify_intent(self, user_input):
pet_names = [p["name"] for p in self.pet_data.get("pets", [])]
prompt_filled = _CLASSIFY_PROMPT.format(
pet_names=", ".join(pet_names) if pet_names else "none",
)
try:
raw = self.capability_worker.text_to_text_response(
f"User said: {user_input}",
system_prompt=prompt_filled,
)
return json.loads(_strip_llm_fences(raw))
except (json.JSONDecodeError, Exception) as e:
self.worker.editor_logging_handler.error(
f"[PetCare] Classification error: {e}"
)
return {"mode": "unknown"}
async def classify_intent_async(self, user_input):
return await asyncio.to_thread(self.classify_intent, user_input)
def extract_value(self, raw_input, instruction):
if not raw_input:
return ""
try:
result = self.capability_worker.text_to_text_response(
f"Input: {raw_input}",
system_prompt=instruction,
)
return _strip_llm_fences(result).strip().strip('"')
except Exception:
return raw_input.strip()
async def extract_value_async(self, raw_input, instruction):
return await asyncio.to_thread(self.extract_value, raw_input, instruction)
async def extract_pet_name_async(self, raw_input):
return await self.extract_value_async(
raw_input, "Extract the pet's name from this. Return just the name."
)
async def extract_species_async(self, raw_input):
return await self.extract_value_async(
raw_input,
"Extract the animal species ONLY if it is explicitly mentioned in the text. "
"Return one word: dog, cat, bird, rabbit, hamster, etc. "
"If no species is clearly stated, return 'unknown'. "
"Do NOT guess from pet names or context.",
)
async def extract_breed_async(self, raw_input):
return await self.extract_value_async(
raw_input,
"Extract the breed name ONLY if explicitly mentioned in the text. "
"If they say mixed or don't know, return 'mixed'. "
"If no breed is mentioned at all, return 'unknown'. "
"Do NOT guess from pet names or context.",
)
async def extract_birthday_async(self, raw_input):
return await self.extract_value_async(
raw_input,
"Extract a birthday in YYYY-MM-DD format if possible. "
"If they give an age like '3 years old', calculate the approximate birthday "
f"from today ({datetime.now().strftime('%Y-%m-%d')}). "
"Return just the date string.",
)
async def extract_weight_async(self, raw_input):
return await self.extract_value_async(
raw_input,
"Extract the weight as a number in pounds. If they give kilos, convert to pounds. "
"Return just the number.",
)
async def extract_allergies_async(self, raw_input):
return await self.extract_value_async(
raw_input,
"Extract allergies as a JSON array of strings. "
'If none, return []. Example: ["chicken", "grain"]. Return only the array.',
)
async def extract_medications_async(self, raw_input):
return await self.extract_value_async(
raw_input,
"Extract medications as a JSON array of objects with 'name' and 'frequency' keys. "
'If none, return []. Example: [{"name": "Heartgard", "frequency": "monthly"}]. '
"Return only the array.",
)
async def extract_vet_name_async(self, raw_input):
return await self.extract_value_async(
raw_input, "Extract the veterinarian's name. Return just the name."
)
async def extract_phone_number_async(self, raw_input):
return await self.extract_value_async(
raw_input,
"Extract the phone number as digits only (e.g., 5125551234). Return just digits.",
)
async def extract_location_async(self, raw_input):
return await self.extract_value_async(
raw_input,
"Extract the city and state/country. Return in format 'City, State' or 'City, Country'.",
)
@staticmethod
def clean_input(text):
if not text:
return ""
cleaned = text.lower().strip()
cleaned = re.sub(r"[^\w\s']", "", cleaned)
return cleaned.strip()
def is_exit(self, text):
if not text:
return False
cleaned = self.clean_input(text)
if not cleaned:
return False
for phrase in _FORCE_EXIT_PHRASES:
if phrase in cleaned:
return True
words = cleaned.split()
for cmd in _EXIT_COMMANDS:
if cmd in words:
return True
for resp in _EXIT_RESPONSES:
if cleaned == resp:
return True
if cleaned.startswith(f"{resp} "):
return True
return False
def is_hard_exit(self, text: str) -> bool:
"""Exit detection for mid-question contexts (Tier 1 + 2 only).
Use instead of is_exit() when 'no', 'done', 'thanks', etc. are valid
answers (e.g. onboarding). Only matches explicit abort/reset commands.
"""
if not text:
return False
cleaned = self.clean_input(text)
if not cleaned:
return False
for phrase in _FORCE_EXIT_PHRASES:
if phrase in cleaned:
return True
words = cleaned.split()
for cmd in _EXIT_COMMANDS:
if cmd in words:
return True
reset_phrases = [
"start over",
"wanna start over",
"want to start over",
"start from scratch",
"restart",
"reset everything",
"start from beginning",
]
return any(phrase in cleaned for phrase in reset_phrases)
def is_exit_llm(self, text):
try:
result = self.capability_worker.text_to_text_response(
"Does this message mean the user wants to END the conversation? "
"Reply with ONLY 'yes' or 'no'.\n\n"
f'Message: "{text}"'
)
return result.strip().lower().startswith("yes")
except Exception:
return False
async def is_exit_llm_async(self, text):
return await asyncio.to_thread(self.is_exit_llm, text)
def get_trigger_context(self):
initial_request = None
try:
initial_request = self.worker.transcription
except (AttributeError, Exception):
pass
if not initial_request:
try:
initial_request = self.worker.last_transcription
except (AttributeError, Exception):
pass
return initial_request.strip() if initial_request else ""
# ===========================================================================
# External API Service (unused directly — logic inlined in main capability)
# ===========================================================================
class ExternalAPIService:
def __init__(self, worker, serper_api_key=None):
self.worker = worker
self.serper_api_key = serper_api_key
"""Pet Care Assistant — voice-first ability for tracking pets' daily lives.
Stores pet profiles and activity logs, finds emergency vets, checks weather
safety, and monitors food recalls. Persists data across sessions using JSON files.
"""
EXIT_MESSAGE = "Take care of those pets! See you next time."
PETS_FILE = "petcare_pets.json"
ACTIVITY_LOG_FILE = "petcare_activity_log.json"
REMINDERS_FILE = "petcare_reminders.json"
MAX_LOG_ENTRIES = 500
ACTIVITY_TYPES = {
"feeding",
"medication",
"walk",
"weight",
"vet_visit",
"grooming",
"other",
}
# Serper API key placeholder — get a free key at serper.dev (2,500 free queries)
SERPER_API_KEY = "your_serper_api_key_here"
LOOKUP_SYSTEM_PROMPT = (
"You are a pet care assistant answering a question about the user's "
"pet activity log. Given the log entries and the user's question, "
"give a short, clear spoken answer. Include when it happened "
"(e.g., 'this morning', '3 days ago', 'last Tuesday'). "
"Keep it to 1-2 sentences. If no matching entries exist, say so. "
"Today's date is {today}."
)
WEATHER_SYSTEM_PROMPT = (
"You are a pet care assistant checking weather safety for a pet. "
"Given the current weather data and the pet's info (species, breed), "
"assess if it's safe for the pet to be outside. "
"Use these thresholds:\n"
"- Temperature > 90F/32C: Warning (hot pavement, bring water)\n"
"- Temperature > 100F/38C: Danger (heatstroke risk, do not go outside)\n"
"- Temperature < 32F/0C: Warning for short-haired breeds and cats\n"
"- Temperature < 20F/-7C: Danger (too cold for more than a few minutes)\n"
"- Wind > 30 mph: Caution for small pets\n"
"- UV > 7: Caution for light-colored or short-haired dogs\n"
"If conditions are safe, say so positively. "
"Add breed-specific nuance if you know the breed. "
"Keep response to 1-2 sentences."
)
WEIGHT_SUMMARY_PROMPT = (
"You are a pet care assistant summarizing weight history. "
"Given the weight log entries for a pet, give a short spoken summary "
"of their current weight and any trend. Keep it to 1-2 sentences. "
"Today's date is {today}."
)
def _strip_json_fences(text: str) -> str:
"""Strip markdown code fences from LLM output (e.g. ```json ... ```)."""
text = text.strip()
if text.startswith("```"):
lines = text.split("\n")
lines = lines[1:]
if lines and lines[-1].strip() == "```":
lines = lines[:-1]
text = "\n".join(lines)
return text.strip()
def _fmt_phone_for_speech(phone: str) -> str:
"""Format a phone number for spoken output, digit by digit.
Handles multiple formats:
- 10-digit US: (512) 555-1234 → "5, 1, 2, 5, 5, 5, 1, 2, 3, 4"
- 11-digit US with country code: 1-512-555-1234 → "1, 5, 1, 2, 5, 5, 5, ..."
- International (7-15 digits): grouped by 3s for readability
- Invalid lengths (<7 or >15): all digits or error message
"""
if not phone:
return "no number provided"
digits = re.sub(r"\D", "", phone)
if not digits:
return "no number provided"
if len(digits) == 10:
return (
f"{', '.join(digits[:3])}, "
f"{', '.join(digits[3:6])}, "
f"{', '.join(digits[6:])}"
)
elif len(digits) == 11 and digits[0] == "1":
return (
f"1, "
f"{', '.join(digits[1:4])}, "
f"{', '.join(digits[4:7])}, "
f"{', '.join(digits[7:])}"
)
elif 7 <= len(digits) <= 15:
groups = [digits[i: i + 3] for i in range(0, len(digits), 3)]
return ", ".join(", ".join(group) for group in groups)
elif len(digits) < 7:
return "incomplete phone number"
else:
return "phone number too long, please check"
class PetCareAssistantCapability(MatchingCapability):
"""OpenHome ability for multi-pet care tracking with persistent storage,
emergency vet finder, weather safety, and food recall checks."""
# {{register capability}}
worker: AgentWorker = None
capability_worker: CapabilityWorker = None
pet_data: dict = None
activity_log: list = None
_geocode_cache: dict = None
# Services initialized in run()
pet_data_service: "PetDataService" = None
activity_log_service: "ActivityLogService" = None
external_api_service: "ExternalAPIService" = None
llm_service: "LLMService" = None
reminders: list = None
# Stash for a command embedded in a "no more pets" response during onboarding
_pending_intent_text: str = None
def call(self, worker: AgentWorker):
self.worker = worker
self.capability_worker = CapabilityWorker(self.worker)
self.worker.session_tasks.create(self.run())
def _is_hard_exit(self, text: str) -> bool:
"""Exit check for onboarding — ignores 'no'/'done'/'bye' etc.
Only matches explicit abort/reset commands so that 'no' to 'any allergies?'
is treated as an answer, not an exit.
"""
if not text:
return False
cleaned = re.sub(r"[^\w\s']", "", text.lower().strip())
# Single-word abort commands
if any(w in cleaned.split() for w in ["stop", "quit", "exit", "cancel"]):
return True
# Reset/restart phrases
reset_phrases = [
"start over",
"wanna start over",
"want to start over",
"start from scratch",
"restart",
"reset everything",
"start from beginning",
]
return any(phrase in cleaned for phrase in reset_phrases)
# === Main flow ===
async def run(self):
try:
self.worker.editor_logging_handler.info("[PetCare] Ability started")
self.pet_data_service = PetDataService(self.capability_worker, self.worker)
self.activity_log_service = ActivityLogService(self.worker, MAX_LOG_ENTRIES)
self.external_api_service = ExternalAPIService(self.worker, SERPER_API_KEY)
self.pet_data = await self.pet_data_service.load_json(PETS_FILE, default={})
self.llm_service = LLMService(
self.capability_worker, self.worker, self.pet_data
)
self.activity_log = await self.pet_data_service.load_json(
ACTIVITY_LOG_FILE, default=[]
)
self.reminders = await self.pet_data_service.load_json(
REMINDERS_FILE, default=[]
)
self._geocode_cache = {}
self._corrected_name = None
await self._check_due_reminders()
trigger = self.llm_service.get_trigger_context()
has_pet_data = await self.capability_worker.check_if_file_exists(
PETS_FILE, False
)
if not has_pet_data or not self.pet_data.get("pets"):
await self.run_onboarding(initial_context=trigger)
if not self.pet_data.get("pets"):
await self.capability_worker.speak(EXIT_MESSAGE)
return
# If the user embedded a command in their "no more pets" answer
# (e.g. "No, is it safe to walk Luna?"), handle it now instead of
# prompting "What would you like to do?" and making them repeat.
if self._pending_intent_text:
pending = self._pending_intent_text
self._pending_intent_text = None
pending_intent = await self.llm_service.classify_intent_async(
pending
)
if pending_intent.get("mode") not in ("unknown", "exit"):
await self._route_intent(pending_intent)
else:
await self.capability_worker.speak(
"What would you like to do? You can log activities, "
"look up history, find vets, check weather, or set reminders."
)
else:
await self.capability_worker.speak(
"What would you like to do? You can log activities, "
"look up history, find vets, check weather, or set reminders."
)
elif trigger:
intent = await self.llm_service.classify_intent_async(trigger)
mode = intent.get("mode", "unknown")
if mode not in ("unknown", "exit"):
await self._route_intent(intent)
await self.capability_worker.speak("Anything else for your pets?")
follow_up = await self.capability_worker.user_response()
if follow_up and not self.llm_service.is_exit(follow_up):
follow_intent = await self.llm_service.classify_intent_async(
follow_up
)
if follow_intent.get("mode") not in ("unknown", "exit"):
await self._route_intent(follow_intent)
await self.capability_worker.speak(EXIT_MESSAGE)
return
else:
# Returning user (pet data already exists, no trigger matched)
pet_names = [p["name"] for p in self.pet_data.get("pets", [])]
names_str = ", ".join(pet_names)
greeting = (
f"Pet Care here. You have {len(pet_names)} "
f"pet{'s' if len(pet_names) != 1 else ''}: {names_str}."
)
# Announce pending reminders and offer to read them
pending = len(self.reminders) if self.reminders else 0
if pending > 0:
greeting += (
f" You also have {pending} "
f"reminder{'s' if pending != 1 else ''} set."
)
await self.capability_worker.speak(
greeting + " Want me to read your reminders?"
)
resp = await self.capability_worker.user_response()
if resp and any(
w in resp.lower()
for w in ["yes", "yeah", "yep", "sure", "read", "go", "yup"]
):
await self._handle_reminder({"action": "list"})
elif resp and not self.llm_service.is_exit(resp):
# Route non-exit response as the initial command
intent = await self.llm_service.classify_intent_async(resp)
if intent.get("mode") not in ("unknown", "exit"):
await self._route_intent(intent)
else:
await self.capability_worker.speak(
greeting + " What would you like to do?"
)
idle_count = 0
consecutive_unknown = 0
for _ in range(20):
user_input = await self.capability_worker.user_response()
if not user_input or not user_input.strip():
idle_count += 1
if idle_count >= 2:
await self.capability_worker.speak(
"Still here if you need me. Otherwise I'll close."
)
final = await self.capability_worker.user_response()
if (
not final
or not final.strip()
or self.llm_service.is_exit(final)
):
await self.capability_worker.speak(EXIT_MESSAGE)
break
user_input = final
idle_count = 0
else:
continue
idle_count = 0
cleaned = self.llm_service.clean_input(user_input)
# Reset/restart phrases map to edit_pet+reset_all and must not
# be classified as exits; guard both code paths against that.
_reset_phrases = [
"start over",
"start from scratch",
"restart",
"reset everything",
"start from beginning",
]
_is_reset = any(p in cleaned for p in _reset_phrases)
# Long inputs bypass keyword checks: "no <follow-up>" would
# false-positive as an exit via Tier-3 prefix match, so send
# them straight to the LLM classifier for accurate intent detection.
if len(cleaned.split()) > 4:
intent = await self.llm_service.classify_intent_async(user_input)
mode = intent.get("mode", "unknown")
if mode == "exit" and not _is_reset:
await self.capability_worker.speak(EXIT_MESSAGE)
break
else:
if not _is_reset:
if self.llm_service.is_exit(user_input):
await self.capability_worker.speak(EXIT_MESSAGE)
break
if await self.llm_service.is_exit_llm_async(cleaned):
await self.capability_worker.speak(EXIT_MESSAGE)
break
intent = await self.llm_service.classify_intent_async(user_input)
mode = intent.get("mode", "unknown")
if mode == "exit" and not _is_reset:
await self.capability_worker.speak(EXIT_MESSAGE)
break
self.worker.editor_logging_handler.info(f"[PetCare] Intent: {intent}")
if mode == "unknown":
consecutive_unknown += 1
if consecutive_unknown >= 2:
consecutive_unknown = 0
await self.capability_worker.speak(
"Here's what I can do: log activities like feeding or walks, "
"look up history, find emergency vets, check weather safety, "
"check food recalls, or set reminders. What would you like?"
)
else:
await self.capability_worker.speak(
"Sorry, I didn't catch that. Could you say that again?"
)
continue
consecutive_unknown = 0
await self._route_intent(intent)
else:
await self.capability_worker.speak(EXIT_MESSAGE)
except Exception as e:
self.worker.editor_logging_handler.error(f"[PetCare] Unexpected error: {e}")
await self.capability_worker.speak(
"Something went wrong. Closing Pet Care."
)
finally:
self.worker.editor_logging_handler.info("[PetCare] Ability ended")
self.capability_worker.resume_normal_flow()
# === Intent router ===
async def _route_intent(self, intent: dict):
"""Route to the correct handler based on classified intent."""
mode = intent.get("mode", "unknown")
if mode == "log":
await self._handle_log(intent)
elif mode == "lookup":
await self._handle_lookup(intent)
elif mode == "emergency_vet":
await self._handle_emergency_vet()
elif mode == "weather":
await self._handle_weather(intent)
elif mode == "food_recall":
await self._handle_food_recall()
elif mode == "edit_pet":
await self._handle_edit_pet(intent)
elif mode == "reminder":
await self._handle_reminder(intent)
elif mode == "greeting":
await self.capability_worker.speak(
"What can I help with? I can log activities, look up history, "
"find emergency vets, check weather, check food recalls, or set reminders."
)
elif mode == "onboarding":
await self.run_onboarding()
else:
await self.capability_worker.speak(
"Sorry, I didn't catch that. Could you say that again?"
)
# === Onboarding ===
async def run_onboarding(self, initial_context: str = ""):
"""Guided voice onboarding for first-time users.
Args:
initial_context: Trigger phrase already captured (e.g. "Pet care Luna").
Passed to _collect_pet_info() to avoid re-consuming it
from the STT queue as the first user response.
"""
self.worker.editor_logging_handler.info("[PetCare] Starting onboarding")
await self.capability_worker.speak(
"Hi! I'm your pet care assistant. I'd love to help you out! "
"Let's get started — what's your pet's name?"
)
while True:
pet = await self._collect_pet_info(initial_context=initial_context)
initial_context = "" # Only use trigger for the first pet
if pet is None:
await self.capability_worker.speak("No problem. Come back anytime!")
return
if "pets" not in self.pet_data:
self.pet_data["pets"] = []
self.pet_data["pets"].append(pet)
await self._save_json(PETS_FILE, self.pet_data)
await self.capability_worker.speak(
f"Awesome, {pet['name']} is all set! "
f"You can say things like 'I just fed {pet['name']}' to log activities, "
"set reminders, check the weather, or find an emergency vet."
)
await self.capability_worker.speak("Do you have any other pets to add?")
response = await self.capability_worker.user_response()
if not response:
break
cleaned = response.lower().strip()
# If the response is only an exit phrase, leave
if self.llm_service.is_exit(response) and len(cleaned.split()) <= 2:
break
# Only continue if user explicitly says yes — default to done
if not any(
w in cleaned
for w in ["yes", "yeah", "yep", "yup", "sure", "another", "more", "add"]
):
# User said no (possibly with an embedded follow-up command,
# e.g. "No, is it safe to walk Luna?"). Strip leading negation
# and stash any remaining content so the main loop handles it.
_no_strip = re.compile(
r"^(?:no[,.]?|nope[,.]?|nah[,.]?)\s*", re.IGNORECASE
)
remainder = _no_strip.sub("", response).strip()
if remainder and len(remainder.split()) >= 3:
self._pending_intent_text = remainder
break
await self.capability_worker.speak("Great! What's your next pet's name?")
async def _ask_onboarding_step(self, prompt: str) -> str | None:
"""Ask an onboarding question, handling hard-exit and inline pet queries.
Wraps run_io_loop with two guards applied in order:
1. Hard-exit detection (returns None → caller should abort onboarding).
2. Inline pet inventory query (re-asks the prompt once after answering).
Returns:
User response string (may be empty), or None if hard exit detected.
"""
response = await self.capability_worker.run_io_loop(prompt)
if not response:
return ""
if self._is_hard_exit(response):
return None
if await self._answer_inline_query(response):
response = await self.capability_worker.run_io_loop(prompt)
if not response:
return ""
if self._is_hard_exit(response):
return None
return response
async def _answer_inline_query(self, response: str) -> bool:
"""Detect and answer a question embedded in an onboarding response.
Handles two tiers:
1. Fast keyword check — pet inventory questions ("do you have any animal?").
2. LLM-based classification — general stored-info lookups (pet profile,
activity history, vet info) for longer question-like inputs.
Returns:
True — inline query found and answered; caller should re-ask its prompt.
False — no inline query; caller should treat response as a normal answer.
"""
if not response:
return False
lower = response.lower()
# ── Tier 1: fast keyword check for pet inventory ──────────────────
inventory_patterns = [
"do you have any",
"do i have any",
"have any animal",
"have any pet",
"any animals",
"any pets",
"what animals",
"what pets",
"what the animal",
"what animal",
"the animal do i have",
"the pet do i have",
"how many pets",
"how many animals",
"list pet",
"list animal",
"animal do i have",