Last active
April 13, 2023 21:07
-
-
Save drikusroor/ecf7d98cc6e67e8d9408828be87af3ca to your computer and use it in GitHub Desktop.
Simple GPT CLI
This file contains hidden or 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 | |
function print_help() { | |
GREEN="\033[1;32m" | |
BLUE="\033[1;34m" | |
RESET="\033[0m" | |
echo -e "${GREEN}Usage:${RESET}" | |
echo -e " ${BLUE}gpt [options] [question]${RESET}" | |
echo "" | |
echo -e "${GREEN}Options:${RESET}" | |
echo -e " ${BLUE}-h, --help${RESET} Show this help message and exit" | |
echo -e " ${BLUE}--t=NUM${RESET} Set the maximum number of tokens in the response (default: 50)" | |
echo "" | |
echo -e "${GREEN}Examples:${RESET}" | |
echo -e " ${BLUE}gpt --t=200 Tell me a story about a programmer who became a potato${RESET}" | |
echo -e " ${BLUE}gpt --t=100 \"How can I make my computer run faster with a rubber chicken?\"${RESET}" | |
echo -e " ${BLUE}gpt What would a conversation between a cat and a toaster sound like --t=20${RESET}" | |
} | |
if [[ -z "$OPENAI_API_KEY" ]]; then | |
echo "Please set the OPENAI_API_KEY environment variable." | |
exit 1 | |
fi | |
# Set default max_tokens | |
max_tokens=50 | |
# Parse command-line arguments | |
for i in "$@" | |
do | |
case $i in | |
-h|--help) | |
print_help | |
exit 0 | |
;; | |
--t=*) | |
max_tokens="${i#*=}" | |
shift | |
;; | |
*) | |
if [[ -z "$QUESTION" ]]; then | |
QUESTION="$i" | |
else | |
QUESTION="$QUESTION $i" | |
fi | |
shift | |
;; | |
esac | |
done | |
# Prompt for question and max_tokens if not provided | |
if [[ -z "$QUESTION" ]]; then | |
echo "Please enter your question:" | |
read -r QUESTION | |
fi | |
if [[ -z "$max_tokens" ]]; then | |
echo "Please enter the max tokens (default: 50):" | |
read -r max_tokens_input | |
if [[ ! -z "$max_tokens_input" ]]; then | |
max_tokens="$max_tokens_input" | |
fi | |
fi | |
response=$(curl -s -X POST "https://api.openai.com/v1/engines/text-davinci-002/completions" \ | |
-H "Content-Type: application/json" \ | |
-H "Authorization: Bearer $OPENAI_API_KEY" \ | |
-d "{\"prompt\": \"${QUESTION}\", \"max_tokens\": ${max_tokens}, \"n\": 1, \"stop\": null, \"temperature\": 0.7}") | |
error_message=$(echo "$response" | jq -r '.error.message' 2>/dev/null) | |
if [[ "$error_message" != "null" ]] && [[ ! -z "$error_message" ]]; then | |
echo "Error: $error_message" | |
else | |
answer=$(echo "$response" | jq -r '.choices[0].text' | sed 's/^[[:space:]]*//') | |
echo "GPT-3 answers: $answer" | |
fi | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See also: https://www.ainab.site/posts/simple-gpt-cli/ for instructions on how to use