Last active
May 3, 2023 03:15
-
-
Save ravila4/1d5c870e43501b80b26cc7b8c9bc5e82 to your computer and use it in GitHub Desktop.
A simple curl wrapper around the OpenAI completions API.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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