How to save (extended Open Ai) responses to json list?

With file integration I am saving ai responses to txt file. Storing voice assistant (OpenAI) history. My question is how to call last message only (for replaying last message)?
Or even better how to store responses into json list instead?

part of my script wich writes to txt looks like this:

action: notify.send_message
metadata: {}
data:
  title: Abu gryžtam
  message: "{{agent.response.speech.plain.speech}}"
target:
  entity_id: notify.file_2
enabled: true

saved messages

The file integration also includes a sensor platform that can be used to read the file you write to. Something along the lines of:

sensor:
- platform: file
  name: Last Message
  file_path: /share/whatever

This only gives you the last line of the file, and will be limited to 256 characters since it’s in the entity state. So you would want to ensure that it’s all on one line:

message: "{{ agent.response.speech.plain.speech  | replace('\n', ' ') }}"

It supports JSON too (although I’ve never used it), so if you write JSON it should work, but still not overcome the character limit because it doesn’t look like it loads attributes.

To write JSON, just ensure your notify.send_message is in the appropriate format, something like:

message: '{ "speech": "{{agent.response.speech.plain.speech}}" }'

It seems the integration doesn’t require the whole file to be valid JSON, just each line.

However, I expect the character limit is still a deal-breaker. If you’re using Node Red you could move the code over there using equivalent functions to avoid the limit.

Thanks Michael for response :grinning:

# do not work
sensor:
  - platform: file

I’m afraid file integration sensors can’t be created in yaml. They won’t show up in entities.

Lesson learned :
File integration output works fine but up to 255 characters. File integration both sensors must be created via UI only, no yaml.
File integration “sensor.file” will read last txt line if it is less than 255 characters only (has no attributes), otherwise will show (unknown).
File integration "notify.file " via “notify.send_message” will store any size message.
Make sure that the file you want to use is added to the allowlist_external_dirs.

I foolishly believed that when we can have txt file created with file integration that we can read from it and store data in template sensor’s attributes for example. That is not the case.

What i’m trying to achieve is, to read last txt line wich is more than 255 characters.
Def need to take your advice and dig into Node Red.