Aider-AI aider 完整教學

對應 gh-save:inbox/2026-05-22-github-Aider-AI-aider.md 來源 repo:https://github.com/Aider-AI/aider (45.1k stars / Apache-2.0) 版本基準:v0.86.0 (2025-08-09) + main HEAD 6435cb8 (2026-05-16)


1. 專案定位與適用情境

Aider 是 Paul Gauthier 主導的 terminal-based AI pair programming CLI (命令列 AI 結對程式設計工具),2023-05 開源,到 2026-05 為止 45.1k stars,PyPI 累計下載 6.8M 次。它的角色不是 IDE 外掛、也不是聊天視窗 — 而是「跑在 terminal 裡、看得到你整個 codebase、會直接編輯磁碟檔案並 auto-commit」的 LLM 操作介面。

最適合的場景:

  • 在已存在的 git repo 裡做多檔同步修改(例如重構、改 API、加 feature flag)
  • 想用**任何 LLM (large language model; 大型語言模型)**寫程式,而不被 IDE 廠商鎖在 Cursor / Windsurf 生態
  • 需要 LLM 看到整個 codebase 的結構 — Aider 的 repo map (tree-sitter-based; 程式碼結構圖) 是業界最成熟的 context engineering 範本
  • 跑「reasoning model 規劃 + cheap model 執行」的 architect mode (兩階段推理-執行模式)
  • 想把 LLM 操作整合進 shell pipeline(aider --message "..." 可單發、可 batch)

不適合:

  • 完全新手、沒用過 git — Aider 的核心心智模型是「LLM 直接 commit 進你的 repo」
  • 想要 IDE-style autocomplete / inline ghost text — 那是 Cursor / Copilot 的領域
  • 對「LLM 改檔再 auto-commit」感到不安 — 雖然 /undo 隨時可退,但需要心理建設

2. 安裝與快速啟動

2.1 推薦安裝方式(隔離環境)

官方推薦 aider-install,會自動建立隔離的 venv:

1python -m pip install aider-install
2aider-install

也可以用 uv (Astral 的 Python 套件管理器;本知識庫預設工具):

1uv tool install aider-chat

或 pipx:

1pipx install aider-chat

2.2 第一次啟動

 1cd /to/your/project        # 必須是 git repo(或讓 aider 幫你 git init)
 2
 3# 用 Claude Sonnet
 4aider --model sonnet --api-key anthropic=sk-ant-...
 5
 6# 用 DeepSeek(價格殺手)
 7aider --model deepseek --api-key deepseek=sk-...
 8
 9# 用 OpenAI o3-mini
10aider --model o3-mini --api-key openai=sk-...
11
12# 完全沒 API key?走 OpenRouter OAuth(PKCE 流程,瀏覽器登入)
13aider

最後一種會觸發 aider/onboarding.py 的 OpenRouter PKCE (Proof Key for Code Exchange; 公鑰交換) OAuth flow — 瀏覽器登入後自動把 key 寫進 ~/.aider/.env,新手 onboarding 體驗超滑順。

2.3 API key 安全載入順序

Aider 依序檢查(後者覆蓋前者):

  1. 系統環境變數(ANTHROPIC_API_KEY / OPENAI_API_KEY / DEEPSEEK_API_KEY / GEMINI_API_KEY / OPENROUTER_API_KEY
  2. ~/.aider/.env(user-level)
  3. <git_root>/.env(project-level,注意要加入 .gitignore
  4. CLI 參數 --api-key(會留在 shell history,不建議

3. 系統架構與資料流

Aider 的核心是 Coder 抽象 — 16 種 Coder 對應 16 種 prompt + edit format。下圖呈現一次「/code 請求」的完整流程:


flowchart TB
    User["使用者輸入 /code 指令"] --> IO["aider/io.py REPL"]
    IO --> Commands["aider/commands.py 路由"]
    Commands --> Coder["aider/coders/editblock_coder.py"]
    Coder --> RepoMap["aider/repomap.py tree-sitter 抽 symbols"]
    RepoMap -.->|"PageRank 排序"| Context["相關函數簽章 context"]
    Context --> Prompt["base_prompts + edit format 範例"]
    Prompt --> SendChat["aider/sendchat.py + retry"]
    SendChat --> LiteLLM["aider/llm.py LiteLLM wrapper"]
    LiteLLM --> LLMAPI["LLM Provider API"]
    LLMAPI -->|"streaming response"| Parser["aider/coders 解析 search/replace 區塊"]
    Parser --> EditDisk["直接寫入磁碟"]
    EditDisk --> GitRepo["aider/repo.py auto-commit"]
    GitRepo --> Diff["顯示 diff 給使用者"]
    Diff -.->|"使用者 /undo"| GitRepo

Architect mode 的雙模型流程:


sequenceDiagram
    participant U as 使用者
    participant A as architect_coder
    participant R as Reasoning Model
(o1 / Sonnet) participant E as Editor Model
(gpt-4o / Haiku) participant G as GitRepo U->>A: /architect 重構 X 模組 A->>R: 純自然語言「規劃」prompt R-->>A: 步驟清單 + 設計決策 A->>E: 帶 plan 的 edit format prompt E-->>A: search/replace 區塊 A->>G: 套用 + auto-commit G-->>U: 顯示 diff

Repo map 的 token 預算機制:


flowchart LR
    Files["repo 內所有檔案"] --> TS["tree-sitter parse"]
    TS --> Symbols["抽出函數 / class 簽章"]
    Symbols --> Graph["建定義 / 引用圖"]
    Graph --> PR["PageRank 排序"]
    PR --> Budget["依 model context 預算截斷"]
    Budget --> Map["最終 repo map(~2k tokens)"]


4. 核心功能逐項說明

4.1 16 種 Coder(edit format)

Coder適用模型機制
editblock預設 / Claude / GPT-4o<<<<<<< SEARCH ... ======= ... >>>>>>> REPLACE 區塊
editblock_fencedDeepSeek / 小模型同上但用 fenced code block 包起來
editblock_funcfunction calling 模型透過 OpenAI tool calling 結構化呼叫
udiffOpenAI o1 / o3unified diff (Unix diff -u; 統一差異格式)
diff_fencedGeminifenced unified diff
whole弱小模型 / 短檔重寫整個檔案
patchGPT-4.1OpenAI 新 patch format
architectreasoning + editor 兩模型拆解規劃與執行
ask任何純問答,不改檔
context任何純讀檔,建立 context
help任何/help 對話
editor_editblock / editor_whole / editor_diff_fencedarchitect 的 editor 端同名 + architect 流程
editblock_fenced_funcfunction calling 變體結構化 search/replace

實務選用: 多數情況 editblock 已經夠;長檔案大改用 udiff;新 codebase 第一次接觸用 architect(讓 reasoning model 先規劃)。

4.2 50+ 個斜線指令

最常用的 12 個:

 1/add <path>          將檔案加入 chat context(LLM 才能修改)
 2/drop <path>         移出 context
 3/read-only <path>    加入但不允許修改(適合 reference 程式碼)
 4/code <prompt>       一般編輯
 5/architect <prompt>  雙模型規劃-執行
 6/ask <prompt>        純問答不改檔
 7/context <prompt>    純讀檔建立上下文
 8/run <cmd>           執行 shell command(user-initiated,shell=True)
 9/test [cmd]          跑 test,結果丟回 LLM 修
10/lint                跑 linter,把錯誤丟回 LLM 修
11/commit              手動 commit dirty changes
12/undo                退回上一個 aider commit
13/diff                顯示上一輪 diff
14/tokens              顯示當前 context 用量
15/web <url>           抓網頁丟給 LLM
16/paste               貼剪貼簿(圖 / 文)
17/voice               語音輸入(Whisper)
18/model <name>        切模型
19/clear               清對話歷史(保留檔案 context)
20/reset               全部清掉

4.3 Repo map:tree-sitter + PageRank

aider/repomap.py 是 Aider 最值得抄的設計。流程:

  1. tree-sitter (語法樹解析器) 對所有檔案抽出 top-level 符號(函數、class、method 簽章)
  2. 建定義 → 引用的有向圖
  3. PageRank 排序,找出「被引用最多」的核心符號
  4. 依當前 model 的 context 預算(如 Sonnet 200k token 預留 2-8k 給 map)截斷

支援 80+ 種語言(看 aider/queries/),最近 2026-05 才剛合併 bash tree-sitter tags 支援(PR #5132)。

4.4 Git 整合

  • 預設 auto-commit:每次 LLM 編輯後 → 自動 git add + git commit with aider: <message>
  • --no-auto-commits:關掉 auto-commit
  • --attribute-co-authored-by:加 Co-authored-by: aider (model_name) trailer
  • --dirty-commits:開始 session 前先 commit working tree dirty changes(隔離 aider 編輯)
  • /undo:等於 git reset --hard HEAD~1,只能退最近一次 aider commit

4.5 LiteLLM 抽象層

aider/llm.py 是 LiteLLM (BerriAI/litellm; 統一 LLM API 介面) 的 thin wrapper — Aider 自己不維護 provider-specific 程式碼。新模型出來只需要在 aider/resources/model-settings.yml 加一行:

1- name: anthropic/claude-opus-4-7
2  edit_format: editblock
3  use_repo_map: true
4  weak_model_name: anthropic/claude-haiku-4
5  extra_params:
6    extra_headers:
7      anthropic-beta: "..."

這就是為什麼 Claude Opus 4.7 / GPT-5.5 / Grok-4 出來後 7 天內就進主線。


5. 設定檔與環境變數

5.1 三層設定優先序

由弱到強:

  1. ~/.aider.conf.yml(user-level)
  2. <git_root>/.aider.conf.yml(project-level,建議 commit 進 repo)
  3. CLI 參數

5.2 常用設定範例

.aider.conf.yml

 1model: sonnet
 2weak-model: haiku
 3editor-model: gpt-4o
 4edit-format: editblock
 5auto-commits: true
 6attribute-author: false
 7attribute-committer: false
 8attribute-co-authored-by: true
 9read: [README.md, CLAUDE.md, docs/architecture.md]
10test-cmd: pytest -x
11lint-cmd: ruff check .

5.3 環境變數

1ANTHROPIC_API_KEY=...
2OPENAI_API_KEY=...
3DEEPSEEK_API_KEY=...
4GEMINI_API_KEY=...
5OPENROUTER_API_KEY=...
6
7AIDER_MODEL=sonnet              # 等同 --model
8AIDER_AUTO_COMMITS=false        # 等同 --no-auto-commits
9AIDER_ANALYTICS=false           # 關 telemetry

6. 資安掃描

整體評等:🟡 中度風險(acceptable for trusted environments)

風險點等級說明
aider/run_cmd.py:67 shell=True + Popen🟡 中處理 /run 指令的使用者輸入;使用者主動觸發,非 LLM 注入路徑。但若把 aider 包成 daemon 對外開放,等同 RCE (Remote Code Execution; 遠端執行)。
aider/editor.py:134 subprocess.call(..., shell=True)🟡 中啟動 $EDITOR;命令來自環境變數,本地使用者可控。
aider/io.py:1093 notifications_command shell=True🟡 中使用者設定的通知指令;信任 user-config。
aider/commands.py:980 /git 指令 shell=True🟡 中/run,user-initiated。
API key 寫入 ~/.aider/.env(onboarding.py:367)🟡 中OAuth 完成後寫檔,權限預設 600;若 repo 內 .env 未進 .gitignore 會洩漏 — Aider 啟動時會檢查並提醒。
aider/scrape.py 抓任意 URL🟡 中/web 指令;LLM 可能被 prompt-injection(看到惡意網頁要它 exfiltrate API key)。建議 /web 後別緊接 /code 改敏感檔。
Telemetry (analytics.py)🟢 低預設開啟匿名統計,可 --analytics-disable 關閉;不傳檔案內容。
linter.py 用 subprocess 跑 linter🟢 低不用 shell=True,arg list 模式,安全。
沒有 eval( / exec( 在 user input 路徑🟢 低已掃過全部 aider/*.py,無危險動態執行。

機密邊界提醒:

  • 不要在含機密的 repo 裡跑沒設定 --read-only 的 aider — LLM 看得到 /add 進來的所有檔案
  • 不要讓 aider 看到 .env / secrets/ — 加進 .aiderignore(與 .gitignore 同語法)

最低設定建議:

1# project-level .aiderignore
2.env
3.env.*
4secrets/
5*.pem
6*.key
7docs/superpowers/specs/*meeting-intel*

7. 整合到本知識庫的可能性

Aider 與本知識庫 15 個 Layer 的對接點:

Layer整合方式
Layer 12 gh-tutorial-qd可參考 aider 的 repo map 策略,把 tutorial 寫得更貼近實際符號結構
Layer 4 graphify互補:graphify 用 LLM 抽 ontology,aider repo map 用 tree-sitter + PageRank — 兩者結合是「結構 + 語意」雙重視圖
Layer 6 gitnexus概念高度重疊(都是 symbol graph),可比較兩者實作
Layer 14 meeting-intel可用 aider /web 抓會議邀請內容;但戰術討論文件不能餵給 aider
Layer 15 paper-tutorial互補:paper-tutorial 是「N 篇 paper → 教學 HTML」,aider 是「對 codebase 直接編輯」
  1. aider --read aider.conf.yml --read CLAUDE.md 把規範鎖進 read-only context
  2. --test-cmd "pytest -x tests/unit" 自動跑單元測試
  3. --lint-cmd "ruff check src/" 自動 lint
  4. architect mode 下用 Claude Opus 4.7 規劃 + Haiku 執行(成本對半砍)

8. 與類似專案比較

專案定位開源LLM-agnostic直接編輯磁碟Repo map
Aiderterminal CLI✅ Apache-2.0✅ LiteLLM✅ + auto-commit✅ tree-sitter + PageRank
Claude Codeterminal CLI❌ 閉源❌ Anthropic only
CursorIDE fork (VSCode)❌ 閉源部分(自家 + OpenAI / Claude)✅ inline
Continue.devIDE extension✅ Apache-2.0✅ via IDE部分
ClineVSCode extension✅ Apache-2.0部分
Codex (OpenAI)CLI / agent❌ 閉源❌ OpenAI only部分

Aider 的相對優勢: terminal-native(無需 IDE)+ 真正 LLM-agnostic + 業界最成熟 repo map + Apache-2.0。 相對劣勢: 沒有 inline ghost text,沒有 IDE 整合,UX 對非 CLI-native 使用者較陡。


9. 常見坑與除錯指南

9.1 LLM 不 follow edit format

症狀: 回應內容沒有 <<<<<<< SEARCH 區塊,aider 印 ❌ The LLM did not conform to the edit format. 解:--edit-format whole(弱小模型)或 --edit-format udiff(o1);或加 --edit-format-examples 5 增強 few-shot。

9.2 Auto-commit 把錯誤 commit 進主線

症狀: LLM 改錯但已經 git commit 解: /undo 退一步;或事先 git checkout -b aider/feature-x 在 feature branch 跑。 預防: --no-auto-commits + 手動 /commit,或設 --dirty-commits 隔離。

9.3 Context 爆掉(Context too long)

症狀: Sonnet 上限 200k 還是塞爆 解: /drop 不需要的檔案;用 /tokens 看哪些檔最大;用 --map-tokens 4096 增大 repo map 預算反而能少加實檔。

9.4 OpenRouter 429 / 5xx

症狀: OpenrouterException - 'choices'(issue #3550,52 留言) 解: 換 provider(--model deepseek/deepseek-chat 直連 DeepSeek);或 --max-tokens 降低;或設 --retry-on-error

9.5 tree-sitter parse 失敗

症狀: 啟動時 warning「Could not load tree-sitter for X」 解: 多半是新語言沒進 aider/queries/ — 提 PR 加 tag file(最近 bash 就是這樣加進來的)。


10. 進階:擴充與貢獻

10.1 新增模型

編輯 aider/resources/model-settings.yml

1- name: yournewprovider/yourmodel-v1
2  edit_format: editblock
3  weak_model_name: yournewprovider/yourmodel-mini
4  use_repo_map: true
5  use_temperature: true
6  extra_params:
7    max_tokens: 8192

然後 aider --model yournewprovider/yourmodel-v1 --verbose 測試。

10.2 新增 tree-sitter 語言

  1. tree-sitter-<lang> package
  2. aider/queries/tree-sitter-language-pack/<lang>-tags.scm 加 query(定義 def / ref / docstring)
  3. pytest tests/basic/test_repomap.py
  4. 提 PR — 參考 #5132(bash)

10.3 新增 edit format

繼承 aider/coders/base_coder.py

1class MyCustomCoder(Coder):
2    edit_format = "mycustom"
3    gpt_prompts = MyCustomPrompts()
4    def get_edits(self): ...
5    def apply_edits(self, edits): ...

加進 aider/coders/__init__.py__all__

10.4 開發環境

1git clone https://github.com/Aider-AI/aider.git
2cd aider
3uv venv && source .venv/bin/activate
4uv pip install -e ".[dev]"
5pre-commit install
6pytest tests/basic

11. 學習路徑建議

第 1 小時 — 跑起來:

  1. pip install aider-install && aider-install
  2. cd <你的 side project>
  3. aider --model sonnet → 試 /add README.md/ask 這個 repo 在做什麼?
  4. /code 在 README 加一段 install 指令 → 看 auto-commit
  5. /undo

第 2-4 小時 — 進入工作流:

  1. 在實際 feature branch 用 architect mode:aider --architect --model o1 --editor-model gpt-4o
  2. 設定 .aider.conf.yml + .aiderignore
  3. test-cmd / lint-cmd → 看 LLM 自動修錯
  4. /web <doc-url> 把官方文件當 context

第 5+ 小時 — 深入:

  1. aider/coders/base_coder.py(~2000 行,是 prompt loop 經典)
  2. aider/repomap.py(PageRank 實作)
  3. aider/onboarding.py(PKCE OAuth 完整實作,700 行可學)
  4. benchmark/ 自己出題評估不同 model + edit format 組合

推薦延伸閱讀:

  • Aider’s leaderboards — 每個模型在 edit / refactor / polyglot benchmark 的真實表現
  • HISTORY.md — 76k 字完整 changelog,看一個工具如何兩年內 ship 80+ 個 release
  • Paul Gauthier 在 X / blog 上的 prompt engineering 短文

附錄:對本知識庫使用者的速查表

 1# 把整個 repo 給 aider 規劃重構
 2aider --architect --model sonnet --editor-model haiku --read CLAUDE.md
 3
 4# 只看不改(codebase 探勘)
 5aider --model sonnet
 6> /ask 解釋 scripts/quarkdown.sh 的編譯流程
 7
 8# 隔離 working tree 後再讓 aider 開工
 9git stash && aider --dirty-commits --model deepseek
10
11# 設 `.aiderignore` 保護機密