-
-
Notifications
You must be signed in to change notification settings - Fork 33.4k
/
Copy pathdefault_agent.py
1558 lines (1308 loc) · 55.2 KB
/
default_agent.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
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
"""Standard conversation implementation for Home Assistant."""
from __future__ import annotations
import asyncio
from collections import OrderedDict
from collections.abc import Awaitable, Callable, Iterable
from dataclasses import dataclass
from enum import Enum, auto
import functools
import logging
from pathlib import Path
import re
import time
from typing import IO, Any, cast
from hassil.expression import Expression, ListReference, Sequence, TextChunk
from hassil.intents import (
Intents,
SlotList,
TextSlotList,
TextSlotValue,
WildcardSlotList,
)
from hassil.recognize import (
MISSING_ENTITY,
RecognizeResult,
recognize_all,
recognize_best,
)
from hassil.string_matcher import UnmatchedRangeEntity, UnmatchedTextEntity
from hassil.trie import Trie
from hassil.util import merge_dict
from home_assistant_intents import ErrorKey, get_intents, get_languages
import yaml
from homeassistant import core
from homeassistant.components.homeassistant.exposed_entities import (
async_listen_entity_updates,
async_should_expose,
)
from homeassistant.const import EVENT_STATE_CHANGED, MATCH_ALL
from homeassistant.helpers import (
area_registry as ar,
device_registry as dr,
entity_registry as er,
floor_registry as fr,
intent,
start as ha_start,
template,
translation,
)
from homeassistant.helpers.entity_component import EntityComponent
from homeassistant.helpers.event import async_track_state_added_domain
from homeassistant.util.json import JsonObjectType, json_loads_object
from .const import (
DATA_DEFAULT_ENTITY,
DEFAULT_EXPOSED_ATTRIBUTES,
DOMAIN,
ConversationEntityFeature,
)
from .entity import ConversationEntity
from .models import ConversationInput, ConversationResult
from .trace import ConversationTraceEventType, async_conversation_trace_append
_LOGGER = logging.getLogger(__name__)
_DEFAULT_ERROR_TEXT = "Sorry, I couldn't understand that"
_ENTITY_REGISTRY_UPDATE_FIELDS = ["aliases", "name", "original_name"]
REGEX_TYPE = type(re.compile(""))
TRIGGER_CALLBACK_TYPE = Callable[
[ConversationInput, RecognizeResult], Awaitable[str | None]
]
METADATA_CUSTOM_SENTENCE = "hass_custom_sentence"
METADATA_CUSTOM_FILE = "hass_custom_file"
ERROR_SENTINEL = object()
def json_load(fp: IO[str]) -> JsonObjectType:
"""Wrap json_loads for get_intents."""
return json_loads_object(fp.read())
@dataclass(slots=True)
class LanguageIntents:
"""Loaded intents for a language."""
intents: Intents
intents_dict: dict[str, Any]
intent_responses: dict[str, Any]
error_responses: dict[str, Any]
language_variant: str | None
@dataclass(slots=True)
class TriggerData:
"""List of sentences and the callback for a trigger."""
sentences: list[str]
callback: TRIGGER_CALLBACK_TYPE
@dataclass(slots=True)
class SentenceTriggerResult:
"""Result when matching a sentence trigger in an automation."""
sentence: str
sentence_template: str | None
matched_triggers: dict[int, RecognizeResult]
class IntentMatchingStage(Enum):
"""Stages of intent matching."""
EXPOSED_ENTITIES_ONLY = auto()
"""Match against exposed entities only."""
UNEXPOSED_ENTITIES = auto()
"""Match against unexposed entities in Home Assistant."""
FUZZY = auto()
"""Capture names that are not known to Home Assistant."""
@dataclass(frozen=True)
class IntentCacheKey:
"""Key for IntentCache."""
text: str
"""User input text."""
language: str
"""Language of text."""
device_id: str | None
"""Device id from user input."""
@dataclass(frozen=True)
class IntentCacheValue:
"""Value for IntentCache."""
result: RecognizeResult | None
"""Result of intent recognition."""
stage: IntentMatchingStage
"""Stage where result was found."""
class IntentCache:
"""LRU cache for intent recognition results."""
def __init__(self, capacity: int) -> None:
"""Initialize cache."""
self.cache: OrderedDict[IntentCacheKey, IntentCacheValue] = OrderedDict()
self.capacity = capacity
def get(self, key: IntentCacheKey) -> IntentCacheValue | None:
"""Get value for cache or None."""
if key not in self.cache:
return None
# Move the key to the end to show it was recently used
self.cache.move_to_end(key)
return self.cache[key]
def put(self, key: IntentCacheKey, value: IntentCacheValue) -> None:
"""Put a value in the cache, evicting the least recently used item if necessary."""
if key in self.cache:
# Update value and mark as recently used
self.cache.move_to_end(key)
elif len(self.cache) >= self.capacity:
# Evict the oldest item
self.cache.popitem(last=False)
self.cache[key] = value
def clear(self) -> None:
"""Clear the cache."""
self.cache.clear()
def _get_language_variations(language: str) -> Iterable[str]:
"""Generate language codes with and without region."""
yield language
parts = re.split(r"([-_])", language)
if len(parts) == 3:
lang, sep, region = parts
if sep == "_":
# en_US -> en-US
yield f"{lang}-{region}"
# en-US -> en
yield lang
async def async_setup_default_agent(
hass: core.HomeAssistant,
entity_component: EntityComponent[ConversationEntity],
config_intents: dict[str, Any],
) -> None:
"""Set up entity registry listener for the default agent."""
entity = DefaultAgent(hass, config_intents)
await entity_component.async_add_entities([entity])
hass.data[DATA_DEFAULT_ENTITY] = entity
@core.callback
def async_entity_state_listener(
event: core.Event[core.EventStateChangedData],
) -> None:
"""Set expose flag on new entities."""
async_should_expose(hass, DOMAIN, event.data["entity_id"])
@core.callback
def async_hass_started(hass: core.HomeAssistant) -> None:
"""Set expose flag on all entities."""
for state in hass.states.async_all():
async_should_expose(hass, DOMAIN, state.entity_id)
async_track_state_added_domain(hass, MATCH_ALL, async_entity_state_listener)
ha_start.async_at_started(hass, async_hass_started)
class DefaultAgent(ConversationEntity):
"""Default agent for conversation agent."""
_attr_name = "Home Assistant"
_attr_supported_features = ConversationEntityFeature.CONTROL
def __init__(
self, hass: core.HomeAssistant, config_intents: dict[str, Any]
) -> None:
"""Initialize the default agent."""
self.hass = hass
self._lang_intents: dict[str, LanguageIntents | object] = {}
# intent -> [sentences]
self._config_intents: dict[str, Any] = config_intents
self._slot_lists: dict[str, SlotList] | None = None
# Used to filter slot lists before intent matching
self._exposed_names_trie: Trie | None = None
self._unexposed_names_trie: Trie | None = None
# Sentences that will trigger a callback (skipping intent recognition)
self.trigger_sentences: list[TriggerData] = []
self._trigger_intents: Intents | None = None
self._unsub_clear_slot_list: list[Callable[[], None]] | None = None
self._load_intents_lock = asyncio.Lock()
# LRU cache to avoid unnecessary intent matching
self._intent_cache = IntentCache(capacity=128)
@property
def supported_languages(self) -> list[str]:
"""Return a list of supported languages."""
return get_languages()
@core.callback
def _filter_entity_registry_changes(
self, event_data: er.EventEntityRegistryUpdatedData
) -> bool:
"""Filter entity registry changed events."""
return event_data["action"] == "update" and any(
field in event_data["changes"] for field in _ENTITY_REGISTRY_UPDATE_FIELDS
)
@core.callback
def _filter_state_changes(self, event_data: core.EventStateChangedData) -> bool:
"""Filter state changed events."""
return not event_data["old_state"] or not event_data["new_state"]
@core.callback
def _listen_clear_slot_list(self) -> None:
"""Listen for changes that can invalidate slot list."""
assert self._unsub_clear_slot_list is None
self._unsub_clear_slot_list = [
self.hass.bus.async_listen(
ar.EVENT_AREA_REGISTRY_UPDATED,
self._async_clear_slot_list,
),
self.hass.bus.async_listen(
fr.EVENT_FLOOR_REGISTRY_UPDATED,
self._async_clear_slot_list,
),
self.hass.bus.async_listen(
er.EVENT_ENTITY_REGISTRY_UPDATED,
self._async_clear_slot_list,
event_filter=self._filter_entity_registry_changes,
),
self.hass.bus.async_listen(
EVENT_STATE_CHANGED,
self._async_clear_slot_list,
event_filter=self._filter_state_changes,
),
async_listen_entity_updates(self.hass, DOMAIN, self._async_clear_slot_list),
]
async def async_recognize_intent(
self, user_input: ConversationInput, strict_intents_only: bool = False
) -> RecognizeResult | None:
"""Recognize intent from user input."""
language = user_input.language or self.hass.config.language
lang_intents = await self.async_get_or_load_intents(language)
if lang_intents is None:
# No intents loaded
_LOGGER.warning("No intents were loaded for language: %s", language)
return None
slot_lists = self._make_slot_lists()
intent_context = self._make_intent_context(user_input)
if self._exposed_names_trie is not None:
# Filter by input string
text_lower = user_input.text.strip().lower()
slot_lists["name"] = TextSlotList(
name="name",
values=[
result[2] for result in self._exposed_names_trie.find(text_lower)
],
)
start = time.monotonic()
result = await self.hass.async_add_executor_job(
self._recognize,
user_input,
lang_intents,
slot_lists,
intent_context,
language,
strict_intents_only,
)
_LOGGER.debug(
"Recognize done in %.2f seconds",
time.monotonic() - start,
)
return result
async def async_process(self, user_input: ConversationInput) -> ConversationResult:
"""Process a sentence."""
# Check if a trigger matched
if trigger_result := await self.async_recognize_sentence_trigger(user_input):
# Process callbacks and get response
response_text = await self._handle_trigger_result(
trigger_result, user_input
)
# Convert to conversation result
response = intent.IntentResponse(
language=user_input.language or self.hass.config.language
)
response.response_type = intent.IntentResponseType.ACTION_DONE
response.async_set_speech(response_text)
return ConversationResult(response=response)
# Match intents
intent_result = await self.async_recognize_intent(user_input)
return await self._async_process_intent_result(intent_result, user_input)
async def _async_process_intent_result(
self,
result: RecognizeResult | None,
user_input: ConversationInput,
) -> ConversationResult:
"""Process user input with intents."""
language = user_input.language or self.hass.config.language
conversation_id = None # Not supported
# Intent match or failure
lang_intents = await self.async_get_or_load_intents(language)
if result is None:
# Intent was not recognized
_LOGGER.debug("No intent was matched for '%s'", user_input.text)
return _make_error_result(
language,
intent.IntentResponseErrorCode.NO_INTENT_MATCH,
self._get_error_text(ErrorKey.NO_INTENT, lang_intents),
conversation_id,
)
if result.unmatched_entities:
# Intent was recognized, but not entity/area names, etc.
_LOGGER.debug(
"Recognized intent '%s' for template '%s' but had unmatched: %s",
result.intent.name,
(
result.intent_sentence.text
if result.intent_sentence is not None
else ""
),
result.unmatched_entities_list,
)
error_response_type, error_response_args = _get_unmatched_response(result)
return _make_error_result(
language,
intent.IntentResponseErrorCode.NO_VALID_TARGETS,
self._get_error_text(
error_response_type, lang_intents, **error_response_args
),
conversation_id,
)
# Will never happen because result will be None when no intents are
# loaded in async_recognize.
assert lang_intents is not None
# Slot values to pass to the intent
slots: dict[str, Any] = {
entity.name: {
"value": entity.value,
"text": entity.text or entity.value,
}
for entity in result.entities_list
}
device_area = self._get_device_area(user_input.device_id)
if device_area:
slots["preferred_area_id"] = {"value": device_area.id}
async_conversation_trace_append(
ConversationTraceEventType.TOOL_CALL,
{
"intent_name": result.intent.name,
"slots": {
entity.name: entity.value or entity.text
for entity in result.entities_list
},
},
)
try:
intent_response = await intent.async_handle(
self.hass,
DOMAIN,
result.intent.name,
slots,
user_input.text,
user_input.context,
language,
assistant=DOMAIN,
device_id=user_input.device_id,
conversation_agent_id=user_input.agent_id,
)
except intent.MatchFailedError as match_error:
# Intent was valid, but no entities matched the constraints.
error_response_type, error_response_args = _get_match_error_response(
self.hass, match_error
)
return _make_error_result(
language,
intent.IntentResponseErrorCode.NO_VALID_TARGETS,
self._get_error_text(
error_response_type, lang_intents, **error_response_args
),
conversation_id,
)
except intent.IntentHandleError as err:
# Intent was valid and entities matched constraints, but an error
# occurred during handling.
_LOGGER.exception("Intent handling error")
return _make_error_result(
language,
intent.IntentResponseErrorCode.FAILED_TO_HANDLE,
self._get_error_text(
err.response_key or ErrorKey.HANDLE_ERROR, lang_intents
),
conversation_id,
)
except intent.IntentUnexpectedError:
_LOGGER.exception("Unexpected intent error")
return _make_error_result(
language,
intent.IntentResponseErrorCode.UNKNOWN,
self._get_error_text(ErrorKey.HANDLE_ERROR, lang_intents),
conversation_id,
)
if (
(not intent_response.speech)
and (intent_response.intent is not None)
and (response_key := result.response)
):
# Use response template, if available
response_template_str = lang_intents.intent_responses.get(
result.intent.name, {}
).get(response_key)
if response_template_str:
response_template = template.Template(response_template_str, self.hass)
speech = await self._build_speech(
language, response_template, intent_response, result
)
intent_response.async_set_speech(speech)
return ConversationResult(
response=intent_response, conversation_id=conversation_id
)
def _recognize(
self,
user_input: ConversationInput,
lang_intents: LanguageIntents,
slot_lists: dict[str, SlotList],
intent_context: dict[str, Any] | None,
language: str,
strict_intents_only: bool,
) -> RecognizeResult | None:
"""Search intents for a match to user input."""
skip_exposed_match = False
# Try cache first
cache_key = IntentCacheKey(
text=user_input.text, language=language, device_id=user_input.device_id
)
cache_value = self._intent_cache.get(cache_key)
if cache_value is not None:
if (cache_value.result is not None) and (
cache_value.stage == IntentMatchingStage.EXPOSED_ENTITIES_ONLY
):
_LOGGER.debug("Got cached result for exposed entities")
return cache_value.result
# Continue with matching, but we know we won't succeed for exposed
# entities only.
skip_exposed_match = True
if not skip_exposed_match:
start_time = time.monotonic()
strict_result = self._recognize_strict(
user_input, lang_intents, slot_lists, intent_context, language
)
_LOGGER.debug(
"Checked exposed entities in %s second(s)",
time.monotonic() - start_time,
)
# Update cache
self._intent_cache.put(
cache_key,
IntentCacheValue(
result=strict_result,
stage=IntentMatchingStage.EXPOSED_ENTITIES_ONLY,
),
)
if strict_result is not None:
# Successful strict match with exposed entities
return strict_result
if strict_intents_only:
# Don't try matching against all entities or doing a fuzzy match
return None
# Try again with all entities (including unexposed)
skip_unexposed_entities_match = False
if cache_value is not None:
if (cache_value.result is not None) and (
cache_value.stage == IntentMatchingStage.UNEXPOSED_ENTITIES
):
_LOGGER.debug("Got cached result for all entities")
return cache_value.result
# Continue with matching, but we know we won't succeed for all
# entities.
skip_unexposed_entities_match = True
if not skip_unexposed_entities_match:
unexposed_entities_slot_lists = {
**slot_lists,
"name": self._get_unexposed_entity_names(user_input.text),
}
start_time = time.monotonic()
strict_result = self._recognize_strict(
user_input,
lang_intents,
unexposed_entities_slot_lists,
intent_context,
language,
)
_LOGGER.debug(
"Checked all entities in %s second(s)", time.monotonic() - start_time
)
# Update cache
self._intent_cache.put(
cache_key,
IntentCacheValue(
result=strict_result, stage=IntentMatchingStage.UNEXPOSED_ENTITIES
),
)
if strict_result is not None:
# Not a successful match, but useful for an error message.
# This should fail the intent handling phase (async_match_targets).
return strict_result
# Try again with missing entities enabled
skip_fuzzy_match = False
if cache_value is not None:
if (cache_value.result is not None) and (
cache_value.stage == IntentMatchingStage.FUZZY
):
_LOGGER.debug("Got cached result for fuzzy match")
return cache_value.result
# We know we won't succeed for fuzzy matching.
skip_fuzzy_match = True
maybe_result: RecognizeResult | None = None
if not skip_fuzzy_match:
start_time = time.monotonic()
best_num_matched_entities = 0
best_num_unmatched_entities = 0
best_num_unmatched_ranges = 0
for result in recognize_all(
user_input.text,
lang_intents.intents,
slot_lists=slot_lists,
intent_context=intent_context,
allow_unmatched_entities=True,
):
if result.text_chunks_matched < 1:
# Skip results that don't match any literal text
continue
# Don't count missing entities that couldn't be filled from context
num_matched_entities = 0
for matched_entity in result.entities_list:
if matched_entity.name not in result.unmatched_entities:
num_matched_entities += 1
num_unmatched_entities = 0
num_unmatched_ranges = 0
for unmatched_entity in result.unmatched_entities_list:
if isinstance(unmatched_entity, UnmatchedTextEntity):
if unmatched_entity.text != MISSING_ENTITY:
num_unmatched_entities += 1
elif isinstance(unmatched_entity, UnmatchedRangeEntity):
num_unmatched_ranges += 1
num_unmatched_entities += 1
else:
num_unmatched_entities += 1
if (
(maybe_result is None) # first result
or (num_matched_entities > best_num_matched_entities)
or (
# Fewer unmatched entities
(num_matched_entities == best_num_matched_entities)
and (num_unmatched_entities < best_num_unmatched_entities)
)
or (
# Prefer unmatched ranges
(num_matched_entities == best_num_matched_entities)
and (num_unmatched_entities == best_num_unmatched_entities)
and (num_unmatched_ranges > best_num_unmatched_ranges)
)
or (
# More literal text matched
(num_matched_entities == best_num_matched_entities)
and (num_unmatched_entities == best_num_unmatched_entities)
and (num_unmatched_ranges == best_num_unmatched_ranges)
and (
result.text_chunks_matched
> maybe_result.text_chunks_matched
)
)
or (
# Prefer match failures with entities
(result.text_chunks_matched == maybe_result.text_chunks_matched)
and (num_unmatched_entities == best_num_unmatched_entities)
and (num_unmatched_ranges == best_num_unmatched_ranges)
and (
("name" in result.entities)
or ("name" in result.unmatched_entities)
)
)
):
maybe_result = result
best_num_matched_entities = num_matched_entities
best_num_unmatched_entities = num_unmatched_entities
best_num_unmatched_ranges = num_unmatched_ranges
# Update cache
self._intent_cache.put(
cache_key,
IntentCacheValue(result=maybe_result, stage=IntentMatchingStage.FUZZY),
)
_LOGGER.debug(
"Did fuzzy match in %s second(s)", time.monotonic() - start_time
)
return maybe_result
def _get_unexposed_entity_names(self, text: str) -> TextSlotList:
"""Get filtered slot list with unexposed entity names in Home Assistant."""
if self._unexposed_names_trie is None:
# Build trie
self._unexposed_names_trie = Trie()
for name_tuple in self._get_entity_name_tuples(exposed=False):
self._unexposed_names_trie.insert(
name_tuple[0].lower(),
TextSlotValue.from_tuple(name_tuple, allow_template=False),
)
# Build filtered slot list
text_lower = text.strip().lower()
return TextSlotList(
name="name",
values=[
result[2] for result in self._unexposed_names_trie.find(text_lower)
],
)
def _get_entity_name_tuples(
self, exposed: bool
) -> Iterable[tuple[str, str, dict[str, Any]]]:
"""Yield (input name, output name, context) tuples for entities."""
entity_registry = er.async_get(self.hass)
for state in self.hass.states.async_all():
entity_exposed = async_should_expose(self.hass, DOMAIN, state.entity_id)
if exposed and (not entity_exposed):
# Required exposed, entity is not
continue
if (not exposed) and entity_exposed:
# Required not exposed, entity is
continue
# Checked against "requires_context" and "excludes_context" in hassil
context = {"domain": state.domain}
if state.attributes:
# Include some attributes
for attr in DEFAULT_EXPOSED_ATTRIBUTES:
if attr not in state.attributes:
continue
context[attr] = state.attributes[attr]
if (
entity := entity_registry.async_get(state.entity_id)
) and entity.aliases:
for alias in entity.aliases:
alias = alias.strip()
if not alias:
continue
yield (alias, alias, context)
# Default name
yield (state.name, state.name, context)
def _recognize_strict(
self,
user_input: ConversationInput,
lang_intents: LanguageIntents,
slot_lists: dict[str, SlotList],
intent_context: dict[str, Any] | None,
language: str,
) -> RecognizeResult | None:
"""Search intents for a strict match to user input."""
return recognize_best(
user_input.text,
lang_intents.intents,
slot_lists=slot_lists,
intent_context=intent_context,
language=language,
best_metadata_key=METADATA_CUSTOM_SENTENCE,
best_slot_name="name",
)
async def _build_speech(
self,
language: str,
response_template: template.Template,
intent_response: intent.IntentResponse,
recognize_result: RecognizeResult,
) -> str:
# Make copies of the states here so we can add translated names for responses.
matched = [
state_copy
for state in intent_response.matched_states
if (state_copy := core.State.from_dict(state.as_dict()))
]
unmatched = [
state_copy
for state in intent_response.unmatched_states
if (state_copy := core.State.from_dict(state.as_dict()))
]
all_states = matched + unmatched
domains = {state.domain for state in all_states}
translations = await translation.async_get_translations(
self.hass, language, "entity_component", domains
)
# Use translated state names
for state in all_states:
device_class = state.attributes.get("device_class", "_")
key = f"component.{state.domain}.entity_component.{device_class}.state.{state.state}"
state.state = translations.get(key, state.state)
# Get first matched or unmatched state.
# This is available in the response template as "state".
state1: core.State | None = None
if intent_response.matched_states:
state1 = matched[0]
elif intent_response.unmatched_states:
state1 = unmatched[0]
# Render response template
speech_slots = {
entity_name: entity_value.text or entity_value.value
for entity_name, entity_value in recognize_result.entities.items()
}
speech_slots.update(intent_response.speech_slots)
speech = response_template.async_render(
{
# Slots from intent recognizer and response
"slots": speech_slots,
# First matched or unmatched state
"state": (
template.TemplateState(self.hass, state1)
if state1 is not None
else None
),
"query": {
# Entity states that matched the query (e.g, "on")
"matched": [
template.TemplateState(self.hass, state) for state in matched
],
# Entity states that did not match the query
"unmatched": [
template.TemplateState(self.hass, state) for state in unmatched
],
},
}
)
# Normalize whitespace
if speech is not None:
speech = str(speech)
speech = " ".join(speech.strip().split())
return speech
async def async_reload(self, language: str | None = None) -> None:
"""Clear cached intents for a language."""
if language is None:
self._lang_intents.clear()
_LOGGER.debug("Cleared intents for all languages")
else:
self._lang_intents.pop(language, None)
_LOGGER.debug("Cleared intents for language: %s", language)
# Intents have changed, so we must clear the cache
self._intent_cache.clear()
async def async_prepare(self, language: str | None = None) -> None:
"""Load intents for a language."""
if language is None:
language = self.hass.config.language
lang_intents = await self.async_get_or_load_intents(language)
# No intents loaded
if lang_intents is None:
return
self._make_slot_lists()
async def async_get_or_load_intents(self, language: str) -> LanguageIntents | None:
"""Load all intents of a language with lock."""
if lang_intents := self._lang_intents.get(language):
return (
None
if lang_intents is ERROR_SENTINEL
else cast(LanguageIntents, lang_intents)
)
async with self._load_intents_lock:
# In case it was loaded now
if lang_intents := self._lang_intents.get(language):
return (
None
if lang_intents is ERROR_SENTINEL
else cast(LanguageIntents, lang_intents)
)
start = time.monotonic()
result = await self.hass.async_add_executor_job(
self._load_intents, language
)
if result is None:
self._lang_intents[language] = ERROR_SENTINEL
else:
self._lang_intents[language] = result
_LOGGER.debug(
"Full intents load completed for language=%s in %.2f seconds",
language,
time.monotonic() - start,
)
return result
def _load_intents(self, language: str) -> LanguageIntents | None:
"""Load all intents for language (run inside executor)."""
intents_dict: dict[str, Any] = {}
language_variant: str | None = None
supported_langs = set(get_languages())
# Choose a language variant upfront and commit to it for custom
# sentences, etc.
all_language_variants = {lang.lower(): lang for lang in supported_langs}
# en-US, en_US, en, ...
for maybe_variant in _get_language_variations(language):
matching_variant = all_language_variants.get(maybe_variant.lower())
if matching_variant:
language_variant = matching_variant
break
if not language_variant:
_LOGGER.warning(
"Unable to find supported language variant for %s", language
)
return None
# Load intents for this language variant
lang_variant_intents = get_intents(language_variant, json_load=json_load)
if lang_variant_intents:
# Merge sentences into existing dictionary
# Overriding because source dict is empty
intents_dict = lang_variant_intents
_LOGGER.debug(
"Loaded built-in intents for language=%s (%s)",
language,
language_variant,
)
# Check for custom sentences in <config>/custom_sentences/<language>/
custom_sentences_dir = Path(
self.hass.config.path("custom_sentences", language_variant)
)
if custom_sentences_dir.is_dir():
for custom_sentences_path in custom_sentences_dir.rglob("*.yaml"):
with custom_sentences_path.open(
encoding="utf-8"
) as custom_sentences_file:
# Merge custom sentences
if not isinstance(
custom_sentences_yaml := yaml.safe_load(custom_sentences_file),
dict,
):
_LOGGER.warning(
"Custom sentences file does not match expected format path=%s",
custom_sentences_file.name,
)
continue
# Add metadata so we can identify custom sentences in the debugger
custom_intents_dict = custom_sentences_yaml.get("intents", {})
for intent_dict in custom_intents_dict.values():
intent_data_list = intent_dict.get("data", [])
for intent_data in intent_data_list:
sentence_metadata = intent_data.get("metadata", {})
sentence_metadata[METADATA_CUSTOM_SENTENCE] = True
sentence_metadata[METADATA_CUSTOM_FILE] = str(
custom_sentences_path.relative_to(
custom_sentences_dir.parent
)
)
intent_data["metadata"] = sentence_metadata
merge_dict(intents_dict, custom_sentences_yaml)
_LOGGER.debug(
"Loaded custom sentences language=%s (%s), path=%s",
language,
language_variant,
custom_sentences_path,
)
# Load sentences from HA config for default language only