Skip to main content
Template functions use Home Assistant’s Jinja2 templating to return dynamic values. They’re ideal for retrieving entity states, attributes, or generating formatted responses.

Configuration

function:
  type: template
  value_template: "{{ your_template_here }}"
value_template
string
required
Jinja2 template that returns the function result

Examples

Get Current Weather

This simple example demonstrates template syntax:
- spec:
    name: get_current_weather
    description: Get the current weather in a given location
    parameters:
      type: object
      properties:
        location:
          type: string
          description: The city and state, e.g. San Francisco, CA
        unit:
          type: string
          enum:
          - celsius
          - fahrenheit
      required:
      - location
  function:
    type: template
    value_template: The temperature in {{ location }} is 25 {{unit}}
Weather Template
This is a simplified example from the OpenAI documentation.

Get Entity Attributes

Access state and attributes of one or multiple entities.
- spec:
    name: get_attributes
    description: Get attributes of entity or multiple entities.
    parameters:
      type: object
      properties:
        entity_id:
          type: array
          description: entity_id of entity or multiple entities
          items:
            type: string
      required:
      - entity_id
  function:
    type: template
    value_template: >-
      ```csv
      entity,attributes
      {%for entity in entity_id%}
      {{entity}},{{states[entity].attributes}}
      {%endfor%}
      ```
Get Attributes
This function returns attributes in CSV format, making it easy for the AI to parse and understand multiple entities at once.

Template Features

{{ states('sensor.temperature') }}
{{ states.sensor.temperature.state }}
{{ state_attr('sensor.temperature', 'unit_of_measurement') }}
{% set on_lights = states.light | selectattr('state', 'eq', 'on') | list %}
{{ on_lights | length }} lights are on
{{ now() }}
{{ now().strftime('%Y-%m-%d %H:%M:%S') }}
{{ as_timestamp(now()) }}
{% set total = (value1 | float) + (value2 | float) %}
{% if total > 100 %}High{% else %}Normal{% endif %}

Use Cases

Entity Queries

Retrieve current states and attributes of entities

Calculations

Perform math operations on sensor values

Formatting

Format data for natural language responses

Filtering

Filter entities by state, area, or attributes

Best Practices

1

Keep templates simple

Use template functions for simple data retrieval. For complex logic, consider composite functions.
2

Handle missing values

Always use default values and safe filters:
{{ states('sensor.temperature') | float(0) }}
{{ state_attr('light.bedroom', 'brightness') | default('N/A') }}
3

Format for readability

Return human-readable text that the AI can use in responses:
The temperature is {{ states('sensor.temp') }}°C (feels like {{ state_attr('sensor.temp', 'feels_like') }}°C)

Next Steps