import json from ..base_plugin import BasePlugin class Plugin(BasePlugin): def __init__(self, config: dict) -> None: super().__init__(config=config) self.light_map = self.get_light_map() def prompt(self): prompt = "These are the lights available:\n" + json.dumps( self.light_map, indent=2, ensure_ascii=False ) return prompt def tools(self): tools = [ { "type": "function", "function": { "name": "control_light", "function_to_call": self.tool_control_light, "description": "Control lights in users a home", "parameters": { "type": "object", "properties": { "entity_id": { "type": "string", "enum": self.available_lights(), "description": "What light entity to control", }, "state": { "type": "string", "enum": ["on", "off"], "description": "on or off", }, }, "required": ["room", "state"], }, }, } ] return tools def tool_control_light(self, entity_id: str, state: str): self.homeassistant.call_api(f"services/light/turn_{state}", payload={"entity_id": entity_id}) return json.dumps({"status": "success", "message": f"{entity_id} was turned {state}."}) def available_lights(self): available_lights = [] for room in self.light_map: for light in self.light_map[room]: available_lights.append(light["entity_id"]) return available_lights def get_light_map(self): template = ( "{% for state in states.light %}\n" + '{ "entity_id": "{{ state.entity_id }}", "name" : "{{ state.attributes.friendly_name }}", "room": "{{area_name(state.entity_id)}}"}\n' + "{% endfor %}\n" ) response = self.homeassistant.call_api(f"template", payload={"template": template}) light_map = {} for item_str in response.split("\n\n"): item_dict = json.loads(item_str) if item_dict["room"] not in light_map: light_map[item_dict["room"]] = [] light_map[item_dict["room"]].append( {"entity_id": item_dict["entity_id"], "name": item_dict["name"]} ) return light_map