-
Notifications
You must be signed in to change notification settings - Fork 20
Git Commit with AI Generated Messages
Automate the creation of high-quality, standardized commit messages using AgentCrew AI. This recipe demonstrates how to leverage AI to generate Conventional Commits compliant messages from your staged git changes.
- Consistency: All commit messages follow the same professional format
- Time Savings: Eliminate the mental overhead of crafting commit messages
- Best Practices: Automatically adhere to Conventional Commits specification
- Code Review: Clearer commit history improves team collaboration
Before implementing this recipe, ensure you have:
- ✅ Git installed and configured
- ✅ AgentCrew installed (Installation Guide)
- ✅ Working in a git repository with staged changes
- ✅ API access to an LLM provider (e.g., OpenAI)
1. Stage your changes → git add <files>
2. Run the AI commit function → ai_commit
3. AI analyzes staged diff → Generates commit message
4. Auto-commit with message → Changes committed
The solution consists of two components:
- CommitMessageGenerator Agent: An AgentCrew agent configured with strict prompt rules to generate Conventional Commits
- Shell Function: A wrapper script that orchestrates the git diff → AI generation → commit workflow
Create an agent in AgentCrew with the following system prompt configuration. This prompt ensures the agent generates precise, specification-compliant commit messages.
Generate concise, precise commit messages following the Conventional Commits specification. Output should be the commit message itself - no explanations, no preamble, no additional commentary.
## Commit Message Format
<type>[optional scope]: <description>
[optional body]
[optional footer(s)]
## Commit Types
- **feat**: A new feature for the user
- **fix**: A bug fix
- **docs**: Documentation only changes
- **style**: Code style changes (formatting, missing semi-colons, etc.)
- **refactor**: Code change that neither fixes a bug nor adds a feature
- **perf**: Performance improvement
- **test**: Adding or updating tests
- **build**: Changes to build system or dependencies
- **ci**: CI/CD configuration changes
- **chore**: Other changes that don't modify src or test files
- **revert**: Reverts a previous commit
## Rules
1. **Type**: Must be one of the types listed above
2. **Scope**: (Optional) Represents section of codebase (e.g., api, auth, ui, parser)
3. **Description**:
- Use imperative mood ("add feature" not "added feature")
- Start with lowercase letter
- No period at the end
- Maximum 72 characters
- Must comprehensively describe all changes in the diff
4. **Output**: Return ONLY the commit message text, nothing else-
Agent Name:
CommitMessageGenerator(referenced in the shell function) -
Model Recommendation: Even lightweight models work well (e.g.,
gpt-4o-mini,claude-3-haiku). Commit message generation is a focused task with clear rules, not requiring advanced reasoning
Choose the implementation for your shell environment:
Add this function to your ~/.bashrc or ~/.zshrc:
ai_commit() {
# ============================================
# Dependency Validation
# ============================================
if ! command -v agentcrew >/dev/null 2>&1; then
echo "Error: agentcrew command not found" >&2
echo " Please install agentcrew first" >&2
return 1
fi
if ! command -v git >/dev/null 2>&1; then
echo "Error: git command not found" >&2
return 1
fi
# ============================================
# Git Repository Check
# ============================================
if ! git rev-parse --git-dir >/dev/null 2>&1; then
echo "Error: Not in a git repository" >&2
return 1
fi
# ============================================
# Staged Changes Validation
# ============================================
local diff_content
diff_content=$(git diff --staged)
if [[ -z "$diff_content" ]]; then
echo "Error: No staged changes found" >&2
echo " Use 'git add' to stage files first" >&2
return 1
fi
# ============================================
# AI Commit Message Generation
# ============================================
echo "Generating commit message from staged changes..."
echo ""
local generated_message
generated_message=$(agentcrew job \
--agent="CommitMessageGenerator" \
--provider=openai \
--model-id="gpt-4o-mini" \
--output-schema='{"type": "string"}' \
"$diff_content" 2>&1)
local agentcrew_exit_code=$?
# Handle agentcrew execution errors
if [[ $agentcrew_exit_code -ne 0 ]]; then
echo "Error: Failed to generate commit message" >&2
echo " Exit code: $agentcrew_exit_code" >&2
echo " Output: $generated_message" >&2
return 1
fi
# Validate generated message is not empty
if [[ -z "$generated_message" ]]; then
echo "Error: Generated commit message is empty" >&2
return 1
fi
# ============================================
# Message Cleanup & Display
# ============================================
# Strip surrounding quotes and whitespace from JSON output
generated_message=$(echo "$generated_message" | sed 's/^["'\''[:space:]]*//;s/["'\''[:space:]]*$//')
echo "Generated commit message:"
echo "================================================"
echo "$generated_message"
echo "================================================"
echo ""
# ============================================
# Git Commit Execution
# ============================================
echo "Committing changes..."
if git commit -m "$generated_message"; then
echo "Successfully committed changes"
return 0
else
echo "Error: git commit failed" >&2
return 1
fi
}To activate: Run source ~/.bashrc or restart your terminal
Add this function to your PowerShell profile ($PROFILE):
function Invoke-AICommit {
<#
.SYNOPSIS
Generates and commits staged changes using AI-generated commit messages.
.DESCRIPTION
Uses AgentCrew to analyze staged git changes and generate a Conventional Commits
compliant message, then commits the changes automatically.
.EXAMPLE
Invoke-AICommit
# Generates a commit message for staged changes and commits them
ai_commit # Using the alias
.NOTES
Requirements: agentcrew, git
Author: AgentCrew Community
#>
[CmdletBinding()]
param()
# ============================================
# Dependency Validation
# ============================================
if (-not (Get-Command agentcrew -ErrorAction SilentlyContinue)) {
Write-Error "Error: agentcrew command not found`n Please install agentcrew first"
return
}
if (-not (Get-Command git -ErrorAction SilentlyContinue)) {
Write-Error "Error: git command not found"
return
}
# ============================================
# Git Repository Check
# ============================================
$null = git rev-parse --git-dir 2>&1
if ($LASTEXITCODE -ne 0) {
Write-Error "Error: Not in a git repository"
return
}
# ============================================
# Staged Changes Validation
# ============================================
$diffContent = git diff --staged
if ([string]::IsNullOrWhiteSpace($diffContent)) {
Write-Error "Error: No staged changes found`n Use 'git add' to stage files first"
return
}
# ============================================
# AI Commit Message Generation
# ============================================
Write-Host "Generating commit message from staged changes..." -ForegroundColor Cyan
Write-Host ""
try {
$generatedMessage = agentcrew job `
--agent="CommitMessageGenerator" `
--provider='openai' `
--model-id="gpt-4o-mini" `
--output-schema='{\"type\": \"string\"}' `
$diffContent 2>&1
$agentcrewExitCode = $LASTEXITCODE
}
catch {
Write-Error "Error: Exception during agentcrew execution`n $_"
return
}
# Handle agentcrew execution errors
if ($agentcrewExitCode -ne 0) {
Write-Error "Error: Failed to generate commit message`n Exit code: $agentcrewExitCode`n Output: $generatedMessage"
return
}
# Validate generated message is not empty
if ([string]::IsNullOrWhiteSpace($generatedMessage)) {
Write-Error "Error: Generated commit message is empty"
return
}
# ============================================
# Message Cleanup & Display
# ============================================
# Strip surrounding quotes and whitespace from JSON output
$generatedMessage = $generatedMessage.Trim().Trim('"', "'")
Write-Host "Generated commit message:" -ForegroundColor Green
Write-Host "==================================================" -ForegroundColor Gray
Write-Host $generatedMessage -ForegroundColor White
Write-Host "==================================================" -ForegroundColor Gray
Write-Host ""
# ============================================
# Git Commit Execution
# ============================================
Write-Host "Committing changes..." -ForegroundColor Cyan
git commit -m $generatedMessage
if ($LASTEXITCODE -eq 0) {
Write-Host "Successfully committed changes" -ForegroundColor Green
}
else {
Write-Error "Error: git commit failed"
}
}
# Create convenient alias
Set-Alias -Name ai_commit -Value Invoke-AICommitTo activate: Run . $PROFILE or restart your PowerShell session
# 1. Make changes to your code
echo "console.log('Hello');" >> app.js
# 2. Stage the changes
git add app.js
# 3. Generate AI commit message and commit
ai_commitOutput:
Generating commit message from staged changes...
Generated commit message:
================================================
feat: add hello world console log
================================================
Committing changes...
Successfully committed changes
Replace the --provider and --model-id flags with your preferred provider:
Anthropic (Claude):
--provider=claude \
--model-id="claude-3-5-haiku-latest"GitHub Copilot:
--provider=github_copilot \
--model-id="gpt-4.1-mini"Google (Gemini):
--provider=google \
--model-id="gemini-2.5-flash"To adjust commit message style:
- Access your AgentCrew configuration
- Locate the
CommitMessageGeneratoragent - Modify the system prompt rules
- Examples: Add emoji support, change description style, require ticket numbers
To add a confirmation step before committing, modify the function:
# Add before the git commit command:
read -p "Proceed with this commit? (y/n) " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
echo "Commit cancelled"
return 1
fi# Add before the git commit command:
$confirmation = Read-Host "Proceed with this commit? (y/n)"
if ($confirmation -ne 'y') {
Write-Host "Commit cancelled" -ForegroundColor Yellow
return
}Created with AgentCrew 🤖