Search code examples
bashjqopenai-api

"Invalid numeric literal" using jq and openai api


I'm quite new to programming, so forgive me if my question is silly.

I'm working on a bash script to translate copied text using xclip and openai. I'm trying to pipe openai's response (not including the prompt).

Here's the relevant part of the script:


xdotool key ctrl+a
xdotool key ctrl+c
export OPENAI_API_KEY='XXXXXXXXXXXXXXXXXXXXXX'    
trans=$(openai api completions.create -m text-davinci-003 -p 'Translate '"$(xclip -o -sel c)"' into English.' | jq -r '.choices[0].text')

echo "$trans" always returns the following error: "parse error: Invalid numeric literal at line 1, column 10"

I've looked into jq a little, and it seems that the problem could be with the use of single versus double quotes, or that the json output from openai is causing an issue, but I'm not sure how to test that.


Solution

  • You could ask ChapGPT :-)

    I believe you can get a JSON responSE by specifying the "Content-Type" header as "application/json" in the API request.

    For example, if you are using the OpenAI GPT-3 API:

    
    curl https://api.openai.com/v1/engines/davinci-codex/completions \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer API_KEY" \
    -d '{"prompt": "Hello, World!", "max_tokens": 5}'