diff --git a/homeassistant/components/energy/llm.py b/homeassistant/components/energy/llm.py index 952adbb7c55f..2e14514be40d 100644 --- a/homeassistant/components/energy/llm.py +++ b/homeassistant/components/energy/llm.py @@ -1,6 +1,7 @@ """LLM tools for the energy integration.""" from typing import TYPE_CHECKING, Any, cast, override +import uuid import probatio @@ -22,9 +23,11 @@ from .const import BATTERY_DIRECTIONS, DOMAIN from .data import ( DEVICE_CONSUMPTION_SCHEMA, ENERGY_SOURCE_SCHEMA, + FIXED_COSTS_SCHEMA, EnergyManager, EnergyPreferences, EnergyPreferencesUpdate, + FixedCostType, async_get_manager, ) from .validate import async_validate @@ -117,6 +120,15 @@ _DEVICE_DESCRIPTION = ( "devices. stat_consumption is the meter of the device, included_in_stat the " "stat_consumption of a device whose meter also measures this device." ) +_FIXED_COST_FIELDS = ("type", "name", "number_amount", "entity_amount", "period") +_FIXED_COST: VolDictType = { + probatio.Optional("id"): _STR_OR_NONE, + probatio.Required("type"): str, + probatio.Required("name"): str, + probatio.Optional("number_amount"): _FLOAT_OR_NONE, + probatio.Optional("entity_amount"): _STR_OR_NONE, + probatio.Required("period"): str, +} _PARAMETERS = probatio.Schema( { @@ -178,6 +190,20 @@ _PARAMETERS = probatio.Schema( probatio.Optional( "device_consumption_gas", description=f"Gas {_DEVICE_DESCRIPTION}" ): [DEVICE_CONSUMPTION_SCHEMA], + probatio.Optional( + "fixed_costs", + description=( + "Fixed costs, like standing charges, that are charged at the start " + "of each period. type is grid, gas or water, and period is day, " + "month or year. The amount per period, in the currency of Home " + "Assistant, is the number in number_amount or the state of the " + "entity in entity_amount. id identifies an existing fixed cost: " + "send it back to change that fixed cost and keep its history. " + "Without id, a fixed cost takes the id of the current one with the " + "same type and name when it is clear which one that is. Send a new " + "id to start a fixed cost with a new history." + ), + ): [_FIXED_COST], } ) @@ -192,6 +218,36 @@ def _split_by_type( return split +def _with_ids( + current: list[FixedCostType], fixed_costs: list[dict[str, Any]] +) -> list[dict[str, Any]]: + """Return the fixed costs, each with an ID. + + A fixed cost without an ID reuses the ID of a current fixed cost that is the + same, or else of the only one with the same type and name, so a repeated call + keeps the sensors. Otherwise it gets a new ID. + """ + given = {fixed_cost.get("id") for fixed_cost in fixed_costs} + unclaimed = [existing for existing in current if existing["id"] not in given] + ids = [fixed_cost.get("id") for fixed_cost in fixed_costs] + for fields, unique in ((_FIXED_COST_FIELDS, False), (("type", "name"), True)): + for index, fixed_cost in enumerate(fixed_costs): + if ids[index]: + continue + matches = [ + existing + for existing in unclaimed + if all(existing.get(field) == fixed_cost.get(field) for field in fields) + ] + if matches and not (unique and len(matches) > 1): + unclaimed.remove(matches[0]) + ids[index] = matches[0]["id"] + return [ + {**fixed_cost, "id": fixed_cost_id or str(uuid.uuid4())} + for fixed_cost, fixed_cost_id in zip(fixed_costs, ids, strict=True) + ] + + def _format_preferences(preferences: EnergyPreferences) -> JsonObjectType: """Return the preferences with the energy sources per type, without the type.""" sources = [ @@ -203,6 +259,7 @@ def _format_preferences(preferences: EnergyPreferences) -> JsonObjectType: { **_split_by_type(preferences, sources), **{key: preferences.get(key, []) for key in _DEVICE_KEYS}, + "fixed_costs": preferences.get("fixed_costs", []), }, ) @@ -214,8 +271,9 @@ class GetPreferencesTool(Tool): title = "Get energy preferences" description = ( "Get the energy preferences that the energy dashboard uses: the grid, " - "solar, battery, gas, water and home energy sources, and the devices that " - "track their electricity, water and gas consumption." + "solar, battery, gas, water and home energy sources, the devices that " + "track their electricity, water and gas consumption, and the fixed costs, " + "like standing charges, of the grid, gas and water." ) annotations = ToolAnnotations( read_only=True, destructive=False, idempotent=True, open_world=False @@ -238,12 +296,13 @@ class UpdatePreferencesTool(Tool): name = "energy__update_preferences" title = "Update energy preferences" description = ( - "Update the energy preferences that the energy dashboard uses. Each given " - "list replaces the complete current list, so get the preferences first and " - "send all items of a list, also the items that do not change. Lists that " - "are not given stay the same. Fields that start with stat_ hold statistic " - "IDs, usually the entity IDs of sensors. stat_rate is a power or flow rate " - "sensor. Returns the new preferences and the validation issues of each item." + "Update the energy preferences that the energy dashboard uses: the energy " + "sources, the devices and the fixed costs. Each given list replaces the " + "complete current list, so get the preferences first and send all items of " + "a list, also the items that do not change. Lists that are not given stay " + "the same. Fields that start with stat_ hold statistic IDs, usually the " + "entity IDs of sensors. stat_rate is a power or flow rate sensor. Returns " + "the new preferences and the validation issues of each item." ) annotations = ToolAnnotations( read_only=False, destructive=True, idempotent=True, open_world=False @@ -272,6 +331,12 @@ class UpdatePreferencesTool(Tool): update["energy_sources"] = ENERGY_SOURCE_SCHEMA(sources) except probatio.Invalid as err: return ToolResult(data={"error": str(err)}, error=True) + if "fixed_costs" in args: + fixed_costs = _with_ids(current.get("fixed_costs", []), args["fixed_costs"]) + try: + update["fixed_costs"] = FIXED_COSTS_SCHEMA(fixed_costs) + except probatio.Invalid as err: + return ToolResult(data={"error": str(err)}, error=True) await manager.async_update(cast(EnergyPreferencesUpdate, update)) # Validation reads the preferences before its first await, so these are diff --git a/tests/components/energy/test_llm.py b/tests/components/energy/test_llm.py index 07c7239f928b..9cc8cfae2480 100644 --- a/tests/components/energy/test_llm.py +++ b/tests/components/energy/test_llm.py @@ -2,6 +2,7 @@ import json from typing import Any +import uuid import probatio import pytest @@ -37,6 +38,14 @@ BATTERY_SOURCE = { "stat_energy_to": "sensor.battery_in", "power_config": {"stat_rate_inverted": "sensor.battery_power"}, } +FIXED_COST = { + "id": "standing_charge", + "type": "grid", + "name": "Standing charge", + "number_amount": 0.5, + "entity_amount": None, + "period": "day", +} EMPTY_PREFERENCES = { "grid_sources": [], "solar_sources": [], @@ -47,6 +56,7 @@ EMPTY_PREFERENCES = { "device_consumption": [], "device_consumption_water": [], "device_consumption_gas": [], + "fixed_costs": [], } @@ -148,6 +158,7 @@ def _fields(schema: Any) -> set[str]: ("gas_sources", data.GAS_SOURCE_SCHEMA, None), ("water_sources", data.WATER_SOURCE_SCHEMA, None), ("home_sources", data.HOME_SOURCE_SCHEMA, None), + ("fixed_costs", data.FIXED_COST_SCHEMA, None), ], ) async def test_update_parameters_declare_all_fields( @@ -184,6 +195,7 @@ async def test_get_preferences(hass: HomeAssistant, api: llm.APIInstance) -> Non {"type": "grid", **GRID_SOURCE}, ], "device_consumption": [{"stat_consumption": "sensor.fridge"}], + "fixed_costs": [FIXED_COST], } ) @@ -195,6 +207,7 @@ async def test_get_preferences(hass: HomeAssistant, api: llm.APIInstance) -> Non "grid_sources": [GRID_SOURCE], "solar_sources": [SOLAR_SOURCE], "device_consumption": [{"stat_consumption": "sensor.fridge"}], + "fixed_costs": [FIXED_COST], } ) @@ -245,7 +258,6 @@ async def test_update_preferences(hass: HomeAssistant, api: llm.APIInstance) -> "solar_sources": 1, "battery_sources": 1, "device_consumption_water": 1, - "fixed_costs": 0, } assert validation["solar_sources"][0] == [ { @@ -277,6 +289,132 @@ async def test_update_preferences(hass: HomeAssistant, api: llm.APIInstance) -> json.dumps(result.data) +async def test_update_fixed_costs(hass: HomeAssistant, api: llm.APIInstance) -> None: + """Test that an update keeps the IDs of the fixed costs and adds missing ones.""" + tax_rebate = { + "id": "tax_rebate", + "type": "grid", + "name": "Tax rebate", + "number_amount": -10.0, + "entity_amount": None, + "period": "month", + } + manager = await async_get_manager(hass) + await manager.async_update( + { + "energy_sources": [{"type": "grid", **GRID_SOURCE}], + "fixed_costs": [FIXED_COST, tax_rebate], + } + ) + energy_sources = manager.data["energy_sources"] + tool_input = llm.ToolInput( + UPDATE_TOOL, + { + "fixed_costs": [ + {**FIXED_COST, "number_amount": 0.6}, + { + "type": "grid", + "name": "Standing charge", + "number_amount": 10, + "period": "month", + }, + { + "id": None, + "type": "grid", + "name": "Tax rebate", + "number_amount": -120, + "period": "year", + }, + { + "type": "gas", + "name": "Network fee", + "entity_amount": "sensor.network_fee", + "period": "month", + }, + ] + }, + ) + + result = await api.async_call_tool(tool_input) + + assert not result.error + fixed_costs = manager.data["fixed_costs"] + new_ids = [fixed_costs[1]["id"], fixed_costs[3]["id"]] + assert all(str(uuid.UUID(new_id)) == new_id for new_id in new_ids) + assert fixed_costs == [ + {**FIXED_COST, "number_amount": 0.6}, + { + "id": new_ids[0], + "type": "grid", + "name": "Standing charge", + "number_amount": 10.0, + "entity_amount": None, + "period": "month", + }, + {**tax_rebate, "number_amount": -120.0, "period": "year"}, + { + "id": new_ids[1], + "type": "gas", + "name": "Network fee", + "number_amount": None, + "entity_amount": "sensor.network_fee", + "period": "month", + }, + ] + assert manager.data["energy_sources"] == energy_sources + assert result.data["preferences"]["fixed_costs"] == fixed_costs + assert result.data["validation"]["fixed_costs"] == [ + [], + [], + [], + [ + { + "type": "entity_not_defined", + "affected_entities": [["sensor.network_fee", None]], + "translation_placeholders": None, + } + ], + ] + + # A repeated call finds the fixed costs without ID by type and name + result = await api.async_call_tool(tool_input) + + assert not result.error + assert manager.data["fixed_costs"] == fixed_costs + + +async def test_update_fixed_costs_same_name( + hass: HomeAssistant, api: llm.APIInstance +) -> None: + """Test the IDs that fixed costs without ID get when their name is not unique.""" + monthly = {**FIXED_COST, "id": "monthly", "number_amount": 10.0, "period": "month"} + manager = await async_get_manager(hass) + await manager.async_update({"fixed_costs": [FIXED_COST, monthly]}) + monthly_without_id = {key: value for key, value in monthly.items() if key != "id"} + daily_without_id = {key: value for key, value in FIXED_COST.items() if key != "id"} + + # Unchanged fixed costs keep their IDs, also in another order + result = await api.async_call_tool( + llm.ToolInput( + UPDATE_TOOL, {"fixed_costs": [monthly_without_id, daily_without_id]} + ) + ) + + assert not result.error + assert manager.data["fixed_costs"] == [monthly, FIXED_COST] + + # A changed fixed cost cannot tell which of the two it was + yearly = {**daily_without_id, "number_amount": 100.0, "period": "year"} + result = await api.async_call_tool( + llm.ToolInput(UPDATE_TOOL, {"fixed_costs": [yearly]}) + ) + + assert not result.error + [stored] = manager.data["fixed_costs"] + assert stored["id"] not in ("standing_charge", "monthly") + assert stored == {**yearly, "id": stored["id"]} + + async def test_update_preferences_round_trip( hass: HomeAssistant, api: llm.APIInstance ) -> None: @@ -288,7 +426,8 @@ async def test_update_preferences_round_trip( {"type": "grid", **GRID_SOURCE}, {"type": "solar", **SOLAR_SOURCE}, {"type": "battery", **BATTERY_SOURCE}, - ] + ], + "fixed_costs": [FIXED_COST], } ) stored = manager.data @@ -300,25 +439,48 @@ async def test_update_preferences_round_trip( assert manager.data == stored +@pytest.mark.parametrize( + ("tool_args", "error"), + [ + ( + {"home_sources": [{"stat_energy_to": "a"}, {"stat_energy_to": "b"}]}, + "Only one home source is allowed", + ), + ( + { + "solar_sources": [{"stat_energy_from": "sensor.solar"}], + "fixed_costs": [ + {**FIXED_COST, "entity_amount": "sensor.standing_charge"} + ], + }, + "Define either an entity or a fixed number for the amount at '[0]'", + ), + ( + {"fixed_costs": [{**FIXED_COST, "period": "week"}]}, + "value must be one of ['day', 'month', 'year'] at '[0].period'", + ), + ( + {"fixed_costs": [FIXED_COST, {**FIXED_COST, "type": "gas"}]}, + "Cannot specify standing_charge more than once", + ), + ], +) async def test_update_preferences_invalid( - hass: HomeAssistant, api: llm.APIInstance + hass: HomeAssistant, api: llm.APIInstance, tool_args: dict[str, Any], error: str ) -> None: """Test that invalid preferences return an error and change nothing.""" manager = await async_get_manager(hass) - await manager.async_update({"energy_sources": [{"type": "grid", **GRID_SOURCE}]}) + await manager.async_update( + { + "energy_sources": [{"type": "grid", **GRID_SOURCE}], + "fixed_costs": [FIXED_COST], + } + ) stored = manager.data - result = await api.async_call_tool( - llm.ToolInput( - UPDATE_TOOL, - {"home_sources": [{"stat_energy_to": "a"}, {"stat_energy_to": "b"}]}, - ) - ) + result = await api.async_call_tool(llm.ToolInput(UPDATE_TOOL, tool_args)) - assert result == llm.ToolResult( - data={"error": "Only one home source is allowed"}, - error=True, - ) + assert result == llm.ToolResult(data={"error": error}, error=True) assert manager.data == stored @@ -329,6 +491,7 @@ async def test_update_preferences_invalid( {"device_consumption": [{"name": "Fridge"}]}, {"device_consumption_gas": "sensor.gas"}, {"solar_sources": [{"stat_energy_from": "sensor.solar", "type": "grid"}]}, + {"fixed_costs": [{**FIXED_COST, "amount": 0.5}]}, ], ) async def test_update_preferences_invalid_args(