> ## Documentation Index
> Fetch the complete documentation index at: https://extended-openai-conversation.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Template Functions

> Return dynamic values using Jinja2 templates

Template functions use Home Assistant's [Jinja2 templating](https://www.home-assistant.io/docs/configuration/templating/) to return dynamic values. They're ideal for retrieving entity states, attributes, or generating formatted responses.

## Configuration

```yaml theme={null}
function:
  type: template
  value_template: "{{ your_template_here }}"
```

<ParamField path="value_template" type="string" required>
  Jinja2 template that returns the function result
</ParamField>

## Examples

### Get Current Weather

This simple example demonstrates template syntax:

```yaml theme={null}
- 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}}
```

<Frame>
  <img width="300" alt="Weather Template" src="https://github.com/jekalmin/extended_openai_conversation/assets/2917984/05e31ea5-daab-4759-b57d-9f5be546bac8" />
</Frame>

<Note>
  This is a simplified example from the [OpenAI documentation](https://platform.openai.com/docs/guides/function-calling/common-use-cases).
</Note>

### Get Entity Attributes

Access state and attributes of one or multiple entities.

````yaml theme={null}
- 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%}
      ```
````

<Frame>
  <img width="300" alt="Get Attributes" src="https://github.com/jekalmin/extended_openai_conversation/assets/2917984/5994c7a0-1370-4924-bed8-d2e77ec1d11d" />
</Frame>

This function returns attributes in CSV format, making it easy for the AI to parse and understand multiple entities at once.

## Template Features

<AccordionGroup>
  <Accordion title="Access Entity States">
    ```jinja2 theme={null}
    {{ states('sensor.temperature') }}
    {{ states.sensor.temperature.state }}
    {{ state_attr('sensor.temperature', 'unit_of_measurement') }}
    ```
  </Accordion>

  <Accordion title="Filter and Select">
    ```jinja2 theme={null}
    {% set on_lights = states.light | selectattr('state', 'eq', 'on') | list %}
    {{ on_lights | length }} lights are on
    ```
  </Accordion>

  <Accordion title="Date and Time">
    ```jinja2 theme={null}
    {{ now() }}
    {{ now().strftime('%Y-%m-%d %H:%M:%S') }}
    {{ as_timestamp(now()) }}
    ```
  </Accordion>

  <Accordion title="Math and Logic">
    ```jinja2 theme={null}
    {% set total = (value1 | float) + (value2 | float) %}
    {% if total > 100 %}High{% else %}Normal{% endif %}
    ```
  </Accordion>
</AccordionGroup>

## Use Cases

<CardGroup cols={2}>
  <Card title="Entity Queries" icon="database">
    Retrieve current states and attributes of entities
  </Card>

  <Card title="Calculations" icon="calculator">
    Perform math operations on sensor values
  </Card>

  <Card title="Formatting" icon="align-left">
    Format data for natural language responses
  </Card>

  <Card title="Filtering" icon="filter">
    Filter entities by state, area, or attributes
  </Card>
</CardGroup>

## Best Practices

<Steps>
  <Step title="Keep templates simple">
    Use template functions for simple data retrieval. For complex logic, consider composite functions.
  </Step>

  <Step title="Handle missing values">
    Always use default values and safe filters:

    ```jinja2 theme={null}
    {{ states('sensor.temperature') | float(0) }}
    {{ state_attr('light.bedroom', 'brightness') | default('N/A') }}
    ```
  </Step>

  <Step title="Format for readability">
    Return human-readable text that the AI can use in responses:

    ```jinja2 theme={null}
    The temperature is {{ states('sensor.temp') }}°C (feels like {{ state_attr('sensor.temp', 'feels_like') }}°C)
    ```
  </Step>
</Steps>

## Next Steps

<CardGroup cols={3}>
  <Card title="Script Functions" icon="scroll" href="/functions/script">
    Execute service sequences
  </Card>

  <Card title="Composite Functions" icon="layer-group" href="/functions/composite">
    Combine templates with other functions
  </Card>

  <Card title="Template Documentation" icon="book" href="https://www.home-assistant.io/docs/configuration/templating/">
    Home Assistant templating guide
  </Card>
</CardGroup>
