Pierre Wessman 7b45d19308 init
2025-01-16 16:22:58 +01:00

108 lines
3.7 KiB
Python

import asyncio
import json
from ..base_plugin import BasePlugin
class Plugin(BasePlugin):
def __init__(self, config: dict) -> None:
super().__init__(config=config)
def prompt(self):
prompt = "These are the todo lists available:\n" + json.dumps(
self.get_todo_lists(), indent=2, ensure_ascii=False
)
return prompt
def tools(self):
tools = [
{
"type": "function",
"function": {
"name": "get_todo_list_items",
"function_to_call": self.get_todo_list_items,
"description": "Get items from todo-list.",
"parameters": {
"type": "object",
"properties": {
"entity_id": {
"type": "string",
"description": "What list to get items from.",
}
},
"required": ["entity_id"],
},
},
},
{
"type": "function",
"function": {
"name": "add_todo_item",
"function_to_call": self.add_todo_item,
"description": "Add item to todo-list.",
"parameters": {
"type": "object",
"properties": {
"entity_id": {
"type": "string",
"description": "What list to add item to.",
},
"item": {
"type": "string",
"description": "Description of the item.",
},
},
"required": ["entity_id", "item"],
},
},
},
]
return tools
def get_todo_list_items(self, entity_id: str = None):
"""
Get items from todo-list.
"""
if entity_id is None:
entity_id = self.config["plugins"]["todo"]["default_list"]
response = asyncio.run(
self.homeassistant.send_command(
"call_service",
domain="todo",
service="get_items",
target={"entity_id": entity_id},
service_data={"status": "needs_action"},
return_response=True,
)
)
return json.dumps(response["response"])
def add_todo_item(self, item: str, entity_id: str = None):
"""
Add item to todo-list.
"""
if entity_id is None:
entity_id = self.config["plugins"]["todo"]["default_list"]
asyncio.run(
self.homeassistant.send_command(
"call_service",
domain="todo",
service="add_item",
target={"entity_id": entity_id},
service_data={"item": item},
)
)
return json.dumps({"status": f"{item} added to list."})
def get_todo_lists(self):
template = (
"{% for state in states.todo %}\n"
+ '{ "entity_id": "{{ state.entity_id }}", "name" : "{{ state.attributes.friendly_name }}"}\n'
+ "{% endfor %}\n"
)
response = self.homeassistant.call_api(f"template", payload={"template": template})
todo_lists = {}
for item_str in response.split("\n\n"):
item_dict = json.loads(item_str)
todo_lists[item_dict["name"]] = item_dict["entity_id"]
return todo_lists