Generate Semantic Commits Instantly with Python

KeyGroqFreeAPI · Updated 2026-11-24 · 12 Min read

Laptop with code editor and terminal showing git diff
A typical setup for running the commit message generator

Writing meaningful commit messages is often the most tedious part of version control. Developers frequently default to vague phrases like "fix" or "update," which obscures the actual intent of the code change. This tutorial shows how to build a Python CLI tool that reads file diffs and generates precise, conventional commit messages using an LLM.

The tool works by extracting the diff of uncommitted changes, formatting them into a structured prompt, and sending the request to an API endpoint. The result is a ready-to-use commit message that follows semantic conventions, saving time and improving repository history clarity without requiring manual typing.

We will use a keyless API endpoint that requires no account or API key, making it easy to integrate into any workflow. The solution is lightweight, runs locally, and can be extended with reasoning capabilities for complex changes. This approach ensures that every commit tells a clear story about what was changed and why.

Frequently asked questions

What is a conventional commit message?

A conventional commit message follows a specific format: type(scope): description. This structure helps automate changelogs and makes git history readable. The tool generates messages that adhere to this standard, ensuring consistency across projects without manual formatting effort.

How does the Python CLI tool work?

The tool uses the subprocess module to run git diff and captures the output. It then formats the diff into a prompt string, sends it to an LLM API, and parses the response. The resulting message is printed to the console or directly committed, depending on the configuration.

Which model is best for commit messages?

For commit messages, a model around 35B parameters provides a good balance of quality and speed. The free-ai model is sufficient for this task, as it understands context well enough to generate accurate descriptions without requiring massive reasoning capabilities.

How does this differ from standard git hooks?

Standard git hooks run local scripts or programs. This tool integrates an LLM into the hook process, allowing for semantic understanding of changes. While hooks can run simple checks, an LLM can generate natural language descriptions that reflect the intent of the code changes.

What is the latency like for this tool?

Latency depends on the API response time. With a keyless endpoint, you can expect a few seconds of delay. Streaming the response can provide immediate feedback, but for commit messages, a single response is usually sufficient and fast enough for interactive use.

Which is better: local LLM or API?

An API offers consistent quality without hardware constraints. A local LLM requires significant RAM and CPU/GPU resources. For most developers, the API approach is more accessible and provides better results than a small local model, especially for complex diffs.

How do I handle large diffs?

Large diffs can exceed token limits. The tool can truncate the diff or summarize it before sending. It is best to commit changes in smaller logical units to ensure the LLM can accurately describe the context. This also improves the quality of the generated message.

Can I customize the commit format?

Yes, the prompt template can be modified to include specific scopes or types. You can define a custom system prompt that enforces your project's conventions. The tool is flexible and can be adapted to any commit message style required by your team.

Step by step

  1. Install Dependencies — Install the requests library and set up your Python environment. Ensure you have git installed and accessible from your terminal. This prepares your system for running the tool.
  2. Retrieve Git Diff — Run the git diff command to get the uncommitted changes. Capture the output and pass it to the prompt constructor. This provides the raw data for the LLM.
  3. Generate Message — Send the diff to the API endpoint. Parse the response to extract the commit message. Handle any errors or rate limits gracefully to ensure reliability.
  4. Commit Changes — Display the generated message or commit it directly. Use the git commit command with the -m flag. You can also integrate this into a git hook for automation.

Setting Up the Environment

Before building the tool, you need a Python environment with the requests library. This library simplifies HTTP calls to the API. You also need git installed, as the tool relies on git commands to retrieve the current state of the repository. Ensure you have a stable internet connection, as the tool depends on an external API for message generation.

The API endpoint used in this tutorial is free and keyless. This means you do not need to sign up for an account or manage API keys. The domain contains the brand Groq but the site is not affiliated with Groq: the free-ai model is an independent open-weight model fine-tuned for high compliance. This setup reduces friction and allows you to start coding immediately.

Installing Dependencies

Install the requests library using pip. This library handles the HTTP requests to the API. You may also want to install colorama for colored output in the terminal, making the tool more user-friendly. These dependencies are lightweight and do not add significant overhead to your project.

Configuring the API Endpoint

The base URL for the API is https://api.keygroqfreeapi.com/v1. This endpoint supports standard OpenAI-compatible formats. You do not need to specify an API key in the header. The model name is free-ai. This configuration is straightforward and works with most Python HTTP clients without additional authentication steps.

import requests
import subprocess
import json

API_URL = "https://api.keygroqfreeapi.com/v1/chat/completions"
MODEL = "free-ai"

# Get uncommitted changes
def get_diff():
    try:
        diff = subprocess.run(['git', 'diff'], capture_output=True, text=True)
        return diff.stdout
    except Exception as e:
        return f"Error getting diff: {e}"

Extracting Git Diffs

The first step is to retrieve the uncommitted changes in your repository. This is done by running the git diff command and capturing its output. The output includes the changes in all tracked files, formatted in a standard unified diff format. This text is the raw material that the LLM will analyze to generate the commit message.

You can filter the diff to include only specific files or directories if needed. This is useful for large projects where you only want to commit a subset of changes. The tool should handle cases where there are no changes, returning a simple message or prompting the user to stage files first. This ensures the tool is robust and handles edge cases gracefully.

Parsing the Diff Output

The diff output is plain text. It includes headers like diff --git a/file.py b/file.py and hunks with @@ lines. The tool does not need to parse this deeply; it can pass the raw text to the LLM. The LLM is trained to understand diff formats and can extract the relevant changes from the text efficiently.

Handling Large Files

If a file is very large, the diff might be extensive. The tool can truncate the diff to the first few thousand tokens. This prevents exceeding the API's token limit and ensures faster responses. Truncation should be done carefully to preserve the context of the changes, focusing on the beginning and end of the diff.

# Get staged changes instead
# def get_staged_diff():
#     diff = subprocess.run(['git', 'diff', '--cached'], capture_output=True, text=True)
#     return diff.stdout
Python script with requests library
The core library used for API communication

Constructing the Prompt

Once you have the diff, you need to construct a prompt for the LLM. The prompt should instruct the model to generate a conventional commit message. It should specify the format: type(scope): description. The prompt should also include the diff text and any additional context, such as the branch name or recent commits, if available.

A well-crafted prompt ensures that the LLM generates a message that is both accurate and follows the desired convention. You can include examples in the prompt to guide the model. For instance, providing a few examples of good commit messages helps the LLM understand the expected style and tone. This reduces the likelihood of generating vague or incorrect messages.

Defining the System Prompt

The system prompt sets the behavior of the model. It should instruct the model to be concise and accurate. It should also specify that the output should be a single line commit message. This ensures that the tool can easily parse the response and use it directly in the git commit command.

Adding Contextual Information

You can add the current branch name and a list of recent commits to the prompt. This helps the LLM understand the context of the changes. For example, if the recent commits are all about feature X, the LLM can infer that the current change is likely related to feature X. This improves the relevance of the generated message.

def construct_prompt(diff):
    system_prompt = "Generate a conventional commit message for the following diff. Format: type(scope): description."
    user_prompt = f"Diff:\n{diff}\n\nGenerate the commit message:"
    messages = [
        {"role": "system", "content": system_prompt},
        {"role": "user", "content": user_prompt}
    ]
    return messages

Sending Requests to the API

With the prompt ready, you can send it to the API. The request should be a POST to the /v1/chat/completions endpoint. The body of the request should include the model name, the messages array, and the maximum tokens. Setting a reasonable max_tokens value prevents excessive output and ensures fast responses.

The API returns a JSON response containing the generated commit message. You need to parse this response and extract the message text. It is important to handle errors, such as rate limits or server errors, by retrying the request or notifying the user. This ensures that the tool is reliable and provides a good user experience even under varying network conditions.

Implementing the HTTP Request

Use the requests library to send the POST request. Set the headers to include the content type. The body should be a JSON object with the model and messages. The response will contain the generated text in the choices array. Extract this text and return it to the caller.

Handling API Responses

Check the status code of the response. If it is 200, parse the JSON and extract the message. If it is 429, handle the rate limit by waiting for the specified time. If it is 503, retry after a short delay. This error handling ensures that the tool is robust and can recover from temporary issues.

def generate_commit_message(messages):
    headers = {"Content-Type": "application/json"}
    payload = {
        "model": MODEL,
        "messages": messages,
        "max_tokens": 100
    }
    response = requests.post(API_URL, headers=headers, json=payload)
    if response.status_code == 200:
        data = response.json()
        return data['choices'][0]['message']['content']
    else:
        return f"API Error: {response.status_code}"
Flow diagram of the commit generation process
The logical flow of data in the tool

Formatting and Committing

Once you have the generated commit message, you can display it to the user or commit it directly. Displaying it allows the user to review and edit the message before committing. This is a good practice, as the LLM might not always generate the perfect message. The user can make minor adjustments to ensure the message accurately reflects the changes.

Committing directly is faster but less flexible. You can use the subprocess module to run git commit with the generated message. This automates the workflow, allowing you to generate and commit changes in one step. This is useful for repetitive tasks or when you trust the LLM's output. You can also add a flag to toggle between display and auto-commit modes.

Displaying the Message

Print the generated message to the console. Use colorama to highlight the message, making it easy to spot. You can also provide a copy-to-clipboard function for convenience. This allows the user to paste the message into their IDE or git client if they prefer to commit manually.

Executing the Git Commit

Run the git commit command with the -m flag followed by the message. Ensure that the message is properly escaped to avoid syntax errors. You can also add a --no-verify flag to skip hooks if needed, but this should be used with caution. This step completes the workflow, saving the changes to the repository.

def commit_message(message):
    subprocess.run(['git', 'commit', '-m', message])
    print(f"Committed: {message}")

# Usage
# diff = get_diff()
# messages = construct_prompt(diff)
# msg = generate_commit_message(messages)
# commit_message(msg)

Adding Reasoning Capabilities

For complex changes, you might want the LLM to reason before generating the message. This can improve the accuracy of the commit message, especially when the diff is large or ambiguous. By enabling the reasoning parameter, the model can think through the changes and provide a more thoughtful response. This is useful for projects with strict commit message standards.

Enabling reasoning increases the token usage and latency. The model will generate a reasoning chain before the final message. This can be helpful for debugging or understanding the model's thought process. You can choose to display the reasoning to the user or use it internally to refine the final message. This adds depth to the tool's capabilities.

Enabling Reasoning Mode

Set the reasoning parameter to true in the API request. This tells the model to generate a reasoning chain. The response will include a reasoning field with the thought process. You can parse this field and include it in the output or use it to validate the generated message.

Balancing Speed and Accuracy

Reasoning mode is slower but more accurate. For simple changes, you can disable it to save time. For complex changes, enable it to ensure quality. The tool can automatically decide based on the diff size. If the diff exceeds a certain token limit, it can switch to reasoning mode automatically.

def generate_with_reasoning(messages):
    payload = {
        "model": MODEL,
        "messages": messages,
        "max_tokens": 2000,
        "reasoning": True
    }
    response = requests.post(API_URL, json=payload)
    data = response.json()
    return data['choices'][0]['message']['content']
Terminal with colored commit message
Example output of the tool with colored formatting

Integrating with Git Hooks

To make the tool seamless, you can integrate it with git hooks. The pre-commit hook runs before each commit, allowing you to generate and apply the commit message automatically. This eliminates the need for manual intervention and ensures that every commit has a meaningful message. It also encourages consistent commit practices across the team.

You can write a bash script that calls the Python tool. The script should capture the diff, call the Python script, and pass the generated message to git commit. This integration is powerful and can be customized to fit your workflow. You can also add options to skip the hook or override the generated message if needed.

Writing the Pre-commit Hook

Create a .git/hooks/pre-commit file. Make it executable. The script should run the Python tool and capture the output. If the tool succeeds, it should commit the message. If it fails, it should abort the commit. This ensures that the hook does not break the workflow if there are issues.

Customizing the Hook Behavior

You can add environment variables to control the hook's behavior. For example, a SKIP_AUTO_COMMIT variable can disable the auto-commit feature. This gives users control over when the tool runs. You can also add a verbose mode to log the generated message for debugging purposes.

#!/bin/bash
# .git/hooks/pre-commit

# Run the Python tool
MESSAGE=$(python3 generate_commit.py)

# Commit the message
git commit -m "$MESSAGE"

Extending and Optimizing

The basic tool can be extended in many ways. You can add support for multiple models, allowing users to choose the best one for their needs. You can also add a cache mechanism to store generated messages and avoid redundant API calls. This can improve performance, especially for similar changes. Caching is a simple optimization that can save time and tokens.

You can also add a configuration file to store user preferences. This allows users to customize the prompt template, model parameters, and other settings. A configuration file makes the tool more flexible and easier to maintain. You can also add a help command to display usage instructions and examples. This improves the user experience and makes the tool more accessible.

Adding Caching

Use a local cache to store diffs and their corresponding commit messages. If the same diff is encountered again, return the cached message. This is useful for repetitive changes or when testing the tool. Caching reduces API calls and speeds up the tool, especially for large projects with many small changes.

Supporting Multiple Models

Allow users to specify a model in the configuration file. The tool can then send requests to different endpoints based on the selected model. This provides flexibility and allows users to experiment with different models. You can also add a feature to compare the output of different models and choose the best one.

# Example caching logic
cache = {}
def get_cached_message(diff):
    diff_hash = hash(diff)
    if diff_hash in cache:
        return cache[diff_hash]
    message = generate_commit_message(construct_prompt(diff))
    cache[diff_hash] = message
    return message
Git pre-commit hook file
Integrating the tool into the git workflow
Try the free API

Test the keyless endpoint now: stream responses in real-time with no API key required, perfect for prototyping your next fast AI application.

Read also