A Bash script that uses OpenAI's API to generate a pull request title
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
#!/usr/bin/env bash | |
# | |
# Print a title of the current pull request's commits. | |
# | |
# - For single commit pull requests, this prints the subject of the commit. | |
# | |
# - For multi-commit pull requests, this uses OpenAI's REST API to digest the | |
# commit messages of the pull request into a single sentence. | |
# | |
# Requires an OPENAI_API_KEY env var to authenticate requests - see: | |
# https://beta.openai.com/docs/api-reference/authentication | |
set -e | |
# Commit selection variables. | |
TARGET_BRANCH=master | |
# OpenAI tuning variables (can be overridden by passing as env vars). | |
TEMPERATURE=${TEMPERATURE:-1} | |
MAX_TOKENS=${MAX_TOKENS:-512} | |
MODEL=${MODEL:-"text-davinci-002"} | |
INTRO=${INTRO:-"Below are some commit messages. Write a one sentence summary of them."} | |
function main { | |
# How we generate the title depends on if there is more than one commit. | |
if [ "$(num_commits)" -eq 1 ]; then | |
single_commit_title | |
else | |
multi_commit_title | |
fi | |
} | |
function num_commits { | |
git log origin/$TARGET_BRANCH.. --oneline | wc -l | |
} | |
function single_commit_title { | |
git log origin/$TARGET_BRANCH.. --format='%s' | head -1 | |
} | |
function multi_commit_title { | |
# Build the JSON payload. | |
payload=$(jq -n \ | |
--arg model "$MODEL" \ | |
--argjson temp $TEMPERATURE \ | |
--argjson tokens $MAX_TOKENS \ | |
--arg prompt "$( | |
echo "$INTRO"; | |
git log origin/$TARGET_BRANCH.. --format='%B'; | |
)" '{model: $model, temperature: $temp, max_tokens: $tokens, prompt: $prompt}' | |
) | |
# POST payload to OpenAI API. | |
response=$(echo "$payload" | http https://api.openai.com/v1/completions Authorization:"Bearer $OPENAI_API_KEY") | |
# Keep a copy of the payload and response for debugging. | |
echo "$payload" | jq . > /tmp/openai-title.json | |
echo "$response" | jq . >> /tmp/openai-title.json | |
# Print the first line of the completion text. | |
echo "$response" | jq -r '.choices[0].text' | sed '/./,$!d' | head -1 | |
} | |
main |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment