Skip to content

Instantly share code, notes, and snippets.

@foysavas
Created June 6, 2023 20:27
Show Gist options
  • Save foysavas/35e7233f13e0b91fb819740db79140df to your computer and use it in GitHub Desktop.
Save foysavas/35e7233f13e0b91fb819740db79140df to your computer and use it in GitHub Desktop.
ask-chatgpt from the command line
#!/bin/bash
## Based on a script from @chrishwiggins
## https://github.com/chrishwiggins/mise/blob/9bc3e8c6ae309db3fb3e9f0e21d38925f06af82e/bash/oai-no-key.sh
if [ $# -eq 0 ]; then
echo "Usage: ask-chatgpt \"your questions\"" >&2
exit 1
fi
prompt=$1
# Escape the input using jq to handle special characters
escaped_input=$(printf '%s' "$prompt" | jq -Rs '.')
# Create a temporary file to store the JSON data
json_file="/tmp/oai_json_$$.json"
# Write the JSON data to the temporary file
cat > "${json_file}" <<EOF
{
"model": "gpt-3.5-turbo",
"messages": [
{
"role": "user",
"content": ${escaped_input}
}
]
}
EOF
# "options": {
# "temperature": 0.8,
# "max_tokens": 100
# }
# Save the API request JSON data for debugging purposes
# cp "${json_file}" "/tmp/oai_`date +%s`.in"
# Execute the curl request with the JSON data from the temporary file
# The curl output is stored in a temporary file
curl_output_file="/tmp/curl_output_$$.txt"
api_response_file="/tmp/api_response_$$.json"
curl --verbose --location --request POST 'https://api.openai.com/v1/chat/completions' \
--header "Authorization: Bearer ${OPENAI_API_KEY}" \
--header 'Content-Type: application/json' \
--data "@${json_file}" 2> >(grep -v Bearer > "${curl_output_file}") > "${api_response_file}"
# Save the curl verbose output (without the API key) for debugging purposes
# cat "${curl_output_file}"
# cp "${curl_output_file}" "/tmp/curl_output_`date +%s`.txt"
# Save the complete API response for debugging purposes
# cat "${api_response_file}"
# cp "${api_response_file}" "/tmp/api_response_`date +%s`.json"
# Process the output with jq to extract the content
output=$(cat "${api_response_file}" | jq '.choices[].message.content')
if [ $? -ne 0 ]
then
cat "${curl_output_file}" >&2
cat "${api_response_file}" >&2
fi
# Remove escape sequences, quotes, and other formatting
echo "${output}" | sed -e 's/\\n/\n/g' -e 's/\\"/"/g' -e 's/^"//' -e 's/"$//' > /tmp/oai_$$.out
fold -s -b -w 65 < /tmp/oai_$$.out
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment