Set global variable based on if condition and consume value in later action

I’m struggling with defining a global variable, setting its value using an if-else statement, and then referencing it in later actions.

I’m writing a script that requests ChatGPT to generate a message using the Conversation Process action and then plays it on my speakers using the TextToSpeech action. The script takes in two parameters: request_message and fallback_message.

I want to define a global variable called result, which stores ChatGPT’s response—unless the response contains the word “Sorry”, indicating an error in communication. In that case, result should be set to fallback_message instead.

The TTS action will then use the value of result variable.

Can you give me an example?

This any help?

Due to dumb variable scope limitations, you cannot do this:

- if:
    …
  then:
  - variables:
      my_variable: …
  else:
  - variables:
      my_variable: …

When leaving the if block, the variable will be lost.

You must instead write your conditions as a template within the variable definition:

- variables:
    my_variable: >-
      {% if … %}
        …
      {% else %}
        …
      {% endif %}

I use ChatGPT to generate the script I need and it actually work!
The key part, similar to @Mayhem_SWE 's suggestion, is this:

 - alias: "Check response and set message"
    variables:
      result: >-
        {% if 'Sorry' in agent_respond.text %}
          {{ fallback_message }}
        {% else %}
          {{ agent_respond.text }}
        {% endif %}

Full script if someone need

alias: ChatGPT TTS Script
description: "Sends a message to ChatGPT and plays the response unless it contains 'Sorry', in which case it plays a fallback message."
fields:
  request_message:
    description: "The message to send to ChatGPT."
    example: "Tell me a joke."
    required: true
    selector:
      text:
  fallback_message:
    description: "The message to play if ChatGPT returns an error."
    example: "I'm unable to process your request right now."
    required: true
    selector:
      text:
  target_speaker_entity:
    description: "The media player entity to play the response."
    example: "media_player.living_room_speaker"
    required: true
    selector:
      entity:
        domain: media_player

sequence:
  - alias: "Send request to ChatGPT"
    service: conversation.process
    data:
      text: "{{ request_message }}"
    response_variable: agent_respond

  - alias: "Check response and set message"
    variables:
      result: >-
        {% if 'Sorry' in agent_respond.text %}
          {{ fallback_message }}
        {% else %}
          {{ agent_respond.text }}
        {% endif %}

  - alias: "Play response via TTS"
    service: tts.speak
    target:
      entity_id: "{{ target_speaker_entity }}"
    data:
      message: "{{ result }}"