Skip to content

Instantly share code, notes, and snippets.

@ravila4
Last active May 3, 2023 03:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ravila4/1d5c870e43501b80b26cc7b8c9bc5e82 to your computer and use it in GitHub Desktop.
Save ravila4/1d5c870e43501b80b26cc7b8c9bc5e82 to your computer and use it in GitHub Desktop.
A simple curl wrapper around the OpenAI completions API.
#!/bin/bash
set -euo pipefail
# This script sends a request to the OpenAI completions endpoint and parses the output using jq.
# It is recommended that the API key is stored in an environment variable.
usage() {
echo "Usage: $0 [-k OPENAI_API_KEY] [-m MODEL] [-t MAX_TOKENS] PROMPT"
echo "Example: $0 -m text-davinci-002 -t 500 \"What is the capital of France?\""
}
if [[ $# -eq 0 ]]; then
usage
exit 1
fi
MODEL="text-davinci-002"
MAX_TOKENS="500"
while getopts ":m:t:k:" opt; do
case $opt in
m)
MODEL="$OPTARG"
;;
t)
MAX_TOKENS="$OPTARG"
;;
k)
OPENAI_API_KEY="$OPTARG"
;;
\?)
echo "Invalid option: -$OPTARG" >&2
usage
exit 1
;;
:)
echo "Option -$OPTARG requires an argument." >&2
usage
exit 1
;;
esac
done
shift $((OPTIND-1))
if [[ $# -eq 0 ]]; then
echo "Error: PROMPT is required." >&2
usage
exit 1
fi
PROMPT="$1"
# Use jq to escape invalid characters from the JSON text
escaped_selection=$(echo "$PROMPT" | `which jq` -Rs .)
curl -sX POST -H "Content-Type: application/json" -H "Authorization: Bearer $OPENAI_API_KEY" -d "{\"model\": \"$MODEL\", \"prompt\": $escaped_selection, \"max_tokens\": $MAX_TOKENS}" "https://api.openai.com/v1/completions" | `which jq` --raw-output '.choices[0].text'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment