---
title: "Aider with DeepSeek Coder via OpenRouter: branch refactor"
description: "Aider configured with DeepSeek Coder V2 via OpenRouter for a targeted refactor on an isolated branch. Auto-commit, repo map, file-scope constraints, regression tests before merge."
url: "https://www.noze.it/en/insights/aider-branch-refactor-sme/"
lang: "en"
alternate: "https://www.noze.it/insights/aider-branch-refactor-pmi/"
published: "2024-07-10"
author: "Stefano Noferi"
keywords: "Open Source, AI, Tutorial, Agentic, Aider, DeepSeek, OpenRouter, SME"
---

# Aider with DeepSeek Coder via OpenRouter: branch refactor

Aider configured with DeepSeek Coder V2 via OpenRouter for a targeted refactor on an isolated branch. Auto-commit, repo map, file-scope constraints, regression tests before merge.

10 July 2024

## Preliminary notes

Content provided **“as-is”**. Before using on real code:

- Work on a **dedicated branch**, never directly on `main`.
- **Back up** (or push to remote) the starting branch before starting the session.
- **Never place secrets** in prompts, config files or generated commit messages.
- If you use a cloud provider (OpenRouter, Anthropic, OpenAI), the content of open files is transmitted. For NDA-bound code, prefer a local endpoint (Ollama) or a verified contractual agreement with the provider.
- The project’s **test suite** must be runnable and ideally reliable: it is the main defence against “plausible” but incorrect refactors.

## Aider + DeepSeek Coder: why

**Aider** ([aider.chat](https://aider.chat)) — the AI pair-programming Python CLI by **Paul Gauthier**, first PyPI release (v0.10.0) on **22 July 2023**, Apache 2.0 — is among the few tools that turn every model interaction into a **git commit**. That choice has a direct practical consequence: the git history of an Aider session is a full audit trail of the agent’s work, and `git revert` is enough to back out any single step.

In mid-2024, **DeepSeek** releases **DeepSeek Coder V2**: a model focused on code editing, competitive on the same Aider Leaderboard refactor benchmarks at a significantly lower cost than generalist frontier models. The _Aider + DeepSeek Coder V2 via OpenRouter_ combination is a useful tradeoff for SMEs who want AI in their refactor workflow without paying frontier-model cost on every iteration.

## Use case: extracting a validation module from a Flask app

A medium-complexity Flask app has input-validation logic scattered across three blueprints (`orders`, `invoices`, `customers`). We want to extract it into a `validators/` module with tested functions, without changing observable behaviour.

### 1. Dedicated branch and green test suite

```
cd ~/projects/appX
git checkout -b refactor/validators
pytest                     # must be green before starting
git log --oneline -5       # anchor for revert in case of disaster
```

If tests fail before you start, stop: Aider is not meant to fix broken tests, and refactoring untested code is a blind jump.

### 2. Install Aider

```
python3 -m venv ~/.venvs/aider
source ~/.venvs/aider/bin/activate
pip install aider-chat
aider --version
```

### 3. OpenRouter key in env

OpenRouter ([openrouter.ai](https://openrouter.ai)) is a router to many models through one API. The key is read from the environment; **do not commit it**.

```
read -rs OPENROUTER_API_KEY && export OPENROUTER_API_KEY
# Variant with key in $HOME/.config/ (only on non-shared machines):
#   echo "OPENROUTER_API_KEY=..." > ~/.config/aider.env
#   chmod 600 ~/.config/aider.env
```

### 4. Start with DeepSeek Coder via OpenRouter

```
aider \
  --model openrouter/deepseek/deepseek-coder-v2 \
  --auto-commits \
  --no-stream \
  src/blueprints/orders.py \
  src/blueprints/invoices.py \
  src/blueprints/customers.py
```

Notes:

- Only relevant files are passed to the agent: it caps context and blast radius.
- `--auto-commits` creates a commit per accepted change. Messages are generated by Aider; review them and rewrite when needed to match your conventions.
- `--no-stream` makes output more readable on shared or recorded terminals.

### 5. Refactor prompt

In the Aider REPL:

_“Extract all input-validation functions (the `@validate_*` decorators and helpers) from the three blueprints into a `src/validators/__init__.py` module with pure functions. Blueprints should keep using them via import. Do not change the error messages returned. Add tests in `tests/test_validators.py`.”_

Aider proposes multiple changes (it may create the module, update the blueprints, add tests). Each approved change becomes a commit with a visible diff. For risky steps, explicitly ask for **the diff only, without applying**:

_“Before writing anything, show me the proposed diffs. Do not apply.”_

### 6. Continuous verification with tests

After each commit, run:

```
pytest tests/
```

If a test fails, the recommended order is:

1. `git log --oneline` → last agent commit.
2. Read the diff: `git show HEAD`.
3. Revert or targeted fix: `git revert HEAD` (cleanup) or a manual fix in a follow-up commit.

### 7. Merge and cleanup

When the refactor is complete:

```
pytest                         # green
git log --oneline main..HEAD   # list of agent commits, to review
git rebase -i main             # optional: squash or rewrite messages
git checkout main
git merge --no-ff refactor/validators
```

Many “minimal” agent commits are normal. Interactive rebase squash or `--squash` merge are both legitimate options: pick according to your history policy.

## Limits and caveats

- **The model can silently break behaviour not covered by tests**: if a function has no test for a side effect (log line, metric), the agent can change it unknowingly. Test coverage is the practical boundary of safe refactoring.
- **The repo map is not magic**: Aider builds a synthetic repo representation via tree-sitter. On highly dynamic code (Python metaprogramming, runtime dispatch) the agent may ignore non-static dependencies. Always manually check non-obvious impacts.
- **Auto-commits vs review**: auto-commit is a convenience, not permission to trust. A committed change is not certified correct: PR review is still required.
- **Token cost with frontier models**: switching to a frontier model for complex tasks, a single refactor session can cost as much as an hour of work in tokens. Monitor spend (OpenRouter exposes dashboards for credit and usage).

**Link**: [aider.chat](https://aider.chat) — [openrouter.ai](https://openrouter.ai) — [github.com/paul-gauthier/aider](https://github.com/paul-gauthier/aider)

---

[**Stefano Noferi**](https://www.noze.it/en/authors/stefano-noferi/), Founder and CEO/CTO of noze\
Tech Entrepreneur · AI Governance & Security Architect
