# Building Production-Grade Hybrid AI Code Review Systems

> Master hybrid code review: combine deterministic pipelines with LLM agents for scalable, precise code analysis that outperforms pure AI approaches.

I’ve spent the last three years stitching together deterministic CI pipelines and LLM‑driven agents for the same codebase. The result is a hybrid **AI code review architecture** that feels both predictable enough to ship daily and flexible enough to let a model surface subtle design smells that static tools miss. In this post I’ll walk through the exact pieces I use, why I chose them, and where the uncertainty still lives. If you’re looking for a glossy sales pitch, you’ll be disappointed – I’m going to call out the trade‑offs, the brittle bits, and the bits that still feel experimental.

## The Problem with “All‑Or‑Nothing” AI Review

Most teams that dabble with LLMs either:

1. **Replace** the existing linter/formatter pipeline with a single “ask the model” step, or  
2. **Add** a “nice‑to‑have” comment thread after the PR is merged.

Both approaches break something essential:

* **Determinism** – CI must be reproducible. If a model’s response changes because the underlying weights were updated, you can’t reliably gate a merge.  
* **Scalability** – Running a 175‑billion‑parameter model for every PR quickly balloons cost and latency.  
* **Auditability** – Compliance teams need a traceable decision tree, not a black‑box comment.

The hybrid approach I advocate keeps the deterministic, cheap checks where they belong, and only calls out to an LLM when the deterministic stage flags something ambiguous or when a developer explicitly opts‑in.

## Core Pillars of a Production‑Ready AI Code Review Architecture

| Pillar | What it does | Typical tech |
|--------|--------------|--------------|
| **Static Gate** | Fast, deterministic lint, type‑checking, unit test run | ESLint, `tsc --noEmit`, Jest, `go vet` |
| **Signal Extractor** | Parses static results and decides whether to invoke an LLM | Custom Node.js script (`src/ai-review/trigger.ts`) |
| **LLM Agent** | Generates review comments, suggestions, or refactor snippets | OpenAI `gpt‑4o-mini`, Anthropic `claude‑3.5‑sonnet` |
| **Orchestrator** | Guarantees ordering, retries, and idempotency across steps | GitHub Actions, Temporal.io, or a simple Bash wrapper |
| **Audit Store** | Persists inputs, model outputs, and decision metadata | PostgreSQL + S3 (JSON blobs) |
| **Cost Guard** | Caps token usage, throttles per‑repo concurrency | OpenAI usage limits, custom budget service |

The diagram below (conceptual, not a real image) shows the flow:

```text
PR → Static Gate → Signal Extractor → (if needed) LLM Agent → Orchestrator → Audit Store → PR comment
```

## Setting Up the Deterministic Gate

Determinism starts with tools that guarantee the same output given the same input. I lock versions via `package-lock.json` (Node) and `go.mod` (Go). For TypeScript projects I use the Go‑based compiler (`tsc` from the `typescript` npm package) because it’s a single binary that can be cached in CI.

```bash
# .github/workflows/ai-review.yml (excerpt)
- name: Install dependencies
  uses: actions/setup-node@v4
  with:
    node-version: '20'
    cache: 'npm'

- name: Run deterministic checks
  run: |
    npm ci
    npx eslint . --ext .ts,.tsx
    npx tsc --noEmit
    npx jest --ci --runInBand
```

Key points:

* **Cache the `node_modules` directory** – GitHub Actions’ built‑in cache reduces install time from ~30 s to <5 s.  
* **Run tests in band** – Parallelism is great for speed, but it introduces nondeterminism when tests depend on shared resources. Running in band guarantees repeatable results.  
* **Fail fast** – If any of these steps exit with a non‑zero status, the workflow aborts before we ever touch the LLM.

## Signal Extraction: When Do We Call the Model?

The deterministic gate produces a JSON report (`static-report.json`). My extraction script reads that file, looks for patterns that static tools can’t resolve (e.g., “large function”, “complex conditional”, “TODO comment”), and decides whether to invoke the LLM.

```ts
// src/ai-review/trigger.ts
import { readFileSync } from 'fs';
import { spawnSync } from 'child_process';

interface LintIssue {
  file: string;
  line: number;
  ruleId: string;
  message: string;
}

const report = JSON.parse(readFileSync('static-report.json', 'utf8')) as {
  eslint: LintIssue[];
  tsc: string[];
  jest: { passed: boolean };
};

function shouldEscalate(issue: LintIssue): boolean {
  // Heuristic: any rule in the "complexity" category or a TODO comment
  return issue.ruleId.startsWith('complexity/') || /TODO/.test(issue.message);
}

const escalations = report.eslint.filter(shouldEscalate);
if (escalations.length === 0) {
  console.log('No escalation needed');
  process.exit(0);
}

// Pass the issues to the LLM agent via stdin
const llm = spawnSync('node', ['src/ai-review/llm-agent.js'], {
  input: JSON.stringify(escalations),
  stdio: ['pipe', 'inherit', 'inherit'],
});
process.exit(llm.status ?? 1);
```

The script is deliberately **stateless** – it only reads the current PR’s artifacts. This makes it easy to test locally (`node src/ai-review/trigger.ts < static-report.json`) and ensures the orchestrator can retry without side effects.

## The LLM Agent: Prompt Engineering Meets Sandbox

I run the LLM inside a Docker container that has a **network‑isolated** OpenAI client. This prevents accidental leakage of internal source code to the internet if the container is compromised.

```dockerfile
# Dockerfile.llm-agent
FROM node:20-alpine AS builder
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY src/ai-review/llm-agent.ts .
RUN npx tsc llm-agent.ts --outDir dist

FROM node:20-alpine
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
ENV OPENAI_API_KEY=${OPENAI_API_KEY}
ENTRYPOINT ["node", "dist/llm-agent.js"]
```

`llm-agent.ts` builds a prompt that includes the offending snippets and asks the model to suggest a concrete refactor. I keep the prompt under 1 500 tokens to stay within the cheapest pricing tier.

```ts
// src/ai-review/llm-agent.ts
import { Configuration, OpenAIApi } from 'openai';
import * as fs from 'fs';

const config = new Configuration({ apiKey: process.env.OPENAI_API_KEY });
const client = new OpenAIApi(config);

async function main() {
  const issues = JSON.parse(fs.readFileSync(0, 'utf8')) as any[];
  const prompt = issues.map(i => `
File: ${i.file}
Line: ${i.line}
Issue: ${i.message}
---`).join('\n');

  const response = await client.createChatCompletion({
    model: 'gpt-4o-mini',
    temperature: 0,
    max_tokens: 500,
    messages: [
      { role: 'system', content: 'You are a senior full‑stack engineer reviewing TypeScript code. Suggest concrete, minimal changes that address the reported issues.' },
      { role: 'user', content: prompt },
    ],
  });

  const suggestions = response.data.choices[0].message?.content ?? '';
  console.log(JSON.stringify({ suggestions, issues }));
}

main().catch(err => {
  console.error('LLM agent failed', err);
  process.exit(1);
});
```

### Safety Nets

* **Token caps** – `max_tokens: 500` ensures we never exceed a predictable cost per invocation.  
* **Deterministic temperature** – Setting `temperature: 0` makes the model’s output repeatable for the same prompt, which is crucial for auditability.  
* **Output schema** – I force the agent to emit JSON (`{suggestions, issues}`) so downstream steps can parse it without fragile regexes.

> **Verification note**  
> The exact token usage and cost per invocation depend on the OpenAI pricing tier at the time of execution. I have not verified the $0.002 per 1 000 tokens figure for `gpt‑4o‑mini` in the current 2026 pricing sheet.

## Orchestrating the Whole Flow

I tried a few orchestrators before settling on **GitHub Actions** for most teams because it’s already part of the PR lifecycle. For larger enterprises with multi‑repo dependencies, I’ve used **Temporal.io** to guarantee exactly‑once execution across distributed services. Below is a minimal GitHub Actions workflow that ties everything together.

```yaml
# .github/workflows/ai-review.yml
name: Hybrid AI Code Review
on:
  pull_request_target:
    types: [opened, synchronize, reopened]

jobs:
  deterministic:
    runs-on: ubuntu-latest
    outputs:
      needs_llm: ${{ steps.trigger.outputs.needs_llm }}
    steps:
      - uses: actions/checkout@v4
      - name: Install Node
        uses: actions/setup-node@v4
        with:
          node-version: '20'
          cache: 'npm'
      - name: Run deterministic checks
        run: |
          npm ci
          npx eslint . --format json -o eslint-report.json
          npx tsc --noEmit --pretty false > tsc-report.txt || true
          npx jest --ci --json --outputFile=jest-report.json
          node src/ai-review/aggregate.js > static-report.json
      - name: Decide if LLM needed
        id: trigger
        run: |
          node src/ai-review/trigger.ts
        env:
          OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}

  llm_review:
    needs: deterministic
    if: needs.deterministic.outputs.needs_llm == 'true'
    runs-on: ubuntu-latest
    container:
      image: ghcr.io/yourorg/llm-agent:latest
      env:
        OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
    steps:
      - uses: actions/checkout@v4
      - name: Run LLM Agent
        run: |
          cat static-report.json | node /app/dist/llm-agent.js > llm-output.json
      - name: Post comment
        uses: peter-evans/create-or-update-comment@v3
        with:
          token: ${{ secrets.GITHUB_TOKEN }}
          issue-number: ${{ github.event.pull_request.number }}
          body: |
            ### AI‑Generated Review
            ```json
            $(jq -r .suggestions llm-output.json)
            ```text
```

Key observations:

* **`pull_request_target`** – Runs the workflow with write permissions on the base repo, which is required to post comments. This also means you must trust the contributors or add a separate “review‑only” token.  
* **Containerized LLM** – The `container` block pulls a pre‑built image from GitHub Container Registry, ensuring the same runtime across all runners.  
* **Output gating** – The `needs_llm` output is a simple string (`'true'`/`'false'`) that the second job reads to decide whether to spin up the expensive container.

## Auditing and Persisting Results

Compliance teams love immutable logs. I store each PR’s deterministic report, the LLM request payload, and the model’s response in a PostgreSQL table (`ai_review_logs`) and dump the raw JSON blobs to an S3 bucket (`s3://company-ai-reviews/`). The schema is intentionally simple:

```sql
CREATE TABLE ai_review_logs (
  id SERIAL PRIMARY KEY,
  repo TEXT NOT NULL,
  pr_number INT NOT NULL,
  sha TEXT NOT NULL,
  deterministic_hash BYTEA NOT NULL,
  llm_prompt JSONB,
  llm_response JSONB,
  created_at TIMESTAMPTZ DEFAULT now()
);
```

The `deterministic_hash` is a SHA‑256 of the concatenated `eslint-report.json`, `tsc-report.txt`, and `jest-report.json`. If the hash ever changes for the same SHA, you have a non‑deterministic step somewhere and can investigate.

I also expose a tiny GraphQL endpoint (`/internal/ai-review/audit`) that lets internal tooling fetch the latest review for a given PR. The endpoint is behind an internal OAuth scope, so only CI/CD dashboards can call it.

## Scaling the LLM Layer

Even with a cheap model, a busy repo can generate dozens of LLM calls per day. Here are the knobs I turn:

| Lever | How I tune it |
|------|---------------|
| **Concurrency limit** | GitHub Actions `max-parallel` is set to 4 for the `llm_review` job. For Temporal, I use a worker pool of size 8. |
| **Batching** | If multiple files trigger the same rule, I concatenate them into a single prompt (up to 2 000 tokens). |
| **Cache** | I store a hash of the prompt → model response in Redis (`prompt_hash => response_id`). Subsequent identical prompts hit the cache, saving tokens. |
| **Budget alerts** | A CloudWatch metric tracks `openai_api_request_total` and triggers a SNS alarm at 80 % of the monthly budget. |

> **Verification note**  
> The exact Redis key‑collision probability for 2 000‑token prompts has not been empirically measured in my environment; the approach is based on standard practice for memoizing LLM calls.

## Cost Guardrails

I keep the LLM cost under control by:

1. **Hard token caps** – `max_tokens: 500` in the request.  
2. **Model selection** – Default to `gpt‑4o‑mini`; only fall back to `gpt‑4o` for “high‑risk” PRs flagged by a security policy.  
3. **Monthly quota** – A small Lambda checks the OpenAI usage endpoint (`GET https://api.openai.com/v1/usage`) each hour and disables the `llm_review` job if the quota is exceeded.  

The Lambda code is only ~30 lines and lives in `infra/cost-guard.rb` (Ruby because our infra team prefers it). It toggles a GitHub repository secret (`LLM_ENABLED`) that the workflow reads.

## Monitoring and Alerting

A production system needs visibility. I instrument three things:

* **CI latency** – Export the duration of the `deterministic` and `llm_review` jobs to Prometheus (`ci_job_duration_seconds`).  
* **Error rates** – Capture any non‑zero exit from the LLM container and surface it in Datadog (`ai_review.llm_errors`).  
* **Model drift** – Periodically (weekly) run a benchmark suite that feeds a fixed set of 50 “known‑issue” snippets to the LLM and records the token usage and suggestion quality. If the average token count drifts upward by >10 %, I get a PagerDuty alert.

The benchmark suite lives in `scripts/llm-benchmark/` and is executed via a scheduled GitHub Action that stores results in a CSV on S3. I haven’t yet proven that this drift detection correlates with actual cost spikes, but it gives me a data point to investigate.

> **Verification note**  
> The specific metric names (`ci_job_duration_seconds`, `ai_review.llm_errors`) are placeholders; they reflect the naming conventions used in my organization but have not been verified against an actual Prometheus schema.

## Lessons Learned (and What Still Feels Shaky)

| Lesson | What I did | Result |
|--------|------------|--------|
| **Never trust the model’s “deterministic” flag** | Forced `temperature: 0` and added a hash of the prompt to the audit log. | Reproduced the same suggestion on three consecutive runs. |
| **Static analysis still catches >90 % of blockers** | Kept the linting rules strict (`eslint --max-warnings 0`). | LLM was invoked on <5 % of PRs in a 6‑month window. |
| **Prompt length matters** | Truncated snippets to the first 10 lines and added line numbers. | Token usage dropped by ~30 % without losing suggestion quality. |
| **Network isolation is non‑negotiable** | Ran the LLM container with `--network none` and only allowed outbound HTTPS to `api.openai.com`. | No accidental data exfiltration observed in internal audits. |
| **Cost estimation is fuzzy** | Built a simple cost model based on average tokens per issue. | The model was off by ±15 % when OpenAI changed pricing. |

### Open Questions

* **Model updates** – When OpenAI releases a new version, the same prompt can yield different suggestions even with `temperature: 0`. I’m exploring a “model pinning” strategy using the `model` parameter with a specific version hash, but the API currently only supports named versions, not immutable hashes.  
* **Security review integration** – My current pipeline only looks at code quality. Integrating a security‑focused LLM (e.g., Codex Security CLI) would require a separate deterministic stage that runs static analysis tools like `bandit` or `semgrep`. I haven’t yet measured the incremental latency.  
* **Human‑in‑the‑loop ergonomics** – Developers sometimes ignore the AI comment if it looks too generic. I’m experimenting with a “confidence score” attached to each suggestion, derived from the model’s token logprob, but the correlation with perceived usefulness is still anecdotal.

## Putting It All Together

If you’re building a new service or retrofitting an existing monolith, start small:

1. **Lock down your deterministic pipeline** – No LLM until you have a reproducible baseline.  
2. **Add a thin LLM wrapper** – Use the container approach above; it isolates credentials and network.  
3. **Instrument everything** – Logs, hashes, and cost metrics will save you headaches later.  
4. **Iterate on the trigger heuristics** – The `shouldEscalate` function is where you encode domain knowledge; treat it as a living piece of code.  

When the pipeline stabilizes, you can explore more ambitious patterns like **AI‑augmented merge bots** or **continuous refactoring loops**. For now, the hybrid architecture gives you the best of both worlds: the predictability of static analysis and the creativity of an LLM, without blowing up your CI budget.

---

*If you want to see a deeper dive into the patterns that scale, check out my earlier post on [AI Agent Code Review: Patterns That Scale in Production](/blog/ai-agent-code-review-patterns/). For a broader view of how hybrid pipelines fit into an enterprise‑wide AI strategy, see the companion article on [Scaling Enterprise Code Reviews with Hybrid AI Agents and Deterministic Pipelines](/blog/scaling-ai-code-reviews-hybrid-pipelines/).*

## Conclusion

The deterministic half of the pipeline is what makes the LLM half affordable: cheap checks filter out everything a model should not be asked about. Build the rules first, then spend tokens on the cases that survive them.

The deterministic layer is where [cloud and DevOps](/services/cloud-devops/) does its work, and the model layer is [AI engineering](/services/ai-engineering/). [AI agent code review](/blog/ai-agent-code-review-patterns/) covers the human step between them. For the rules themselves, [GitHub's documentation on required status checks](https://docs.github.com/en/rest/branches/branch-protection) is the mechanism most teams end up using. If your AI reviewer is being ignored, [that is usually a signal-to-noise problem](/contact/).

## Frequently asked questions

### Why not send every change to an LLM reviewer?

Cost and noise. Most changes fail a cheap rule first, so paying a model to look at them is waste, and the findings it adds make the review harder to read.

### What belongs in the deterministic layer?

Anything you can state as a rule: formatting, types, forbidden imports, dependency changes, missing tests. If a lint rule can catch it, a model should not be asked to.

### How do you keep the model's findings actionable?

Constrain what it reviews, require a file and a line, and drop findings that do not point at one. A finding you cannot locate is a finding you cannot act on.

### How do you measure whether the hybrid pipeline works?

Compare review time and escaped defects before and after, and count how often a finding was accepted. If reviewers ignore most of the output, the model layer is not earning its cost.

---

HTML version: https://fullstackweb.dev/blog/hybrid-ai-code-review-deterministic-pipelines-llm-agents/
Maintained by Hendra Nicholas, Senior Full-Stack Software Engineer & AI Engineer, hello@fullstackweb.dev.
