# Automatic code review

Have a model review each change before it merges.

1. [Give the review its own key](#1-give-the-review-its-own-key).
2. [Write the review script](#2-write-the-review-script).
3. [Run it on your branch](#3-run-it-on-your-branch).
4. [Run it on every pull request](#4-run-it-on-every-pull-request).

## 1. Give the review its own key

Create an API key named for the job, such as *Code review*, and cap it on *API Keys* ([API keys](/docs/api-keys) shows how). A review runs on every push: its own key and cap keep that spend apart from your other apps, and a spent cap stops the review alone with a 402.

Put the key in `OPENDUNES_API_KEY`, in the terminal you run the script from.

## 2. Write the review script

The script reads what your branch changed since it left `main`, as a unified diff, and sends it to [`POST /v1/chat/completions`](/docs/reference/chat-completions) with instructions for a reviewer. It prints the review, then the charge in DA.

| Input | Holds |
|---|---|
| `BASE_REF` | the branch your change goes into: `origin/main` |
| `INSTRUCTIONS` | what the reviewer looks for, sent as the system message |
| the diff | `git diff origin/main...HEAD`: this branch's changes alone |

```python
import os
import subprocess
from openai import OpenAI

API_KEY = os.environ["OPENDUNES_API_KEY"]
BASE_URL = "https://opendunes.com/v1"
MODEL = "anthropic/claude-sonnet-4.5"
BASE_REF = "origin/main"
INSTRUCTIONS = (
    "You review a code change, given as a unified diff. "
    "List bugs, security holes and missing tests, each with its "
    "file and line, most serious first. Say nothing about what is fine."
)

diff = subprocess.run(
    ["git", "diff", f"{BASE_REF}...HEAD"],
    capture_output=True,
    text=True,
    check=True,
).stdout

if not diff.strip():
    print("No change to review.")
    raise SystemExit

client = OpenAI(base_url=BASE_URL, api_key=API_KEY)

reply = client.chat.completions.create(
    model=MODEL,
    messages=[
        {"role": "system", "content": INSTRUCTIONS},
        {"role": "user", "content": diff},
    ],
)

print(reply.choices[0].message.content)
print(reply.usage.cost)
```

```javascript
import { execFileSync } from "node:child_process";
import OpenAI from "openai";

const API_KEY = process.env.OPENDUNES_API_KEY;
const BASE_URL = "https://opendunes.com/v1";
const MODEL = "anthropic/claude-sonnet-4.5";
const BASE_REF = "origin/main";
const INSTRUCTIONS = [
  "You review a code change, given as a unified diff.",
  "List bugs, security holes and missing tests, each with its",
  "file and line, most serious first. Say nothing about what is fine.",
].join(" ");

const diff = execFileSync("git", ["diff", `${BASE_REF}...HEAD`], {
  encoding: "utf8",
  maxBuffer: 64 * 1024 * 1024,
});

if (!diff.trim()) {
  console.log("No change to review.");
  process.exit(0);
}

const client = new OpenAI({ baseURL: BASE_URL, apiKey: API_KEY });

const reply = await client.chat.completions.create({
  model: MODEL,
  messages: [
    { role: "system", content: INSTRUCTIONS },
    { role: "user", content: diff },
  ],
});

console.log(reply.choices[0].message.content);
console.log(reply.usage.cost);
```

```go
package main

import (
	"context"
	"fmt"
	"os"
	"os/exec"
	"strings"

	"github.com/openai/openai-go/v3"
	"github.com/openai/openai-go/v3/option"
)

const (
	baseURL = "https://opendunes.com/v1"
	model   = "anthropic/claude-sonnet-4.5"
	baseRef = "origin/main"
)

func main() {
	apiKey := os.Getenv("OPENDUNES_API_KEY")

	out, err := exec.Command("git", "diff", baseRef+"...HEAD").Output()
	if err != nil {
		panic(err)
	}
	diff := string(out)
	if strings.TrimSpace(diff) == "" {
		fmt.Println("No change to review.")
		return
	}

	client := openai.NewClient(
		option.WithBaseURL(baseURL),
		option.WithAPIKey(apiKey),
	)

	params := openai.ChatCompletionNewParams{
		Model: model,
		Messages: []openai.ChatCompletionMessageParamUnion{
			openai.SystemMessage(instructions),
			openai.UserMessage(diff),
		},
	}
	reply, err := client.Chat.Completions.New(context.TODO(), params)
	if err != nil {
		panic(err)
	}

	fmt.Println(reply.Choices[0].Message.Content)
	fmt.Println(reply.Usage.JSON.ExtraFields["cost"].Raw())
}

const instructions = "You review a code change, given as a unified diff. " +
	"List bugs, security holes and missing tests, each with its " +
	"file and line, most serious first. Say nothing about what is fine."
```

```bash cURL
ADDRESS="https://opendunes.com/v1/chat/completions"
MODEL="anthropic/claude-sonnet-4.5"
BASE_REF="origin/main"
INSTRUCTIONS="You review a code change, given as a unified diff. \
List bugs, security holes and missing tests, each with its \
file and line, most serious first. Say nothing about what is fine."
DIFF=$(git diff "$BASE_REF...HEAD")

jq -n \
  --arg model "$MODEL" \
  --arg system "$INSTRUCTIONS" \
  --arg diff "$DIFF" \
  '{
    model: $model,
    messages: [
      {role: "system", content: $system},
      {role: "user", content: $diff}
    ]
  }' |
curl "$ADDRESS" \
  -H "Authorization: Bearer $OPENDUNES_API_KEY" \
  -H "Content-Type: application/json" \
  -d @- |
jq -r '.choices[0].message.content, .usage.cost'
```

The cURL tab builds the body with `jq`, which escapes the diff's quotes and line breaks for you.

## 3. Run it on your branch

Save the script as `review.py` at the root of your repository, fetch the base branch, and run it from your branch.

```bash
git fetch origin main
python review.py
```

The review prints first, then its charge in DA. Illustrative, for a small change:

```text
1. src/cart.py:42: total() adds the delivery fee twice when the
   coupon is empty. Add it once, after the discount.
2. src/cart.py:57: no test covers an empty cart.
0.412871
```

<div class="watch-out">
<p>The whole diff is prompt tokens, sent again on every run. A branch that renames a folder or commits a generated file sends thousands of lines: review from a branch that holds your change alone, or leave generated files out with <code>git diff origin/main...HEAD -- . ':!*.lock'</code>.</p>
</div>

## 4. Run it on every pull request

In your repository's settings on GitHub, add the review key as the Actions secret `OPENDUNES_API_KEY`. Then commit this workflow as `.github/workflows/review.yml`. On each pull request into `main`, it runs `review.py` and posts the review as a comment.

```yaml
name: Code review

on:
  pull_request:
    branches: [main]

permissions:
  contents: read
  pull-requests: write

jobs:
  review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
        with:
          fetch-depth: 0
      - uses: actions/setup-python@v7
        with:
          python-version: "3.13"
      - run: pip install openai
      - run: python review.py > review.md
        env:
          OPENDUNES_API_KEY: ${{ secrets.OPENDUNES_API_KEY }}
      - run: gh pr comment "$PR" --body-file review.md
        env:
          GH_TOKEN: ${{ github.token }}
          PR: ${{ github.event.pull_request.number }}
```

`fetch-depth: 0` fetches the history, so `origin/main...HEAD` finds where the branch left `main`.

<div class="dont">
<p>Don't expect the review on a pull request opened from a fork. GitHub gives such a run no secrets: the script sends no key and gets a 401.</p>
</div>

<div class="do">
<p>Review forks' changes from your own branch, with step 3, once you have read them.</p>
</div>

## Pick the reviewer

Any text model that reads code does the job: the model is the one value to change. A stronger model reads a large change more closely, and each review costs more.

| Model ID | Suits |
|---|---|
| `anthropic/claude-sonnet-4.5` | every pull request |
| `anthropic/claude-opus-5.5` | a change you want read line by line before a release |

```json
{
  "model": "anthropic/claude-opus-5.5"
}
```

Each model's charge is on its page in [Models](/docs/models). Every review's charge is on *Activity*, in the app, under the review key.

## Errors

| Status | Means | Do |
|---|---|---|
| 401 | no key reached the script | set `OPENDUNES_API_KEY` in the terminal, or add the Actions secret |
| 402 | the balance is at zero or below, cannot pay the request's hold, or the review key's cap is spent | make a deposit, or raise the cap |
| 400 | the diff is longer than the model reads | review a smaller change, or pick a model that reads more |

Every other status: [Errors and retries](/docs/errors-and-retries).

Next: [Claude Code](/docs/cookbook/claude-code) · [Coding agents](/docs/coding-agents) · [Streaming](/docs/streaming)
