Command line sensor runs into character limit

I have set up a command line sensor following this guide: Unlocking the power of ChatGPT in Home Assistant: A step-by-step guide – Home Assistant Guide

This is the configuration:

sensor:
  - platform: command_line
    name: GPT Response
    command: "curl -XPOST https://api.openai.com/v1/chat/completions -H 'Content-Type: application/json' -H 'Authorization: Bearer YOUR_API_SECRET_KEY' -d '{\"model\": \"gpt-3.5-turbo\", \"messages\": [{\"role\": \"user\", \"content\": \"Act as a personal assistant for the male head of a household. You are witty and talk conversationally. The current time is {{ now() }}, and the current day is {{ now().weekday() }}. The weather is {{ states('weather.tomorrow_io_acehouse_control_nowcast') }}. Tottenham Hotspur play their next game {{ state_attr('sensor.thfc_tracker', 'kickoff_in') }} against {{ state_attr('sensor.thfc_tracker', 'opponent_name') }}. Greet me in a friendly but respectful way, commenting on the weather, football, and sometimes making a joke, in one or two sentences.\"}], \"top_p\": 1, \"temperature\": 0.7, \"max_tokens\": 320, \"presence_penalty\": 1}'"
    value_template: "{{ value_json.choices[0].message.content }}"
    scan_interval: 900

However I sometimes find it running into the character limit where the response exceeds 255 characters and thus cannot be stored in the sensor’s value_template. I read somewhere that attributes do not have this limit but I can’t figure out how to write that data into an attribute. Can you guide me here?

This is an example response from ChatGPT:

{
 'id': 'chatcmpl-6p9XYPYSTTRi0xEviKjjilqrWU2Ve',
 'object': 'chat.completion',
 'created': 1677649420,
 'model': 'gpt-3.5-turbo',
 'usage': {'prompt_tokens': 56, 'completion_tokens': 31, 'total_tokens': 87},
 'choices': [
   {
    'message': {
      'role': 'assistant',
      'content': 'The 2020 World Series was played in Arlington, Texas at the Globe Life Field, which was the new home stadium for the Texas Rangers.'},
    'finish_reason': 'stop',
    'index': 0
   }
  ]
}

Since you cannot set the JSON attributes path:

Either:

A) pipe the output in your command-line sensor to JQ and extract only what you want

or

B) Put the whole response into an attribute and use a template sensor to extract what you need
You could likely just remove:

"{{ value_json.choices[0].message.content }}"

Replace it with like “OK” as the state.

Then add:

json_attributes: 
  - choices

Meaning like this:

    value_template: "OK"
    scan_interval: 900
    json_attributes:
       - choices

I tend to use option (a) as it gives me complete control to rewrite the JSON to what I want. But if you do not know JQ, then option (b) can probably get you what you want in an attribute and you can parse downward from there in Lovelace or whatever you wish.

As an example, your JSON with proper quoting and JQ could be like this:

Then the JSON attributes would be “created” and “response”.

Side note: The JSON you post is totally invalid. It uses single quotes. I have a hard time believing that is what you are getting back. Strings in JSON are specified using double quotes, i.e., " . If the strings are enclosed using single quotes, then the JSON is invalid unless processed by something that allows ALLOW_SINGLE_QUOTES

Unfortunately that doesn’t work for the command line sensor. I get this error:

Invalid config for [sensor.command_line]: [json_attributes_path] is an invalid option for [sensor.command_line].

You are too fast, see update above as I forgot json_attributes_path does not work for command line

1 Like

Ok, that solution with JQ sounds really neat. How would I append that command to my prompt? I have trouble forming it with the right quotes as the command is currently wrapped in double quotes.

You use \" to escape the quote. Use this example template for inspiration that gets Vizio Apps from the Vizio website for modern TVs :

- platform: command_line
  scan_interval: 36000
  unique_id: sensor.vizio_apps
  name: Vizio Apps
  command: "curl -s 'http://scfs.vizio.com/appservice/vizio_apps_prod.json' | jq '{\"apps\": [ .[] | {id: .\"id\", name: .\"name\", icon: .\"mobileAppInfo\".\"app_icon_image_url\", sort: .\"mobileAppInfo\".\"featured_sort\" } ]}' "
  value_template: "OK"
  json_attributes:
      - apps
1 Like

About your concern with the format: This is what the documentation says: OpenAI API

It’s not a concern of mine. In fact if you want to laugh … scroll up a bit on that page and look at what they submit TO their application … it uses double quotes. And they return data in single quotes.

see JSON

Specifically the text … A value can be a string in double quotes, or a number , or true or false or null, or an object or an array . These structures can be nested.

It does NOT say a value can be a string in ANY quotes or SINGLE quotes or anything else other than DOUBLE quotes. It is invalid JSON (I would not expect anything less from ChatGPT since it normally gives invalid answers).

This exact discussion is discussed here on another recent post in which another person (like me) says whomever is creating the JSON response does not understand JSON.

Then again, maybe you can just ask ChatGPT why it believes it’s JSON response is correct???

Thanks a lot for your help here. Learned something on the way :slight_smile:

And yeah, I do not use ChatGPT for coding advice but it is a pretty good copywriter :smiley: