🔧 AI Nachrichten ChatGPT showing blank screen [Fix](05.09.2026 um 19:55 Uhr)
⚠️ Malware / Trojaner / VirenSofort deinstallieren: Diese 19 Browser-Erweiterungen sind mit Malware verseucht(06.09.2026 um 08:00 Uhr)
⚠️ Malware / Trojaner / VirenLumma Stealer – dllhost.exe Hollowing, C2 Domains & Payload Extraction(01.09.2026 um 17:19 Uhr)
🔧 AI Nachrichten Simcha Kosman AMA: Owning ChatGPT's Secure Sandbox(03.09.2026 um 07:41 Uhr)
⚠️ Malware / Trojaner / VirenThe Gentlemen Ransomware Analysis: Go Obfuscated(04.09.2026 um 12:05 Uhr)
⚠️ Malware / Trojaner / VirenTengu, a Mirai-style Linux and IoT botnet(06.09.2026 um 15:27 Uhr)
🔧 AI Nachrichten ChatGPT showing blank screen [Fix](05.09.2026 um 19:55 Uhr)
⚠️ Malware / Trojaner / VirenSofort deinstallieren: Diese 19 Browser-Erweiterungen sind mit Malware verseucht(06.09.2026 um 08:00 Uhr)
⚠️ Malware / Trojaner / VirenLumma Stealer – dllhost.exe Hollowing, C2 Domains & Payload Extraction(01.09.2026 um 17:19 Uhr)
🔧 AI Nachrichten Simcha Kosman AMA: Owning ChatGPT's Secure Sandbox(03.09.2026 um 07:41 Uhr)
⚠️ Malware / Trojaner / VirenThe Gentlemen Ransomware Analysis: Go Obfuscated(04.09.2026 um 12:05 Uhr)
⚠️ Malware / Trojaner / VirenTengu, a Mirai-style Linux and IoT botnet(06.09.2026 um 15:27 Uhr)

🔧 Programmierung 🕛 kürzlich 7 Min Lesezeit
0

How to Build a Self-Hosted AI Code Review Tool in Python

↗ Quelle (dev.to)
🗣️ Stimme:
📑 Inhaltsübersicht

Every team has the same code review problem: PRs sit for days, reviewers miss subtle logic bugs, and security issues slip through because nobody carefully checked the authentication layer. Linters catch syntax and style issues, but they don't reason about intent. A language model can — and you can run it entirely on your own infrastructure without sending a single line of your source code to a third party.



This guide walks you through building a self-hosted AI code review tool in Python. It reads a git diff, sends it to a locally hosted language model, and returns structured review comments you can pipe directly into your CI workflow.






Why Self-Hosted Matters



Sending your source code to an external API is a significant trust decision. For proprietary code, regulated industries, or anything security-sensitive, you want model inference happening inside your own perimeter. Ollama handles this cleanly: it runs any GGUF-quantized model locally and exposes an HTTP endpoint that's fully compatible with the OpenAI Python SDK. You get the same API surface, zero data egress.



The architecture is intentionally simple:




  • A Python script reads a git diff (or file path)

  • It splits the diff into manageable chunks

  • Each chunk is sent to the local LLM with a structured system prompt

  • The model returns JSON-formatted review comments

  • You aggregate and display them — or feed them into your CI gate






Setting Up



You need Python 3.11+, the openai SDK (it works against any compatible endpoint), and Ollama running locally with a code-focused model. codellama:13b works well; deepseek-coder:6.7b is faster and nearly as accurate for review tasks.




CODE
pip install openai gitpython
ollama pull deepseek-coder:6.7b






Store your config in a .env file — the script reads from environment variables so swapping models requires no code changes:




CODE
OLLAMA_BASE_URL=http://localhost:11434/v1
OLLAMA_API_KEY=ollama
OLLAMA_MODEL=deepseek-coder:6.7b









The Core Reviewer



The script reads a diff from a file argument or stdin (which makes it trivial to wire into a git hook), sends it to the model, and parses the structured output.




CODE
import os, json, sys
from openai import OpenAI

client = OpenAI(
base_url=os.getenv("OLLAMA_BASE_URL", "http://localhost:11434/v1"),
api_key=os.getenv("OLLAMA_API_KEY", "ollama"),
)
MODEL = os.getenv("OLLAMA_MODEL", "deepseek-coder:6.7b")

SYSTEM_PROMPT = (
"You are a senior software engineer performing a code review.\n"
"Analyze the provided code diff and return a JSON array of review comments.\n"
"Each comment must have: severity (critical/warning/suggestion), "
"line (int or null), message (str), fix (str or null).\n"
"Return ONLY valid JSON. No prose outside the JSON array."
)

def review_diff(diff_text: str, max_chunk_chars: int = 6000) -> list[dict]:
lines = diff_text.splitlines(keepends=True)
chunks, current, current_len = [], [], 0
for line in lines:
if current_len + len(line) > max_chunk_chars and current:
chunks.append("".join(current))
current, current_len = [], 0
current.append(line)
current_len += len(line)
if current:
chunks.append("".join(current))

all_comments = []
for chunk in chunks:
response = client.chat.completions.create(
model=MODEL,
messages=[
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": f"Review this diff:\n\n{chunk}"},
],
temperature=0.1,
max_tokens=1024,
)
raw = response.choices[0].message.content.strip()
try:
comments = json.loads(raw)
if isinstance(comments, list):
all_comments.extend(comments)
except json.JSONDecodeError:
pass
return all_comments

if __name__ == "__main__":
diff = open(sys.argv[1]).read() if len(sys.argv) > 1 else sys.stdin.read()
comments = review_diff(diff)
has_critical = False
for c in sorted(comments, key=lambda x: ["critical","warning","suggestion"].index(x.get("severity","suggestion"))):
print(f"[{c.get('severity','?').upper()}] line {c.get('line','?')}: {c.get('message','')}")
if c.get("fix"):
print(f"{c['fix']}\n")
if c.get("severity") == "critical":
has_critical = True
sys.exit(1 if has_critical else 0)






The script exits with code 1 if any critical issue is found, making it trivial to use as a blocking pre-push hook or CI gate.






Integrating into CI



For GitHub Actions, run the reviewer on every pull request diff:




CODE
name: AI Code Review
on: [pull_request]

jobs:
review:
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: Run AI review
env:
OLLAMA_BASE_URL: ${{ secrets.OLLAMA_BASE_URL }}
OLLAMA_API_KEY: ${{ secrets.OLLAMA_API_KEY }}
OLLAMA_MODEL: deepseek-coder:6.7b
run: |
git diff origin/${{ github.base_ref }}...HEAD > pr.diff
python reviewer.py pr.diff






For self-hosted CI (Gitea Actions, GitLab CI, Jenkins), point OLLAMA_BASE_URL at your internal Ollama instance. The runner needs network access to it, but nothing leaves your perimeter. If your Ollama node lives on a private subnet, use a dedicated runner in that subnet rather than routing through a proxy.






Hardening the Prompt for Security Review



The default prompt covers general code quality. When you want security-focused output — useful as a pre-merge gate on sensitive services — specialize the system prompt:




CODE
SECURITY_PROMPT = (
"You are a security-focused code reviewer.\n"
"Flag only security vulnerabilities: injection flaws, auth bypasses, "
"insecure deserialization, hardcoded credentials, missing input validation, "
"race conditions, and OWASP Top 10 patterns.\n"
"Return a JSON array: [{severity, cwe, line, message, fix}]. "
"Return ONLY valid JSON."
)






Swap this in for SYSTEM_PROMPT. The cwe field is useful if you want to integrate findings with a vulnerability tracker or feed them into a risk scoring pipeline.



Keep in mind that language models produce false positives at a non-trivial rate. Treat this layer as a fast first-pass triage, not a substitute for manual review. For a structured view of what to actually check before shipping to production, our , a cybersecurity consulting firm. We publish free security hardening checklists — PDF and Excel.

Vollständiger Original-Bericht
Ausführliche Details, Code-Beispiele & Hersteller-Stellungnahme auf dev.to.
↗ Original-Artikel auf dev.to lesen
Wie bewertest du diesen Beitrag?
1 Klick Feedback
Teilen mit Netzwerk & Team:

Community-Analysen & Experten-Meinungen 0

Verfasse deine eigene Analyse, teile Workarounds oder diskutiere diesen Vorfall im Blog.
Noch keine Community-Analyse verfasst. Markiere einen Textabschnitt oder klicke oben auf Eigene Analyse verfassen“!
Community Pulse: Relevanz-Einschätzung
1 Klick Experten-Votum
🔴 Akute Relevanz 45%
🟡 In Evaluierung 25%
🟢 Keine Auswirkung 19%
Spannende Innovation 11%
Verwandte Story-Cluster & Quellen (Vektor-KI)
Port 8095 Engine
2 Quellen
Creator Panel – One Creator, Full Production: Der neue Creator Workflow
1 Quelle
ChatGPT showing blank screen [Fix]
1 Quelle
Sofort deinstallieren: Diese 19 Browser-Erweiterungen sind mit Malware verseucht
Ähnliche Beiträge
🔍 Verwandte News

Auch interessante Nachrichten How to Build a Self-Hosted AI Code Review Tool in Python

Thematisch verwandte Begriffe: Build, SelfHosted, Code, Review · 6 Treffer

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...