Why pasting `git log` into a prompt makes bad changelogs
The naive version — dump the raw log, ask the model to "write release notes" — fails in three predictable ways. It invents user-facing framing for internal commits, it repeats the same change five times because five commits touched it, and it silently drops whatever fell past the context window in a busy release.
The fix is not a better prompt. It is moving the boring work out of the model: parse commit messages with a regex, throw away noise before you pay for tokens, split large releases into batches, and force the model to return structured JSON you can validate. If a line cannot be traced back to a commit SHA in the input, it does not ship.
The pipeline, in four moves
Resolve the baseline: the previous tag, or the root commit for a first release.
Parse
type(scope): subjectfrom each commit and drop chores, CI, formatting and WIP.Summarize in batches of roughly 40 commits with
deepseek-v4-flash, then dedupe the entries by text.Render to Keep-a-Changelog markdown and validate that every entry maps to a real SHA.
Runnable script: git history in, markdown out
Save this as changelog.py, export AICREDITS_API_KEY, and run python changelog.py v2.4.0. It finds the previous tag automatically and only reads commits made since then.
#!/usr/bin/env python3
"""changelog.py - turn git history into release notes."""
import json, os, re, subprocess, sys
from openai import OpenAI
client = OpenAI(
api_key=os.environ["AICREDITS_API_KEY"],
base_url="https://api.aicreditsapi.com/v1",
)
CONV = re.compile(r"^(?P<type>[a-zA-Z]+)(?:\((?P<scope>[^)]+)\))?!?:\s*(?P<desc>.+)$")
SKIP_TYPES = {"chore", "ci", "build", "test", "style", "docs"}
SECTIONS = ["Added", "Changed", "Fixed", "Performance", "Removed", "Security"]
def git(*args):
return subprocess.run(["git", *args], capture_output=True, text=True, check=True).stdout
def last_tag():
tags = git("tag", "--sort=-creatordate").split()
return tags[0] if tags else git("rev-list", "--max-parents=0", "HEAD").split()[0]
def commits_since(ref):
raw = git("log", ref + "..HEAD", "--no-merges", "--pretty=format:%H%x1f%s%x1f%b%x1e")
for rec in raw.split("\x1e"):
parts = rec.strip().split("\x1f")
if len(parts) < 2 or not parts[0]:
continue
yield {
"sha": parts[0][:7],
"subject": parts[1].strip(),
"body": (parts[2] if len(parts) > 2 else "").strip()[:300],
}
def classify(c):
m = CONV.match(c["subject"])
if m:
c.update(type=m["type"].lower(), scope=m["scope"], desc=m["desc"].strip())
else:
c.update(type="other", scope=None, desc=c["subject"])
if c["type"] in SKIP_TYPES or "[skip changelog]" in c["subject"].lower():
return None
return c if len(c["desc"]) >= 8 else None
SYSTEM = (
"You write release notes for end users. Use ONLY the commits provided. "
"Never invent features, numbers, links or dates. Merge duplicates. "
"Drop anything with no user-visible effect. Reply with JSON only."
)
def extract_json(text):
text = text.strip()
if text.startswith("```"):
text = re.sub(r"^```[a-zA-Z]*|```$", "", text).strip()
start, end = text.find("{"), text.rfind("}")
if start < 0 or end < 0:
raise ValueError("model did not return JSON: " + text[:200])
return text[start:end + 1]
def summarize(commits):
lines = "\n".join(
"- %s [%s] %s" % (c["sha"], c["type"], c["desc"]) for c in commits
)
resp = client.chat.completions.create(
model="deepseek-v4-flash",
temperature=0.2,
messages=[
{"role": "system", "content": SYSTEM},
{"role": "user", "content": (
"Commits:\n" + lines + "\n\n"
'Return {"entries":[{"section":"Added|Changed|Fixed|Performance|Removed|Security",'
'"text":"one imperative user-facing sentence","refs":["abc1234"]}]}'
)},
],
)
return json.loads(extract_json(resp.choices[0].message.content))["entries"]
def render(version, entries):
out = ["## " + version, ""]
for sec in SECTIONS:
rows = [e for e in entries if e.get("section") == sec]
if not rows:
continue
out.append("### " + sec)
for e in rows:
refs = " ".join("`%s`" % r for r in e.get("refs", []))
out.append("- " + e["text"] + (" (" + refs + ")" if refs else ""))
out.append("")
return "\n".join(out).strip()
def main():
version = sys.argv[1] if len(sys.argv) > 1 else "Unreleased"
base = sys.argv[2] if len(sys.argv) > 2 else last_tag()
commits = [c for c in map(classify, commits_since(base)) if c]
if not commits:
print("## " + version + "\n\nNo user-facing changes.")
return
entries, seen = [], set()
for i in range(0, len(commits), 40):
for e in summarize(commits[i:i + 40]):
key = e["text"].strip().lower()
if key not in seen:
seen.add(key)
entries.append(e)
print(render(version, entries))
if __name__ == "__main__":
main()
Two details matter more than the model choice. First, --no-merges plus the conventional-commit regex removes most of the garbage before a single token is spent, so you pay for a few thousand characters instead of a few hundred thousand. Second, batching at 40 commits keeps each request small enough that nothing gets truncated, and the seen set collapses near-duplicates that survive the filter.
The refs field is the cheap hallucination guard. Because the model can only cite SHAs that appeared in the prompt, you can spot-check entries by hand or reject them programmatically.
Commit types to changelog sections
| Conventional prefix | Section | What the model should write |
|---|---|---|
| feat / add | Added | New capability a user can use today |
| fix | Fixed | The broken behaviour, now working |
| perf | Performance | Faster or lighter, described qualitatively |
| refactor / change | Changed | Behaviour or API that shifted, not new |
| remove / deprecate | Removed | What is gone and the migration path |
| security/… | Security | Only when the commit body documents it |
When you need a second pass
deepseek-v4-flash is the right default: fast, and good enough to turn fix(auth): refresh token race into a readable line. For a headline release — a major version, a public launch — spend the extra on deepseek-v4-pro to rewrite the assembled entries into one consistent voice. Keep the same JSON schema and instruct the model to preserve facts, not to re-summarize.
def polish(entries, version):
resp = client.chat.completions.create(
model="deepseek-v4-pro",
temperature=0.3,
messages=[
{"role": "system", "content": SYSTEM},
{"role": "user", "content": (
"Edit these release notes for " + version + ": tighten the wording, "
"keep every fact, keep the same JSON schema.\n" + json.dumps({"entries": entries})
)},
],
)
return json.loads(extract_json(resp.choices[0].message.content))["entries"]
# in main(), just before render:
# entries = polish(entries, version)
That split is also how you keep the bill sane: pro costs more than flash, so you escalate only the final editing pass instead of every batch. Current rates live at aicreditsapi.com/deepseek-prices — off-peak traffic costs less, cache hits on repeated prompts cost less, and small releases often need no pro pass at all.
Wire it into CI on tag push
Generate notes at release time, not at commit time. The diff between the previous tag and HEAD is exactly your release, so a tag-push workflow is the natural trigger.
name: changelog
on:
push:
tags: ["v*"]
permissions:
contents: write
jobs:
notes:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- run: pip install openai
- name: Generate notes
run: |
PREV=$(git tag --sort=-creatordate | sed -n '2p')
python changelog.py "$GITHUB_REF_NAME" "${PREV:-$(git rev-list --max-parents=0 HEAD)}" > NOTES.md
env:
AICREDITS_API_KEY: ${{ secrets.AICREDITS_API_KEY }}
- run: gh release create "$GITHUB_REF_NAME" -F NOTES.md
env:
GH_TOKEN: ${{ github.token }}
fetch-depth: 0 is mandatory — a shallow clone has no tags and no history, and the script fails at git tag. Passing the previous tag explicitly avoids the classic bug where the tag you just pushed is also the baseline, producing an empty release.
Guards that keep the output honest
Temperature 0.2–0.3. Higher and the model starts "improving" your feature descriptions.
Validate refs: reject any entry whose SHA is not in the commit list you sent.
Allow an empty result. "No user-facing changes" is a correct answer for an internal release.
Cache the rendered output keyed on the sorted SHA list, so CI retries cost nothing.
Keep a human review gate for major versions. The model is a writer, not a release manager.
Frequently asked questions
Yes — the script uses the standard OpenAI SDK, so you only change base_url and the key. OpenAI's models are strong and the ecosystem is broad. AiCredits is aimed at teams who want DeepSeek models and can pay by card or PayPal, without a Chinese phone number or bank account behind the API key.
Run the script once per package with a path filter: change the git log call to git("log", ref + "..HEAD", "--no-merges", "--", "packages/api"). Tag per package instead of per repo, otherwise every package changelog inherits commits it never shipped.
The regex falls through to type "other" and the model still gets the subject, so you get output — but the noise filter cannot drop chores. Either adopt commitlint plus a [skip changelog] escape hatch, or feed the filter a blocklist of substrings like "wip" and "bump".
Batching keeps each request bounded, so nothing is truncated. For very large releases, do a two-level merge: summarize batches with flash, then feed the combined entries to pro with an instruction to merge duplicates across batches and keep every ref.
The model is the least important part of this pipeline. The regex, the batch size and the ref validation are what separate a changelog users read from one they scroll past.