How to use AI for git commit messages
Quick answer
Use an AI language model like
gpt-4o to generate descriptive git commit messages by sending the diff or staged changes as input to the model via the chat.completions.create API. This automates writing clear commit messages that summarize code changes effectively.PREREQUISITES
Python 3.8+OpenAI API key (free tier works)pip install openai>=1.0
Setup
Install the OpenAI Python SDK and set your API key as an environment variable for secure access.
pip install openai>=1.0 Step by step
This example shows how to generate a git commit message by sending the git diff output to the gpt-4o model using the OpenAI Python SDK.
import os
from openai import OpenAI
import subprocess
# Initialize OpenAI client
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
# Get the staged git diff
result = subprocess.run(["git", "diff", "--staged"], capture_output=True, text=True)
git_diff = result.stdout
# Prepare prompt for commit message generation
prompt = f"Generate a concise and clear git commit message for the following changes:\n\n{git_diff}"
# Call the OpenAI chat completion endpoint
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": prompt}]
)
commit_message = response.choices[0].message.content.strip()
print("Generated commit message:")
print(commit_message) output
Generated commit message: Fix bug in user authentication flow by correcting token validation logic
Common variations
- Use
git diffwithout--stagedto generate messages for unstaged changes. - Switch to asynchronous calls with
asynciofor integration in larger apps. - Try other models like
claude-3-5-sonnet-20241022for potentially better commit message quality. - Incorporate commit message templates or prefixes by modifying the prompt.
Troubleshooting
- If the commit message is too generic, provide more context in the prompt or include file names.
- If API calls fail, verify your
OPENAI_API_KEYenvironment variable is set correctly. - For very large diffs, truncate input or summarize changes before sending to the model to avoid token limits.
Key Takeaways
- Use the git diff output as input to an AI model to generate descriptive commit messages automatically.
- The OpenAI
gpt-4omodel can produce concise, human-readable commit summaries from code changes. - Customize prompts and model choice to improve message relevance and style for your project.
- Always secure your API key using environment variables and handle large diffs carefully to avoid token limits.