Tool
Home Assistant Tool
Simple device requests like turn on/off lights, pause media players, etc.
Tool ID
home_assistant_tool
Creator
@crixle
Downloads
560+

Tool Content
python
"""
Editor: atgehrhardt
Editor's Note: I recommend tempering expectations when using this tool
Suggestions:
- Add Valves or UserValves for configurable variables
- Add logic to resolve device names from ID and allow controlling via device name. Device IDs are VERY specific and not very useful
    in a number or HA instances.
- Add additional logic that allows for specific control based on device type. It's unlikely any models short of the best available
    could reliably use this implementation to control devices other than lights.
"""

"""
title: Home Assistant Controls
author: Crixle
funding_url: https://github.com/open-webui
version: 0.1
"""

import os
import requests
from datetime import datetime
import json

HA_API_KEY = "YOUR API KEY"
HA_URL = "IP OR FQDN OF HA INSTANCE"
"""
Recommend that these are replaced with env variables ^^
"""


class Tools:
    def __init__(self):
        pass

    # Add your custom tools using pure Python code here, make sure to add type hints
    # Use Sphinx-style docstrings to document your tools, they will be used for generating tools specifications
    # Please refer to function_calling_filter_pipeline.py file from pipelines project for an example

    def controlDevice(self, entityID: str, domain: str, service: str) -> str:
        """
        Controls a device in Home Assistant for lights, switches, and media players.

        :param domain: The domain of the device being controlled. This could be light, switch, media_player, or climate.
        :param service: Either "turn_on" or "turn_off based on context.
        :param entityID: The entityID that the request is commanding.
        :return: A simple confirmation or an error. Do not restate or appreciate what the user says.
        """

        try:

            # Endpoint to control the light entity
            endpoint = f"{HA_URL}/api/services/{domain}/{service}"

            # Prepare the payload
            payload = json.dumps({"entity_id": entityID})

            # Make the HTTP POST request
            response = requests.post(
                endpoint,
                data=payload,
                headers={"Authorization": f"Bearer {HA_API_KEY}"},
            )

            # Check if the request was successful
            return "Successfully changed the device"
        except Exception as e:
            return f"An error occured: {e}"