Tickd.ai
← The Tickd Guide

Tutorials & Guides

How to Build a Local Git Hook for Auto-Generating Semantic Commit Messages Using Ollama and Python

Tired of writing sloppy commit messages? Build a completely offline, local Git hook using Python and Ollama that automatically analyses your staged changes and drafts clean, semantic conventional commits.

Updated 10/27/2026

Let’s be honest. Nobody actually likes writing commit messages. When you’ve spent three hours hunting down a race condition in your state machine, the absolute last thing you want to do is compose a beautifully formatted, semantic git commit message. So, you write "fixes" or "updates helper" and push it anyway, ignoring the quiet whimpers of your future self.

We can fix this. By combining Git hooks, Python, and a local LLM running via Ollama, we can generate crisp, accurate, semantic commit messages automatically before you even open your editor. No external APIs, no subscription fees, and no data leaving your machine. It makes your git history look like it was curated by a meticulous software architect, ticking all the right boxes for your dev workflow.

Let’s build a local pre-commit hook that analyses your staged changes and proposes a structured commit message.

Why Local LLMs for Git Hooks?

Sending your code to third-party APIs on every single commit is a bad idea. First, it costs money. Second, you might be bound by strict data-privacy agreements that forbid sending proprietary code to external models like those on /platforms/openai or /platforms/claude.

Running a local model like Llama 3 or Mistral via Ollama solves this. It's fast, free, and completely offline. Your source code stays on your local machine, where it belongs.

Which AI should I use for this?

Tickd is independent and not affiliated with any AI company.

Prerequisites

Before we write a single line of Python, ensure you have the following installed on your machine: - Ollama: Download and install it for your OS. Run ollama pull llama3:8b (or a smaller model like qwen2.5:3b if you're on a lightweight machine like a MacBook Air). - Python 3.10+: With the requests library installed (pip install requests). - Git: Installed and initialised in a target repository.

Step 1: Choosing the Right Local Model

When running models locally, you need to balance speed and comprehension. A git commit generator needs to understand code diffs, but it shouldn't take thirty seconds to run.

For most modern development setups: - Llama 3 (8B): Outstanding reasoning capabilities, but requires a decent GPU/M-series Mac with at least 16GB of RAM. - Qwen 2.5 (3B): Blazing fast, surprisingly good at multi-language parsing, and easily runs on 8GB machines. - Phi-3 (3.8B): Excellent structural adherence, making it highly reliable for outputting strict Conventional Commit syntax.

For this guide, we'll assume you are running llama3:8b, but feel free to swap the model name in the script below.

Step 2: The Core Python Script

We need a Python script that reads the staged git changes (the git diff --cached), formats them, sends them to Ollama, and writes back the suggested commit message.

Create a file called generate_commit.py in your utility directory or directly inside your home path:

`python import subprocess import sys import requests

OLLAMA_API_URL = "http://localhost:11434/api/generate" MODEL_NAME = "llama3:8b" # Or "qwen2.5:3b" for speed

def get_git_diff(): # Get only the staged changes result = subprocess.run( ["git", "diff", "--cached"], capture_output=True, text=True, check=True ) return result.stdout.strip()

def generate_commit_message(diff): if not diff: return ""

prompt = f""" You are an expert software engineer. Generate a concise, semantic commit message based on this git diff. Use the Conventional Commits specification (e.g., feat(scope): message, fix: message, chore: message, docs: message, refactor: message). Keep the subject line under 70 characters. If necessary, add a brief bulleted list of changes in the body after a blank line. Do not write any preamble, conversational text, or explanations. Only return the commit message itself.

Diff: \"\"\"{diff}\"\"\" """

payload = { "model": MODEL_NAME, "prompt": prompt, "stream": False }

try: response = requests.post(OLLAMA_API_URL, json=payload) response.raise_for_status() return response.json().get("response", "").strip() except Exception as e: print(f"Error calling local Ollama: {e}", file=sys.stderr) sys.exit(1)

if __name__ == "__main__": diff = get_git_diff() if not diff: print("No staged changes found. Use 'git add' to stage changes first.") sys.exit(1)

commit_msg = generate_commit_message(diff) print(commit_msg) `

Step 3: Refining the Prompt

LLMs can sometimes be verbose. If you find your local model is still adding conversational filler like "Here is your commit message:", you'll want to adjust your system instructions. You can use our advanced /prompts tool to fine-tune your prompts for strict output formatting.

For local models, extreme clarity is key. Tell the model what it must not do. Adding negative constraints (e.g., "Do not include markdown code block backticks") prevents Git from getting confused by weirdly formatted responses.

Step 4: Wire It Into Git Hooks

Git hooks live inside the .git/hooks/ directory of your repository. We want to use the prepare-commit-msg hook, which triggers after you type git commit but before the commit editor actually opens.

Navigate to your test repository and open .git/hooks/prepare-commit-msg (if it doesn't exist, create it):

`bash touch .git/hooks/prepare-commit-msg chmod +x .git/hooks/prepare-commit-msg `

Now, paste the following bash script into prepare-commit-msg. This script calls our Python script, saves the generated message to a temporary file, and feeds it directly into Git's commit buffer:

`bash #!/bin/sh

COMMIT_MSG_FILE=$1 COMMIT_SOURCE=$2

Only generate a message if the user didn't specify one via -m or -F if [ -z "$COMMIT_SOURCE" ]; then # Run our Python script and capture the output GENERATED_MSG=$(python3 /path/to/your/generate_commit.py)

if [ ! -z "$GENERATED_MSG" ]; then # Prepend the generated message to the commit file echo "$GENERATED_MSG" > "$COMMIT_MSG_FILE" fi fi `

(Remember to replace `/path/to/your/generate_commit.py` with the absolute path to where you saved your Python file.)

Step 5: Testing Your Local Setup

Let’s see if our pipeline actually works. Make a small change to a file in your project, stage it, and commit it:

`bash echo "print('Hello World')" > main.py git add main.py git commit `

Your terminal should pause for a couple of seconds while your graphics card spins up the local model, and then your default terminal editor will open pre-populated with something like:

`text feat: add main script with print statement

- Created main.py with basic hello world print function `

Simply save and exit the editor to complete the commit. If you run into issues with Python dependencies or local connection timeouts, make sure to look at our /platforms/openai/articles or general local setups to verify your system's network path.

Customising for Monorepos

If you're working in large monorepos with multiple workspaces, you might want to adjust the prompt dynamically based on which directories have changed. You can edit the Python script to run git diff --cached --name-only to parse the paths, and append a dynamic scope to your prompt (e.g., feat(api): or fix(web):). This keeps your version history incredibly clean, no matter how many files you’re shifting around.

gitollamapythondev-workflowlocal-llm

Keep going

Build something with the prompt generator, decode the jargon in the glossary, or compare the tools on our platform deep-dives.