Skip to content

Instantly share code, notes, and snippets.

@malonehedges
Created November 7, 2022 07:14
Show Gist options
  • Save malonehedges/4b5f955a0f8efe7ddb16b06644a65fd7 to your computer and use it in GitHub Desktop.
Save malonehedges/4b5f955a0f8efe7ddb16b06644a65fd7 to your computer and use it in GitHub Desktop.
#!/bin/bash
# This script
# - takes in a file name from the command line
# - reads the file contents
# - requests from the OpenAI GPT-3 API
# - gets the text of the first suggestion using jq (jq '.choices[0].text' -r)
# - appends the first suggestion to the file
# Usage: ./gpt.sh <file>
# Example: ./gpt.sh test.txt
# Example CURL request
# curl https://api.openai.com/v1/completions \
# -H "Content-Type: application/json" \
# -H "Authorization: Bearer $OPENAI_API_KEY" \
# -d '{
# "model": "text-davinci-002",
# "prompt": "<contents of the file would be put here>",
# "temperature": 0.7,
# "max_tokens": 256,
# "top_p": 1,
# "frequency_penalty": 0,
# "presence_penalty": 0
# }'
# Get the file name from the command line
FILE=$1
# Read the file contents
FILE_CONTENTS=$(cat $FILE)
# Escape the file contents for JSON using jq
FILE_CONTENTS_ESCAPED=$(echo $FILE_CONTENTS | jq -sR)
# Request from the OpenAI GPT-3 API
curl https://api.openai.com/v1/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-d '{
"model": "text-davinci-002",
"prompt": '"$FILE_CONTENTS_ESCAPED"',
"temperature": 0.7,
"max_tokens": 256,
"top_p": 1,
"frequency_penalty": 0,
"presence_penalty": 0
}' | jq '.choices[0].text' -r >> $FILE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment