Skip to content

Instantly share code, notes, and snippets.

@allenporter
Last active April 23, 2024 15:23
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save allenporter/e70d9eb090c7dbdd593cf526e07b4abe to your computer and use it in GitHub Desktop.
Save allenporter/e70d9eb090c7dbdd593cf526e07b4abe to your computer and use it in GitHub Desktop.
Home Assistant Blueprint: Conversation agent Agenda Notification
---
blueprint:
name: Conversation agent Agenda Notification
description:
Conversation agent generates a notification based on the upcoming calendar
agenda, location, and weather information.
domain: automation
input:
notify_time:
name: Notification time
description: Time the automation is triggered to send the notification.
selector:
time: {}
default: 07:00:00
notify_service:
name: Notify service name
description:
The name of the notify service where the notification should be
sent.
selector:
text: {}
default: notify.notify
notify_target:
name: Notify target
description: The target of the notify service.
selector:
text: {}
default:
calendar_entity:
name: Calendar
description: The calendar entity to use for finding upcoming calendar events.
selector:
entity:
multiple: false
filter:
- domain:
- calendar
calendar_duration:
name: Calendar Event duration
description: How many hours ahead to look for upcoming calendar events.
selector:
duration:
default:
hours: 18
weather_entity:
name: Weather Entity
description: The weather entity to use for upcoming weather forecast.
selector:
entity:
multiple: false
filter:
- domain:
- weather
zone_entity:
name: Home Zone Entity
description:
The zone entity to use to determine approximate location for understanding
typical weather.
selector:
entity:
multiple: false
filter:
- domain:
- zone
conversation_agent:
name: Conversation Agent
selector:
conversation_agent:
prompt:
name: Conversation Agent Prompt
selector:
text:
multiline: true
type: text
default: |-
Please generate text for a notification that will be sent to the users
smartphone with helpful information.
You are a helpful personal agent that generates text for the user:
- Your answers are helpful, friendly, warm, insightful.
- Your answers are not technical, and do not include Home Assistant internal details such as entities in responses.
- Your messages help the user prepare for their day, for example:
- Making note of unusual weather for the location and time of year (but not mundane details like "0% chance of precipitation")
- How much time remaining until their first meeting
- Anything that may be special or unique, such as celebrating a birthday
trigger:
platform: time
at: !input notify_time
action:
- variables:
weather_entity: !input weather_entity
calendar_entity: !input calendar_entity
zone_entity: !input zone_entity
calendar_duration: !input calendar_duration
prompt: !input prompt
- alias: Fetch Weather Forecast
service: weather.get_forecasts
data:
type: hourly
target:
entity_id:
- "{{ weather_entity }}"
response_variable: daily_forecast
- variables:
forecast_entity: "{{ daily_forecast[weather_entity] }}"
forecast: "{{ forecast_entity.forecast[0] }}"
- alias: Fetch Calendar Agenda
service: calendar.get_events
data:
duration: !input calendar_duration
target:
entity_id: !input calendar_entity
response_variable: events_response
- alias: "Conversation Agent Notification Text"
service: conversation.process
data:
text: |-
Time: {{ now().strftime("%A %B %d %H:%M %p") }}
{%- if weather_entity is defined %}
{%- set temperature_unit = state_attr(weather_entity, 'temperature_unit') -%}
Forecast: {{ forecast.condition }} ({{ forecast.temperature }}{{ temperature_unit }}, {{ forecast.precipitation }}% precipitation)
{%- endif %}
Calendar "{{ state_attr(calendar_entity, 'friendly_name') }}" events for the next {{ calendar_duration.hours }}:
{%- set agenda = (events_response | items | first)[1] %}
{%- if agenda.events %}
{%- for event in agenda.events %}
- Summary: {{ event.summary }}
Start-End: {% if event.start is defined %}{{ event.start }} to {{ event.end }}{% else %}All Day{% endif %}
{%- if event.description is defined %}
Description: {{ event.description }}
{% endif -%}
{%- if event.location is defined %}
Location: {{ event.location }}
{% endif -%}
{%- endfor %}
{%- else %}
- No upcoming events.
{%- endif %}
{{ prompt }}
agent_id: !input conversation_agent
response_variable: agent
- alias: "Send notification"
service: !input notify_service
data:
target: !input notify_target
title: "{{ now().strftime('%A') }} Agenda"
message: "{{ agent.response.speech.plain.speech }}"
@allenporter
Copy link
Author

The blueprint duration has been updated to use a duration selector instead of an hours field.

@bobvmierlo
Copy link

I get an error when trying to import your blueprint.
Running 2023.7.0b0 and have OpenAI integration installed.

Invalid blueprint: Unknown selector type conversation_agent found for dictionary value @ data['blueprint']['input']['conversation_agent']['selector']. Got {'conversation_agent': None}

@allenporter
Copy link
Author

allenporter commented Jun 29, 2023 via email

@Anto79-ops
Copy link

hey, using this on b1 and working well.

anyway you can add multiple calendars and notify entities to the same automation?

by the way, how to I watch this link for updates? thanks

@allenporter
Copy link
Author

@Anto79-ops you would have to modify the blueprint to call multiple calendars and combine the results in the prompt jinja template. My impression is you can click the Subscribe button to see updates here, but I don't really plan to update this much. I might recommend someone make a post in the home assistant community forum to take this idea further -- (blueprint development is not an expertise of mine, just had enough to get this working)

@Anto79-ops
Copy link

Thanks Allen.

@fixtse
Copy link

fixtse commented Aug 29, 2023

Hey, Thank you for this blueprint, I made a video about it some time ago, and only now found your original gist.
There is a typo in lines 120 and 121, there should say description, no descripton
I Took the liberty of making a version with that fixed and also made a modified version that supports multiple calendars and notify services. Didn't know how to reach out before 😅.

@smartmatic
Copy link

Hey,
first fo all thank you for the Blueprint!
The blueprint is very useful but my OpenAI free trail expired. Then i switched to Home Assistant conversation agent. But it seems that only OpenAI works with that blueprint. Is that correct?

@fixtse
Copy link

fixtse commented Nov 7, 2023

Try the Google IA integration, the blueprint needs a GPT language processor to work, the home assistant conversation won't know what to do with the information provided.

@smartmatic
Copy link

Thx for the tip. I am now on the waitlist, hopefully i can get soon an API Key. If i see it right and compared to OpenAI the Google AI is currently free of charge? (My OpenAI test period expired, therefore i am no longer able to use the capability for free)

@pdsccode
Copy link

pdsccode commented Dec 8, 2023

Please update the blueprint to reflect the service call changes for calendars 🙂

@allenporter
Copy link
Author

@pdsccode Updated

@pdsccode
Copy link

Awesome, thanks 👍

@Progaros
Copy link

Progaros commented Dec 17, 2023

really cool blueprint!
i added multiple calendars, tasks, output language & user name:

blueprint:
  name: Daily Conversation Agent Agenda Notification
  description: |
    Conversation agent generates a personalized notification based on the
    upcoming calendar agenda, tasks, birthday reminders, location, and weather information in your language.
  domain: automation
  input:
    language:
      name: Language
      description: Language of Assistant Response
      selector:
        language:
      default: "en"
    user:
      name: User
      description: User who is being addressed
      selector:
        entity:
          multiple: false
          filter:
            domain:
              - person
    notify_time:
      name: Notification time
      description: Time the automation is triggered to send the notification.
      selector:
        time: {}
      default: 07:00:00
    notify_service:
      name: Notify service name
      description: The name of the notify service where the notification should be sent.
      selector:
        text: {}
      default: notify.notify
    notify_target:
      name: Notify target
      description: The target of the notify service.
      selector:
        text: {}
      default:
    task_entities:
      name: Tasks
      description: The tasks entities to use for finding upcoming todos.
      selector:
        entity:
          multiple: true
          filter:
            domain:
              - todo
    calendar_entities:
      name: Calendar
      description: The calendar entities to use for finding upcoming calendar events.
      selector:
        entity:
          multiple: true
          filter:
            domain:
              - calendar
    calendar_duration:
      name: Calendar Event duration
      description: How many hours ahead to look for upcoming calendar events.
      selector:
        duration:
      default:
        hours: 18
    birthday_calendar:
      name: Birthday Calendar
      description: The calendar entity to use for finding upcoming birthdays.
      selector:
        entity:
          multiple: false
          filter:
            domain:
              - calendar
    birthday_duration:
      name: Birthday Reminder duration
      description: How many days ahead to look for upcoming birthdays.
      selector:
        duration:
          enable_day: true
      default:
        days: 7
    weather_entity:
      name: Weather Entity
      description: The weather entity to use for upcoming weather forecast.
      selector:
        entity:
          multiple: false
          filter:
            domain:
              - weather
    zone_entity:
      name: Home Zone Entity
      description: The zone entity to use to determine approximate location for understanding typical weather.
      selector:
        entity:
          multiple: false
          filter:
            domain:
              - zone
    conversation_agent:
      name: Conversation Agent
      selector:
        conversation_agent:
    user_prompt_task:
      name: Conversation Agent Task
      selector:
        text:
          multiline: true
          type: text
      default: |-
        Please generate a short text (~100 words, no newlines) for a notification for an android smartphone with helpful information.

trigger:
  platform: time
  at: !input notify_time

action:
  - variables:
      language: !input language
      user: !input user
      weather_entity: !input weather_entity
      task_entities: !input task_entities
      calendar_entities: !input calendar_entities
      zone_entity: !input zone_entity
      calendar_duration: !input calendar_duration
      birthday_calendar: !input birthday_calendar
      birthday_duration: !input birthday_duration
      user_prompt_task: !input user_prompt_task
  - alias: Fetch Tasks
    service: todo.get_items
    data:
      status:
        - needs_action
    target:
      entity_id: !input task_entities
    response_variable: tasks_responses
  - alias: Fetch Calendar Agenda
    service: calendar.get_events
    data:
      duration: !input calendar_duration
    target:
      entity_id: !input calendar_entities
    response_variable: events_responses
  - alias: Fetch Birthday Calendar
    service: calendar.get_events
    data:
      duration: !input birthday_duration
    target:
      entity_id: !input birthday_calendar
    response_variable: birthday_responses
  - alias: Get Weather Forecast
    service: weather.get_forecasts
    data:
      type: daily
    target:
      entity_id: !input weather_entity
    response_variable: weekly_weather_forecast
  - alias: "Prepare Prompt"
    variables:
      prompt: |-


        # You are a helpful personal agent that generates notifications for the user:

        - You should respond in the RFC 5646 language: "{{language}}"
        - Your answers are helpful, friendly, warm, insightful.
        - Your answers are not technical, and do not include Home Assistant internal details such as entities in responses.
        - Your messages help the user prepare for their day, for example:
        - Making note of unusual weather for the location and time of year (but not mundane details like "0% chance of precipitation"). 
        - Do not tell the user his location or the current time.
        - How much time remaining until their first meeting
        - Anything that may be special or unique, such as celebrating a birthday (but not that there are no birthdays)

        # Information to include in the notification:

        Name of User: {{ state_attr(user, "friendly_name") }}

        Time: {{ now().time().isoformat('minutes') }}

        {%- if zone_entity is defined %}
        Latitude: {{ state_attr(zone_entity, 'latitude') | round(1) }}
        Longitude: {{ state_attr(zone_entity, 'longitude') | round(1) }}
        {% endif %}

        {%- if weather_entity is defined %}
        {%- set temperature_unit = state_attr(weather_entity, 'temperature_unit') -%}
        {%- set todays_forecast = weekly_weather_forecast[weather_entity]['forecast'][0] %}
        Weather: {{ todays_forecast.condition }} ({{ todays_forecast.temperature }}{{ temperature_unit }}, {{ todays_forecast.precipitation }}% precipitation)
        {%- endif %}

        # Tasks Lists:
        {%- for task_entity in task_entities %}
          Upcoming tasks for today on list "{{ state_attr(task_entity, 'friendly_name') }}":
          {%- set tasks = tasks_responses[task_entities[loop.index0]] %}
          {%- for task in tasks['items'] %}
          {%- if 'due' in task and now().date() == as_datetime(task.due, "2222-11-11").date() %}
          - {{task['summary']}}
          {%- endif %}
          {%- endfor %}
        {%- endfor %}

        # Calendar Events:
        {%- for calendar_entity in calendar_entities %}
          Calendar "{{ state_attr(calendar_entity, 'friendly_name') }}" events for the next {{ calendar_duration.hours }} hours:
          {%- set agenda = events_responses[calendar_entities[loop.index0]] %}
          {%- if "events" in agenda and agenda.events %}
            {%- for event in agenda.events %}
            - Summary: {{ event.summary }}
              Start-End: {% if event.start is defined %}{{ event.start }} to {{ event.end }}{% else %}All Day{% endif %}
              {%- if event.descripton is defined %}
              Descripton: {{ event.descripton }}
              {% endif -%}
              {%- if event.location is defined %}
                Location: {{ event.location }}
              {% endif -%}
            {%- endfor %}
          {%- else %}
            - No upcoming events.
          {%- endif %}
        {%- endfor %}

        # Upcoming birthdays:
        {%- set birthdays = birthday_responses[birthday_calendar] %}
        {%- if "events" in birthdays and birthdays.events %}
          {%- for event in birthdays.events %}
          - Birthday Reminder: {{ event.summary }} on {{ event.start }}
          {%- endfor %}
        {%- else %}
          - No upcoming birthdays.
        {%- endif %}

        # Task:

        {{ user_prompt_task }}
  - alias: "Conversation Agent Notification Text"
    service: conversation.process
    data:
      text: "{{ prompt }}"
      agent_id: !input conversation_agent
    response_variable: agent
  - alias: "Send notification"
    service: !input notify_service
    data:
      target: !input notify_target
      title: "{{ now().strftime('%A') }} Agenda"
      message: "{{ agent.response.speech.plain.speech }}"

updated for HA 2024.4 - thanks @chlaa

added tasks

@OnktheMonk
Copy link

Great blueprint. I use it to get a notification on my phone for my appointments of the day. But is sometimes does not show all the appointments. Sometimes cutting off halfway a sentence. I already added in the promt a max character of 255.

@purpleturtle1988
Copy link

Would it be possible to make this Blueprint so that it writes the text in a Text Helper instead of a notification? This would allow my smart speakers to read out my appointments to me. :-)

@Progaros
Copy link

Would it be possible to make this Blueprint so that it writes the text in a Text Helper instead of a notification? This would allow my smart speakers to read out my appointments to me. :-)

This adds an optional text helper, but only for 255char since that's the limit for text helpers:

blueprint:
  name: Daily Conversation agent Agenda Notification
  description:
    Conversation agent generates a personalized notification based on the
    upcoming calendar agenda, location, and weather information in your language.
  domain: automation
  input:
  # ... (rest of the input fields)
    text_helper:
      name: Text Helper
      description: Text helper for notification message (optional)
      selector:
        entity:
          domain: input_text
      default: ""

trigger:
  platform: time
  at: !input notify_time

action:
  - variables:
  # ... (rest of the variables)
      text_helper: !input text_helper
  # ... (rest of the actions)
  - alias: "Store notification text in text helper"
    choose:
      - conditions:
          - condition: template
            value_template: "{{ text_helper != '' }}"
        sequence:
          - service: input_text.set_value
            target:
              entity_id: "{{ text_helper }}"
            data:
              value: "{{ agent.response.speech.plain.speech | truncate(255) }}" # Limit to 255 characters
  - alias: "Send notification"
    service: !input notify_service
    data:
      target: !input notify_target
      title: "{{ now().strftime('%A') }} Agenda"
      message: "{{ agent.response.speech.plain.speech }}"

@purpleturtle1988
Copy link

That works wonderfully! Thank you for your quick reply and the revised blueprint! Do you happen to know why, despite the time zone being configured correctly in Home Assistant, it always shows one hour off? So instead of 12:00 - 11:00. My time zone is Central European Time Zone (CET), I've already written the prompt that way, but it still doesn't work :-D.

@Progaros
Copy link

Progaros commented Feb 17, 2024

Time {{ now() }} was always correct_time +1 (2024-02-17 16:16:00.283692+01:00)
{{ now().time().isoformat('minutes') }} seems to work (16:16)
you can test it here: https://{{yourHA.instance}}/developer-tools/template
Glad to help :)

@Anto79-ops
Copy link

looks like this will break on 2024.4 due to the depracation of to get weather forecasts:

{%- set forecast = state_attr(weather_entity, 'forecast')[0] %}

the line above wont work

@chlaa
Copy link

chlaa commented Apr 5, 2024

looks like this will break on 2024.4 due to the depracation of to get weather forecasts:

{%- set forecast = state_attr(weather_entity, 'forecast')[0] %}

the line above wont work

For those who want to replace forecast with weather.get_forecasts the following can to be added to the blueprint:
- alias: Get Weather Forecast
service: weather.get_forecasts
data:
type: daily
target:
entity_id: !input weather_entity
response_variable: weekly_weather_forecast

and the prompt text modified to include the following to take todays forecast from the response:
{%- if weather_entity is defined %}
{%- set temperature_unit = state_attr(weather_entity, 'temperature_unit') -%}
{%- set todays_forecast = weekly_weather_forecast[weather_entity]['forecast'][0] %}
Weather: {{ todays_forecast.condition }} ({{ todays_forecast.temperature }}{{ temperature_unit }}, {{ todays_forecast.precipitation }}% precipitation)
{%- endif %}

@allenporter
Copy link
Author

allenporter commented Apr 6, 2024

I updated with the current version I am using.

@Minius90
Copy link

I tried different calendars and weather entities but everytime I execute the automation it stops, showing the following error: Error rendering data template: UndefinedError: None has no element 0
Any idea how I could solve this?

@allenporter
Copy link
Author

I tried different calendars and weather entities but everytime I execute the automation it stops, showing the following error: Error rendering data template: UndefinedError: None has no element 0 Any idea how I could solve this?

Give another try. I may have had a stale version here without the weather updates.

@Minius90
Copy link

I tried different calendars and weather entities but everytime I execute the automation it stops, showing the following error: Error rendering data template: UndefinedError: None has no element 0 Any idea how I could solve this?

Give another try. I may have had a stale version here without the weather updates.

Perfect, thank you very much! works like a charm now

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment