Using the DeepSeek API for Code Review Automation
Most teams don't need a model that reviews everything. They need one that reads the ten lines that actually changed and says something useful about them. That is the version of code review automation worth building: a diff-scoped reviewer that runs in CI, returns findings your tooling can parse, and stays quiet when there is nothing wrong.
Everything below is runnable. The code targets the AiCredits endpoint with model="deepseek-v4-flash", so you can drop it into a repository and iterate today. Reach for deepseek-v4-pro only on the paths where the stakes justify it.
What the bot should and shouldn't do
Read the diff, not the repository. Whole-file context inflates cost and nudges the model toward commenting on code nobody touched in this PR.
Answer in JSON. A free-form review comment is pleasant to read and miserable to automate. Structured output lets you dedupe, sort by severity, and gate a build.
Separate blockers from suggestions. A blocker should fail the pipeline. Everything else is a comment a human reads when they have time.
Stay out of the formatter's lane. Indentation, import order, and line length are solved problems. Spend model attention on logic.
Treat every finding as a candidate, not a verdict. The bot's job is to shorten the time until a human sees the real bug.
A reviewer that comments on every line gets muted within a week. A reviewer that surfaces three real defects per PR gets read every time.
Step 1: Give the model a diff, not a repository
Start with the merge-base diff. git diff base...HEAD (three dots) compares against the point where your branch diverged, so you never review changes that landed on the main branch while you were working. -U5 gives five lines of surrounding context, which is usually enough for the model to understand an added line without dragging in an entire file.
Filter by file extension so lockfiles, generated protobufs, and vendored dependencies never reach the API. If a path is generated, it should be reviewed upstream, not in every PR.
import json
import os
import subprocess
from openai import OpenAI
client = OpenAI(
api_key=os.environ["AICREDITS_API_KEY"],
base_url="https://api.aicreditsapi.com/v1",
)
BASE = os.environ.get('BASE_REF', 'origin/main')
REVIEWABLE = ('.py', '.js', '.ts', '.tsx', '.go', '.java', '.rb', '.rs')
def changed_files(base=BASE):
out = subprocess.run(
['git', 'diff', '--name-only', f'{base}...HEAD'],
capture_output=True, text=True, check=True,
)
return [f for f in out.stdout.splitlines() if f.endswith(REVIEWABLE)]
def file_diff(path, base=BASE):
out = subprocess.run(
['git', 'diff', '-U5', f'{base}...HEAD', '--', path],
capture_output=True, text=True, check=True,
)
return out.stdout
Step 2: Force structured findings and cap request size
Two design choices carry most of the quality here. The first is temperature=0 with response_format={'type': 'json_object'}: reviews should be reproducible, and valid JSON means you can pipe findings straight into a PR comment or a dashboard. The second is a fixed severity vocabulary — a small enum keeps both the model and your CI policy honest.
A single huge diff also degrades quality, because the model spreads attention thin across unrelated files. Chunking by character budget is crude but effective, and it gives you a natural place to route risky files to the stronger model.
SYSTEM_PROMPT = """You are a senior engineer reviewing a pull request diff.
Reply with JSON only:
{\"findings\": [{\"file\": str, \"line\": int, \"severity\": \"blocker\"|\"major\"|\"minor\", \"issue\": str, \"suggestion\": str}]}
Rules:
- Review only added (+) lines and their immediate context.
- Report a finding only when it changes correctness, safety, or performance.
- \"line\" is the line number in the new version of the file.
- If the diff is clean, return {\"findings\": []}.
- Never describe code that is not in the diff.
"""
MAX_CHARS = 24000
HIGH_RISK = ('auth', 'payment', 'billing', 'crypto', 'migration', 'permission')
def pick_model(path):
if any(key in path.lower() for key in HIGH_RISK):
return 'deepseek-v4-pro'
return 'deepseek-v4-flash'
def chunk(diff, limit=MAX_CHARS):
chunks, current, size = [], [], 0
for line in diff.splitlines(keepends=True):
if size + len(line) > limit and current:
chunks.append(''.join(current))
current, size = [], 0
current.append(line)
size += len(line)
if current:
chunks.append(''.join(current))
return chunks
def review_file(path, diff):
findings = []
for part in chunk(diff):
resp = client.chat.completions.create(
model=pick_model(path),
temperature=0,
response_format={'type': 'json_object'},
messages=[
{'role': 'system', 'content': SYSTEM_PROMPT},
{'role': 'user', 'content': 'File: ' + path + '\n\n```diff\n' + part + '\n```'},
],
)
payload = json.loads(resp.choices[0].message.content)
findings.extend(payload.get('findings', []))
return findings
Be honest about the tradeoff: a character-based chunk can cut a hunk in half, so the model may see an added line without its enclosing function. That is why the prompt says to flag only correctness-affecting issues and to avoid speculation. If you prefer clean boundaries, split on diff --git or @@ markers instead of a size budget — you will get fewer, larger, more coherent requests.
Step 3: Gate the build on blockers only
Now wire the findings together and decide what a non-zero exit code means. Deduplication matters more than it looks: overlapping chunks and repeated patterns produce near-identical findings, and a PR with eight copies of the same comment trains people to ignore the bot entirely.
def main():
findings = []
for path in changed_files():
findings.extend(review_file(path, file_diff(path)))
seen, unique = set(), []
for f in findings:
key = (f.get('file'), f.get('line'), f.get('issue', '')[:60])
if key not in seen:
seen.add(key)
unique.append(f)
print(json.dumps(unique, indent=2))
return 1 if any(f.get('severity') == 'blocker' for f in unique) else 0
if __name__ == '__main__':
raise SystemExit(main())
Step 4: Run it in CI
name: ai-code-review
on:
pull_request:
types: [opened, synchronize]
jobs:
review:
runs-on: ubuntu-latest
permissions:
contents: read
pull-requests: write
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: actions/setup-python@v5
with:
python-version: '3.12'
- run: pip install openai
- run: python review.py
env:
AICREDITS_API_KEY: ${{ secrets.AICREDITS_API_KEY }}
BASE_REF: origin/${{ github.base_ref }}
fetch-depth: 0 is required — the merge-base diff needs the full history, and a shallow clone will fail the git diff call. Because main() returns 1 only for blockers, the check fails loudly on real defects and stays green on suggestions. Capture stdout and post it as a single PR comment rather than one comment per finding.
Keeping signal high and spend predictable
Validate that every reported
lineactually appears in the diff before posting; drop anything that doesn't.Post one summary comment per run and edit it on each push instead of stacking new comments.
Keep
deepseek-v4-flashas the default and reservedeepseek-v4-profor security-sensitive and money-touching paths.Review only on push events, not on every comment or label change.
Cache aggressively by design: a stable system prompt and unchanged diff chunks are the cheapest requests you can send, and off-peak traffic costs less than peak.
Run your deterministic linter and formatter first, then the model. Don't pay tokens for problems a tool already caught.
Pricing on the AiCredits side is metered by usage, with cache hits and off-peak windows costing less than standard traffic, and deepseek-v4-pro costing more than deepseek-v4-flash. Rates change, so check aicreditsapi.com/pricing for the current numbers rather than hardcoding assumptions into your budget. Because AiCredits sells credits to international developers with card or PayPal and no Chinese phone number or bank account required, you can top up the same way you'd pay for any other SaaS tool and keep your CI secret in one place.
Where this approach breaks down
Diff-scoped review is excellent at local defects: off-by-one errors, unhandled null paths, missing rollback on a write, a swapped argument. It is weak at anything requiring cross-file reasoning — a new repository method that silently changes semantics for eight callers, or a schema migration that a downstream job hasn't caught up with. It also can't run the tests, so it cannot tell you the change is correct, only that it looks suspicious.
The practical answer is to use the bot as a first pass that clears obvious problems before a human spends attention, and to keep human review focused on design and cross-cutting impact. If you want a second opinion on style and dead code that doesn't depend on a model's mood, pair this pipeline with the linting tooling on AiCredits and let each tool do the job it is actually good at.
FAQ
No. AiCredits is built for international developers: sign up, pay by card or PayPal, and point the OpenAI SDK at base_url="https://api.aicreditsapi.com/v1" with your AiCredits key. The code in this article works unchanged.
deepseek-v4-flash handles the bulk of diffs well and is the sensible default. Route high-risk paths such as authentication, billing, migrations, and permissions to deepseek-v4-pro, where the extra strength is worth the higher cost.
It can, but it shouldn't. Whole-repo review burns context and money, and it produces findings on code that is outside the scope of the change. Review the merge-base diff and let full-repo analysis be a separate, occasional job.
Sometimes. Mitigate by setting temperature to 0, instructing the model to return an empty findings list when the diff is clean, validating that reported line numbers exist in the diff, and only failing CI on blocker severity.
Review only changed files, cap chunk size, default to deepseek-v4-flash, and run on push rather than on every event. Cache hits and off-peak traffic both cost less than standard usage. Current rates are listed at aicreditsapi.com/pricing.