1515
1616from .const import CONF_LLM_HASS_API , CONF_PROMPT , DOMAIN
1717from .entity import AIHubBaseLLMEntity
18- from .intents import get_intents_config
18+ from .intents import get_config_cache
1919
2020_LOGGER = logging .getLogger (__name__ )
2121
@@ -65,6 +65,9 @@ def __init__(
6565
6666 super ().__init__ (entry , subentry , RECOMMENDED_CHAT_MODEL )
6767
68+ # 初始化配置缓存
69+ self ._config_cache = get_config_cache ()
70+
6871 # Enable control feature if LLM Hass API is configured
6972 if self .subentry .data .get (CONF_LLM_HASS_API ):
7073 self ._attr_supported_features = (
@@ -147,7 +150,8 @@ async def _async_handle_message(
147150 except Exception as e :
148151 _LOGGER .error (f"❌ LLM_API_ASSIST获取失败: { e } " )
149152 empty_response = intent .IntentResponse (language = user_input .language )
150- empty_response .async_set_speech ("LLM配置出现问题,请检查集成设置。" )
153+ error_msg = self ._config_cache .get_error_message ("llm_config_error" )
154+ empty_response .async_set_speech (error_msg )
151155 return conversation .ConversationResult (
152156 response = empty_response ,
153157 conversation_id = user_input .conversation_id
@@ -225,11 +229,10 @@ def _is_device_operation(self, tool_name: str) -> bool:
225229 async def _verify_device_operations_with_retry (self , device_operations ):
226230 """验证设备操作并重试,使用配置的时间限制"""
227231 try :
228- from .intents import get_device_verification_config
229- config = get_device_verification_config ()
232+ config = self ._config_cache .get_verification_config ()
230233 except Exception as e :
231234 _LOGGER .debug (f"获取验证配置失败: { e } " )
232- # 使用默认配置
235+ # 使用硬编码的备用配置
233236 config = {
234237 'total_timeout' : 3 ,
235238 'max_retries' : 3 ,
@@ -291,16 +294,8 @@ async def _verify_device_operations_with_retry(self, device_operations):
291294 async def _get_live_context (self ):
292295 """获取当前设备状态 (模拟GetLiveContext工具)"""
293296 # 这里应该调用实际的GetLiveContext工具
294- # 暂时返回模拟数据
295- return {
296- "lights" : {"living_room_main" : "off" , "living_room_ambient" : "on" },
297- "switches" : {},
298- "climate" : {},
299- "covers" : {},
300- "media_players" : {},
301- "locks" : {},
302- "vacuums" : {}
303- }
297+ # 从配置中读取模拟数据
298+ return self ._config_cache .get_device_state_simulation ()
304299
305300 def _is_operation_successful (self , operation , context ):
306301 """检查单个操作是否成功"""
@@ -347,15 +342,10 @@ async def _handle_automation_request(
347342 """Handle automation creation requests."""
348343 user_text = user_input .text .lower ()
349344
350- # 加载配置获取自动化关键词
345+ # 使用配置缓存获取自动化关键词
351346 try :
352- from .intents import get_intents_config
353- config = get_intents_config ()
354- if not config :
355- _LOGGER .debug ("No config available for automation keywords" )
356- return None
347+ automation_keywords = self ._config_cache .get_automation_config ('automation_keywords' , [])
357348
358- automation_keywords = config .get ('automation_keywords' , [])
359349 if not automation_keywords :
360350 _LOGGER .debug ("No automation_keywords found in config" )
361351 return None
@@ -387,27 +377,27 @@ async def _handle_automation_request(
387377 automation_name = config_data .get ("alias" , "新自动化" )
388378
389379 # 使用配置化的成功消息
390- intents_config = get_intents_config ()
391- responses = intents_config .get ('responses' , {}) if intents_config else {}
380+ responses = self ._config_cache .get_responses_config ()
392381 success_template = responses .get ('automation' , {}).get ('creation_success' )
393382 if success_template :
394383 try :
395384 message = success_template .format (automation_name = automation_name )
396385 except KeyError :
397386 message = success_template
398387 else :
388+ default_template = self ._config_cache .get_error_message ("automation_default_name" )
399389 message = f"我已经为您创建了自动化: { automation_name } "
400390
401391 # 可以添加更多配置详情
402392 if config_data .get ("trigger" ):
403- triggers = [t .get ("platform" , "unknown" ) for t in config_data ["trigger" ]]
393+ unknown_platform = self ._config_cache .get_error_message ("automation_trigger_unknown" )
394+ triggers = [t .get ("platform" , unknown_platform ) for t in config_data ["trigger" ]]
404395 message += f"\\ n触发条件: { ', ' .join (triggers )} "
405396
406397 intent_response .async_set_speech (message )
407398 else :
408399 # 使用配置化的错误消息
409- intents_config = get_intents_config ()
410- responses = intents_config .get ('responses' , {}) if intents_config else {}
400+ responses = self ._config_cache .get_responses_config ()
411401 error_template = responses .get ('automation' , {}).get ('creation_error' )
412402 if error_template :
413403 try :
@@ -433,15 +423,9 @@ async def _handle_automation_request(
433423
434424 def _extract_automation_description (self , user_text : str ) -> Optional [str ]:
435425 """Extract automation description from user input."""
436- # 加载配置获取自动化前缀
426+ # 使用配置缓存获取自动化前缀
437427 try :
438- from .intents import get_intents_config
439-
440- config = get_intents_config ()
441- if not config :
442- prefixes = []
443- else :
444- prefixes = config .get ('automation_prefixes' , [])
428+ prefixes = self ._config_cache .get_automation_config ('automation_prefixes' , [])
445429
446430 except Exception as e :
447431 _LOGGER .debug ("Failed to load automation prefixes: %s" , e )
@@ -474,14 +458,9 @@ def _is_all_device_operation(self, intent_info: Dict[str, Any]) -> bool:
474458 """判断是否是"所有设备"操作"""
475459 text = intent_info .get ("text" , "" ).lower ()
476460
477- # 从配置中读取"所有"相关的关键词 ,避免硬编码
461+ # 使用配置缓存获取全局关键词 ,避免硬编码
478462 try :
479- config = get_intents_config ()
480- global_config = config .get ('GlobalDeviceControl' , {}) if config else {}
481- global_keywords = global_config .get ('global_keywords' , []) if global_config else []
482- if not global_keywords :
483- # 如果配置中没有,使用默认值
484- global_keywords = ["所有" , "全部" , "一切" ]
463+ global_keywords = self ._config_cache .get_global_keywords ()
485464 except Exception as e :
486465 _LOGGER .debug (f"读取global_keywords失败,使用默认值: { e } " )
487466 global_keywords = ["所有" , "全部" , "一切" ]
@@ -492,20 +471,12 @@ def _has_local_intent_config(self, intent_type: str, intent_info: Dict[str, Any]
492471 """检查意图是否在本地配置中定义为需要特殊处理"""
493472 text = intent_info .get ("text" , "" ).lower ()
494473
495- # 从intents.yaml中读取本地特征配置,避免硬编码
496- local_features = []
474+ # 使用配置缓存获取本地特征关键词,避免硬编码
497475 try :
498- intents_config = get_intents_config ()
499- if intents_config and 'expansion_rules' in intents_config :
500- # 获取所有本地特征关键词
501- for key , value in intents_config ['expansion_rules' ].items ():
502- if isinstance (value , str ) and '|' in value :
503- # 拆分管道符分隔的关键词
504- local_features .extend (value .split ('|' ))
505- _LOGGER .debug (f"从intents.yaml加载本地特征关键词: { len (local_features )} 个" )
476+ local_features = self ._config_cache .get_local_features ()
477+ _LOGGER .debug (f"从配置缓存加载本地特征关键词: { len (local_features )} 个" )
506478 except Exception as e :
507479 _LOGGER .debug (f"读取本地配置失败,使用默认值: { e } " )
508- # 如果配置读取失败,使用默认的关键词(从配置中读取)
509480 local_features = ["所有设备" , "全部设备" , "所有灯" , "全部灯" ]
510481
511482 return any (feature in text for feature in local_features )
@@ -518,8 +489,7 @@ def _should_skip_ha_standard_processing(self, text: str) -> bool:
518489 - "关闭所有灯"
519490 """
520491 try :
521- from .intents import get_intents_config
522- config = get_intents_config ()
492+ config = self ._config_cache .get_config ()
523493 if not config :
524494 return False
525495
0 commit comments