Skip to content

Git Commit with AI Generated Messages

Khai Tran edited this page Nov 2, 2025 · 1 revision

Overview

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.

Benefits

  • 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

Prerequisites

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)

How It Works

Workflow

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

Architecture

The solution consists of two components:

  1. CommitMessageGenerator Agent: An AgentCrew agent configured with strict prompt rules to generate Conventional Commits
  2. Shell Function: A wrapper script that orchestrates the git diff → AI generation → commit workflow

Part 1: Configure the CommitMessageGenerator Agent

Agent System Prompt

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

Configuration Notes

  • 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

Part 2: Implement the Shell Function

Choose the implementation for your shell environment:

Option A: Bash (Linux/macOS)

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


Option B: PowerShell (Windows)

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-AICommit

To activate: Run . $PROFILE or restart your PowerShell session


Usage Examples

Basic Usage

# 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_commit

Output:

Generating commit message from staged changes...

Generated commit message:
================================================
feat: add hello world console log
================================================

Committing changes...
Successfully committed changes

Customization Options

Using Different AI Providers

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"

Modifying the Agent Prompt

To adjust commit message style:

  1. Access your AgentCrew configuration
  2. Locate the CommitMessageGenerator agent
  3. Modify the system prompt rules
  4. Examples: Add emoji support, change description style, require ticket numbers

Advanced: Adding Confirmation Prompt

To add a confirmation step before committing, modify the function:

Bash

# 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

PowerShell

# 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
}

Additional Resources


Created with AgentCrew 🤖