# https://github.com/Aider-AI/aider 项目说明书

生成时间：2026-05-16 09:51:38 UTC

## 目录

- [Introduction to Aider](#page-introduction)
- [Installation and Setup](#page-installation)
- [Quick Start Guide](#page-quickstart)
- [Core Architecture](#page-core-architecture)
- [Main Application Flow](#page-main-flow)
- [Model Integration System](#page-model-integration)
- [Chat Communication Protocol](#page-chat-communication)
- [Code Editing Strategies](#page-coder-strategies)
- [Edit Format Handling](#page-edit-formats)
- [Git Integration](#page-git-integration)

<a id='page-introduction'></a>

## Introduction to Aider

### 相关页面

相关主题：[Installation and Setup](#page-installation), [Quick Start Guide](#page-quickstart)

<details>
<summary>Relevant Source Files</summary>

以下源码文件用于生成本页说明：

- [aider/README.md](https://github.com/Aider-AI/aider/blob/main/README.md)
- [aider/website/index.html](https://github.com/Aider-AI/aider/blob/main/aider/website/index.html)
- [aider/website/_includes/get-started.md](https://github.com/Aider-AI/aider/blob/main/aider/website/_includes/get-started.md)
- [aider/website/examples/chat-transcript-css.md](https://github.com/Aider-AI/aider/blob/main/aider/website/examples/chat-transcript-css.md)
- [aider/website/examples/complex-change.md](https://github.com/Aider-AI/aider/blob/main/aider/website/examples/complex-change.md)
- [CONTRIBUTING.md](https://github.com/Aider-AI/aider/blob/main/CONTRIBUTING.md)
</details>

# Introduction to Aider

Aider is an AI pair programming tool that runs directly in your terminal. It enables developers to collaborate with Large Language Models (LLMs) to create new projects, modify existing codebases, and manage software development tasks through natural language commands.

## Overview

Aider positions itself as an AI pair programmer, bridging the gap between human developers and artificial intelligence. Unlike traditional coding assistants that operate within IDEs, Aider operates through the command line, making it accessible and scriptable. The tool is designed to work seamlessly with Git, automatically committing changes with descriptive messages.

| Attribute | Value |
|-----------|-------|
| Project Type | AI-assisted code editing tool |
| Interface | Command-line terminal |
| Primary Language | Python |
| License | [MIT](https://github.com/Aider-AI/aider) |
| Repository | [github.com/Aider-AI/aider](https://github.com/Aider-AI/aider) |

资料来源：[aider/website/index.html](https://github.com/Aider-AI/aider/blob/main/aider/website/index.html)

## Core Features

Aider provides a comprehensive set of features designed to streamline the development workflow.

### Cloud and Local LLM Support

Aider connects to various LLM providers, with optimal support for:

| Provider | Recommended Models |
|----------|-------------------|
| Anthropic | Claude 3.7 Sonnet |
| DeepSeek | R1, Chat V3 |
| OpenAI | o1, o3-mini, GPT-4o |
| Local Models | Ollama, LM Studio compatible APIs |

The tool works best with LLM APIs but also supports interaction via web chat interfaces through copy/paste workflows.

资料来源：[aider/website/index.html](https://github.com/Aider-AI/aider/blob/main/aider/website/index.html#L68-L85)

### Multi-Language Support

Aider supports over 100 programming languages including:

- Python, JavaScript, TypeScript
- Rust, Go, Ruby
- C++, PHP
- HTML, CSS
- And many more

资料来源：[aider/website/index.html](https://github.com/Aider-AI/aider/blob/main/aider/website/index.html#L95-L105)

### Git Integration

Aider automatically commits changes with sensible commit messages after each AI response. This integration allows developers to:

- Track all AI-assisted changes
- Use familiar Git tools to diff, manage, and undo changes
- Maintain a complete history of modifications

```bash
# Example workflow
aider --model sonnet --api-key anthropic=<key>
# Make changes via conversation
# Aider auto-commits with descriptive messages
```

资料来源：[aider/website/index.html](https://github.com/Aider-AI/aider/blob/main/aider/website/index.html#L50-L60)

### Codebase Mapping

Aider creates a comprehensive map of your entire codebase, enabling it to:

- Understand project structure and dependencies
- Make contextually appropriate changes in larger projects
- Navigate and modify multiple files intelligently

资料来源：[aider/website/index.html](https://github.com/Aider-AI/aider/blob/main/aider/website/index.html#L85-L95)

## System Architecture

The architecture of Aider consists of several interconnected components that work together to provide the AI pair programming experience.

```mermaid
graph TD
    A[User Terminal] --> B[Aider CLI]
    B --> C[InputOutput Module]
    B --> D[LLM Connector]
    D --> E[External LLM APIs]
    B --> F[Git Manager]
    B --> G[Codebase Mapper]
    G --> H[Repository Files]
    F --> H
    C --> I[prompt_toolkit UI]
    
    style A fill:#e1f5fe
    style E fill:#fff3e0
    style H fill:#e8f5e9
```

### Component Overview

| Component | Purpose |
|-----------|---------|
| CLI Entry Point | Parses arguments and initiates session |
| InputOutput | Handles terminal I/O and UI rendering |
| LLM Connector | Manages communication with LLM providers |
| Git Manager | Handles version control operations |
| Codebase Mapper | Analyzes and indexes project structure |

资料来源：[aider/website/examples/complex-change.md](https://github.com/Aider-AI/aider/blob/main/aider/website/examples/complex-change.md)

## Installation

Aider requires Python 3.9 through 3.12 and can be installed using pip or the official installer.

### Quick Installation

```bash
python -m pip install aider-install
aider-install
```

### Direct pip Installation

```bash
pip install aider-chat
```

### Manual Installation from Source

```bash
git clone https://github.com/Aider-AI/aider.git
cd aider
pip install -e .
```

资料来源：[aider/website/_includes/get-started.md](https://github.com/Aider-AI/aider/blob/main/aider/website/_includes/get-started.md)

## Getting Started

### Basic Usage

1. Navigate to your project directory:

```bash
cd /to/your/project
```

2. Launch Aider with your preferred model:

```bash
# DeepSeek
aider --model deepseek --api-key deepseek=<key>

# Claude 3.7 Sonnet
aider --model sonnet --api-key anthropic=<key>

# OpenAI o3-mini
aider --model o3-mini --api-key openai=<key>
```

3. Start asking for changes:

```bash
# Create a new feature
/add main.py
Please refactor the authenticate_user function to use JWT tokens

# Modify existing code
/add utils.py
Can you add input validation to the parse_config function?
```

资料来源：[README.md](https://github.com/Aider-AI/aider/blob/main/README.md#L45-L75)

### Interactive Workflow

```mermaid
graph LR
    A[Start Aider] --> B{Add files}
    B --> C[Specify task]
    C --> D[AI analyzes code]
    D --> E[Proposes changes]
    E --> F{User approves?}
    F -->|Yes| G[Apply changes]
    F -->|No| H[Provide feedback]
    H --> C
    G --> I[Auto-commit]
    I --> J[Continue or exit]
    J --> C
```

资料来源：[aider/website/examples/update-docs.md](https://github.com/Aider-AI/aider/blob/main/aider/website/examples/update-docs.md)

## Configuration

Aider supports configuration through environment variables and command-line arguments.

| Configuration | Environment Variable | Default | Description |
|--------------|---------------------|---------|-------------|
| Model | `AIDER_MODEL` | gpt-4 | LLM model to use |
| API Key | Provider-specific | None | Authentication for LLM |
| Pretty Output | `AIDER_PRETTY` | 1 (enabled) | Colorized terminal output |
| Auto Commits | `AIDER_AUTO_COMMITS` | 1 (enabled) | Automatic Git commits |
| Show Diffs | `AIDER_SHOW_DIFFS` | 0 (disabled) | Display diffs on commit |
| History File | `AIDER_HISTORY_FILE` | .aider.history | Chat history storage |

资料来源：[aider/website/examples/update-docs.md](https://github.com/Aider-AI/aider/blob/main/aider/website/examples/update-docs.md#L15-L30)

## Advanced Features

### Linting and Testing

Aider can automatically lint and test code after making changes. It integrates with your existing linters and test suites to ensure code quality.

```bash
# Enable auto-linting
aider --lint

# Enable auto-testing
aider --test

# Both together
aider --lint --test
```

资料来源：[aider/website/index.html](https://github.com/Aider-AI/aider/blob/main/aider/website/index.html#L115-L125)

### Voice-to-Code

Speak with Aider about your code using voice input. Request new features, test cases, or bug fixes vocally.

```bash
aider --voice
```

资料来源：[aider/website/index.html](https://github.com/Aider-AI/aider/blob/main/aider/website/index.html#L107-L115)

### Images and Web Pages

Add images and web page references to provide visual context for your requests.

```bash
# Add screenshot reference
/add screenshot.png

# Add documentation URL
/add https://api.example.com/docs
```

资料来源：[aider/website/index.html](https://github.com/Aider-AI/aider/blob/main/aider/website/index.html#L115-L125)

### Web Chat Integration

For LLMs without API access, Aider supports copy/paste workflows with web chat interfaces. The tool streamlines transferring code context and edits between your terminal and browser.

资料来源：[aider/website/index.html](https://github.com/Aider-AI/aider/blob/main/aider/website/index.html#L125-L135)

## Example Workflows

### Editing Existing Code

```bash
$ aider ./README.md aider/main.py
Added README.md to the chat
Added aider/main.py to the chat

#### the cmd line args in main() have been updated. update the readme to accurately describe them.
```

Aider will analyze the code changes and automatically update documentation to match.

资料来源：[aider/website/examples/update-docs.md](https://github.com/Aider-AI/aider/blob/main/aider/website/examples/update-docs.md)

### Styling and UI Changes

```bash
#### add some space inside the border of the blockquote

```html
index.html
<<<<<<< ORIGINAL
    <style>
      .main-content blockquote {
        border: 0.1rem solid #159957;
        border-radius: 0.5rem;
        background-color: #e0f2ef;
      }
=======
    <style>
      .main-content blockquote {
        border: 0.1rem solid #159957;
        border-radius: 0.5rem;
        background-color: #e0f2ef;
        padding: 1rem;
      }
>>>>>>> UPDATED
```

> Applied edit to index.html
> Commit dd7dcb6 aider: Added padding inside the border of the blockquote.

资料来源：[aider/website/examples/chat-transcript-css.md](https://github.com/Aider-AI/aider/blob/main/aider/website/examples/chat-transcript-css.md)

### Complex Refactoring

Aider can handle complex multi-file refactoring tasks:

```python
# Update InputOutput class
class InputOutput:
    def __init__(self, pretty, yes, input_history_file, chat_history_file, input=None, output=None):
        self.input = input
        self.output = output
```

Aider will identify all affected files and apply changes systematically, committing each step with descriptive messages.

资料来源：[aider/website/examples/complex-change.md](https://github.com/Aider-AI/aider/blob/main/aider/website/examples/complex-change.md)

## Development Guidelines

When contributing to Aider or using it for project development, follow these standards:

| Standard | Tool | Configuration |
|----------|------|---------------|
| Code Style | PEP 8 | Max line length: 100 |
| Import Sorting | isort | Configured per project |
| Code Formatting | Black | Default settings |
| Testing | pytest | `aider/tests/test_*.py` |

Aider does not use type hints in its codebase.

资料来源：[CONTRIBUTING.md](https://github.com/Aider-AI/aider/blob/main/CONTRIBUTING.md)

## Resources and Documentation

| Resource | URL |
|----------|-----|
| Official Website | https://aider.chat/ |
| Installation Guide | https://aider.chat/docs/install.html |
| Usage Documentation | https://aider.chat/docs/usage.html |
| LLM Configuration | https://aider.chat/docs/llms.html |
| Configuration Options | https://aider.chat/docs/config.html |
| GitHub Repository | https://github.com/Aider-AI/aider |
| Discord Community | https://discord.gg/Y7X7bhMQFV |

## Summary

Aider transforms the terminal into an AI-powered development environment. By combining natural language processing with Git integration and codebase awareness, it enables developers to:

- Rapidly prototype and implement features
- Refactor existing code with confidence
- Maintain comprehensive change histories
- Work with multiple programming languages and LLM providers

The tool's emphasis on Git-based versioning and its ability to work across 100+ programming languages make it a versatile addition to any developer's toolkit.

---

<a id='page-installation'></a>

## Installation and Setup

### 相关页面

相关主题：[Introduction to Aider](#page-introduction)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [pyproject.toml](https://github.com/Aider-AI/aider/blob/main/pyproject.toml)
- [requirements.txt](https://github.com/Aider-AI/aider/blob/main/requirements.txt)
- [docker/Dockerfile](https://github.com/Aider-AI/aider/blob/main/docker/Dockerfile)
- [aider/website/docs/install.md](https://github.com/Aider-AI/aider/blob/main/aider/website/docs/install.md)
- [requirements/requirements-dev.txt](https://github.com/Aider-AI/aider/blob/main/requirements/requirements-dev.txt)
- [requirements/requirements-help.txt](https://github.com/Aider-AI/aider/blob/main/requirements/requirements-help.txt)
- [CONTRIBUTING.md](https://github.com/Aider-AI/aider/blob/main/CONTRIBUTING.md)
</details>

# Installation and Setup

## Overview

Aider is an AI pair programming tool that integrates with Large Language Models (LLMs) to help developers write, edit, and manage code directly from the terminal. The installation and setup process is designed to be straightforward, supporting multiple installation methods to accommodate different user preferences and system configurations.

The project supports Python versions 3.9, 3.10, 3.11, and 3.12, making it compatible with most modern Python environments. 资料来源：[CONTRIBUTING.md:1]()

## System Requirements

### Python Environment

| Requirement | Specification |
|-------------|---------------|
| Python Version | 3.9, 3.10, 3.11, 3.12 |
| Package Manager | pip, uv, or conda |
| Operating System | Linux, macOS, Windows (via WSL) |

### Core Dependencies

Aider's core dependencies include:

| Package | Purpose |
|---------|---------|
| aiohttp 3.13.3 | Async HTTP client/server |
| litellm | LLM interface abstraction |
| openai | OpenAI API integration |
| gitpython 3.1.46 | Git repository integration |
| prompt-toolkit 3.0.52 | Terminal UI components |
| fastapi 0.135.1 | REST API support |
| pytest 9.0.2 | Testing framework |

资料来源：[requirements.txt:1-50]()

## Installation Methods

### Method 1: pip Installation

The standard installation method uses pip:

```bash
pip install aider-aider
```

### Method 2: uv Package Manager

For faster dependency resolution, use uv:

```bash
uv pip install aider-aider
```

### Method 3: Docker Installation

Aider provides a Docker image for isolated execution. The Dockerfile sets up the complete environment:

```dockerfile
FROM python:3.12-slim
WORKDIR /app
COPY . .
RUN pip install --no-cache-dir -e .
CMD ["aider"]
```

资料来源：[docker/Dockerfile:1-5]()

### Method 4: Development Installation

For contributors setting up a development environment:

```bash
# Clone the repository
git clone https://github.com/Aider-AI/aider.git
cd aider

# Install dependencies
pip install -e .

# Install development dependencies
pip install -r requirements/requirements-dev.txt
```

资料来源：[CONTRIBUTING.md:1-30]()

## Dependency Groups

Aider uses modular dependency groups to support different feature sets:

### Core Dependencies (requirements.txt)

The main requirements file includes essential packages for basic functionality:

| Group | Key Packages |
|-------|--------------|
| LLM Integration | litellm, openai, anthropic, huggingface-hub |
| Git Operations | gitpython, gitdb |
| Terminal UI | prompt-toolkit, rich |
| HTTP/Async | aiohttp, httpx, anyio |
| Configuration | configargparse, diskcache |

资料来源：[requirements.txt:1-100]()

### Optional Dependency Groups

| Group | Purpose | Location |
|-------|---------|----------|
| requirements-help.in | Help system features | Rich documentation output |
| requirements-browser.in | Browser automation | Playwright for web testing |
| requirements-playwright.in | Playwright testing | E2E test automation |

资料来源：[requirements/requirements-help.txt:1-30](), [requirements/requirements-browser.txt:1-30](), [requirements/requirements-playwright.txt:1-20]()

### Development Dependencies

Development setup requires additional tooling:

```bash
# Install all development dependencies
pip install -r requirements/requirements-dev.txt
```

| Package | Purpose |
|---------|---------|
| pytest 9.0.2 | Test runner |
| pytest-cov 7.0.0 | Code coverage |
| pytest-env 1.6.0 | Environment variable management |
| black | Code formatting |
| isort | Import sorting |
| flake8 7.3.0 | Linting |
| pre-commit | Git hook management |
| uv 0.10.11 | Fast package resolver |

资料来源：[requirements/requirements-dev.txt:1-80]()

## Development Setup

### Pre-commit Hooks

The project uses pre-commit hooks to maintain code quality. Install them after cloning:

```bash
pip install pre-commit
pre-commit install
```

The hooks automatically run formatting checks (isort, Black) and linting (flake8) before each commit.

资料来源：[CONTRIBUTING.md:1-30]()

### Code Style Standards

| Standard | Configuration |
|----------|---------------|
| Style Guide | PEP 8 |
| Max Line Length | 100 characters |
| Import Sorting | isort |
| Code Formatting | Black |

### Running Tests

```bash
# Run all tests
pytest

# Run with coverage
pytest --cov=aider

# Run specific test file
pytest aider/tests/test_*.py
```

Test files are located in `aider/tests/` directory following the `test_*.py` naming convention.

资料来源：[CONTRIBUTING.md:1-30]()

## Installation Flow Diagram

```mermaid
graph TD
    A[Start Installation] --> B{Check Python Version}
    B -->|3.9-3.12| C[Choose Installation Method]
    B -->|Invalid| D[Show Error: Python 3.9+ required]
    
    C --> E[pip install]
    C --> F[uv pip install]
    C --> G[Docker]
    C --> H[Development install]
    
    E --> I[Install core dependencies]
    F --> I
    G --> J[Build Docker image]
    H --> K[Install with -e flag]
    H --> L[Install dev dependencies]
    
    I --> M[Installation Complete]
    J --> M
    K --> L
    L --> M
```

## Environment Configuration

### Environment Variables

| Variable | Default | Description |
|----------|---------|-------------|
| AIDER_AUTO_COMMITS | 1 | Enable auto commits |
| AIDER_SHOW_DIFFS | 0 | Show diffs on commit |
| AIDER_NORECORD | 0 | Disable command recording |

### Configuration Files

Aider supports configuration via:

1. `~/.aider.conf.yml` - User-level settings
2. `.aider.conf.yml` in project root - Project-level settings
3. Command-line arguments - Session-specific overrides

## Troubleshooting Installation Issues

### Common Issues

| Issue | Solution |
|-------|----------|
| Python version mismatch | Verify with `python --version`, use pyenv or virtualenv |
| Permission denied | Use `--user` flag or virtual environment |
| Missing git | Install git and ensure it's in PATH |
| SSL/TLS errors | Check corporate firewall or proxy settings |

### Verification

After installation, verify setup:

```bash
aider --version
aider --help
```

## Summary

Aider's installation and setup process supports multiple methods to accommodate various user preferences:

- **pip/uv**: Quick installation for end users
- **Docker**: Isolated environment without local Python conflicts
- **Development**: Full setup for contributors with testing and linting tools

The modular dependency system allows users to install only the features they need, keeping the base installation lightweight while providing optional support for advanced features like browser automation and help system enhancements.

资料来源：[CONTRIBUTING.md:1-30](), [requirements.txt:1-50](), [docker/Dockerfile:1-5]()

---

<a id='page-quickstart'></a>

## Quick Start Guide

### 相关页面

相关主题：[Introduction to Aider](#page-introduction)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [README.md](https://github.com/Aider-AI/aider/blob/main/README.md)
- [aider/website/index.html](https://github.com/Aider-AI/aider/blob/main/aider/website/index.html)
- [aider/website/_includes/get-started.md](https://github.com/Aider-AI/aider/blob/main/aider/website/_includes/get-started.md)
- [aider/website/examples/complex-change.md](https://github.com/Aider-AI/aider/blob/main/aider/website/examples/complex-change.md)
- [aider/website/examples/no-color.md](https://github.com/Aider-AI/aider/blob/main/aider/website/examples/no-color.md)
- [CONTRIBUTING.md](https://github.com/Aider-AI/aider/blob/main/CONTRIBUTING.md)
</details>

# Quick Start Guide

Aider is an AI pair programming tool that integrates Large Language Models (LLMs) directly into your terminal workflow. This guide provides the essential steps to install, configure, and begin using Aider for code development and modification.

## Installation

### Prerequisites

| Requirement | Details |
|-------------|---------|
| Python Version | 3.9, 3.10, 3.11, or 3.12 资料来源：[CONTRIBUTING.md:1]() |
| Package Manager | pip |
| LLM API Access | API key for your chosen provider |

### Quick Installation Methods

**Method 1: Automated Installer (Recommended)**

```bash
python -m pip install aider-install
aider-install
```

资料来源：[aider/website/index.html:1]()

**Method 2: Direct pip Installation**

```bash
pip install aider-chat
```

资料来源：[README.md:1]()

### Supported LLM Providers

Aider supports multiple LLM providers including:

| Provider | Model Examples |
|----------|---------------|
| OpenAI | o1, o3-mini, GPT-4o |
| Anthropic | Claude 3.7 Sonnet |
| DeepSeek | DeepSeek models |
| Local Models | Almost any LLM via API or web interface |

资料来源：[aider/website/index.html:1]()

## Initial Setup

### Step 1: Navigate to Your Project

Change directory into the codebase you want to work on:

```bash
cd /to/your/project
```

资料来源：[aider/website/_includes/get-started.md:1]()

### Step 2: Configure API Key

You can provide your API key via command line or environment variable:

```bash
# Via command line
aider --model sonnet --api-key anthropic=<your-key>

# Via environment variable
export ANTHROPIC_API_KEY=<your-key>
aider --model sonnet
```

资料来源：[aider/website/index.html:1]()

### Step 3: Launch Aider

Start a coding session with your preferred model:

```bash
# DeepSeek
aider --model deepseek --api-key deepseek=<key>

# Claude 3.7 Sonnet
aider --model sonnet --api-key anthropic=<key>

# o3-mini
aider --model o3-mini --api-key openai=<key>
```

资料来源：[aider/website/_includes/get-started.md:1]()

## Core Workflow

```mermaid
graph TD
    A[Launch Aider] --> B[Load Codebase]
    B --> C[Chat with LLM]
    C --> D[Review Changes]
    D --> E{Accept?}
    E -->|Yes| F[Auto-commit Changes]
    E -->|No| G[Continue Editing]
    F --> H[Git Integration]
    G --> C
    H --> I[Session Complete]
```

### Workflow Description

1. **Launch**: Start Aider from your project directory
2. **Load**: Aider automatically maps your codebase 资料来源：[aider/website/index.html:1]()
3. **Chat**: Describe changes in natural language
4. **Review**: Examine proposed modifications
5. **Commit**: Aider automatically commits with sensible messages

## Command Line Options

| Option | Description | Default |
|--------|-------------|---------|
| `--model` | LLM model to use | Required |
| `--api-key` | API key for the provider | Required |
| `--no-auto-commits` | Disable auto commit | Disabled |
| `--show-diffs` | Show diffs when committing | False |
| `--yes` | Auto-confirm all prompts | False |
| `--no-color` | Disable colored output | Auto-detect |

资料来源：[aider/website/examples/update-docs.md:1]()

## Input/Output Configuration

Aider uses the `InputOutput` class to handle terminal interaction. The class supports custom input/output streams for testing and special environments:

```python
def __init__(
    self,
    pretty=True,
    yes=False,
    input_history_file=None,
    chat_history_file=None,
    input=None,
    output=None,
    user_input_color="blue",
    tool_output_color=None,
    tool_error_color="red",
):
```

资料来源：[aider/website/examples/no-color.md:1]()

### Color Output Behavior

Aider respects the `NO_COLOR` environment variable. If set, Aider disables colored output automatically:

```bash
export NO_COLOR=1
aider --model sonnet
```

资料来源：[aider/website/examples/no-color.md:1]()

## Git Integration

Aider provides seamless Git integration:

```mermaid
graph LR
    A[Make Changes] --> B[Auto-Commit]
    B --> C[Sensible Commit Messages]
    C --> D[Use Standard Git Tools]
    D --> E[Diff, Undo, Manage]
```

Key features:
- Automatic commit creation with descriptive messages
- Full compatibility with standard Git workflows
- Easy diffing and undoing of AI changes 资料来源：[aider/website/index.html:1]()

## Interactive Session Example

A typical Aider session looks like:

```
$ aider --model sonnet
>>> Add a new function to calculate fibonacci numbers
```

Aider will:
1. Analyze your codebase
2. Propose the necessary changes
3. Show you the diff
4. Apply changes upon confirmation
5. Commit with a meaningful message

资料来源：[aider/website/examples/complex-change.md:1]()

## Next Steps

| Topic | Link |
|-------|------|
| Installation Guide | [/docs/install.html]() |
| Usage Guide | [/docs/usage.html]() |
| Configuration Options | [/docs/config.html]() |
| Connecting to LLMs | [/docs/llms.html]() |
| Troubleshooting | [/docs/troubleshooting.html]() |
| FAQ | [/docs/faq.html]() |

资料来源：[aider/website/index.html:1]()

---

<a id='page-core-architecture'></a>

## Core Architecture

### 相关页面

相关主题：[Main Application Flow](#page-main-flow), [Model Integration System](#page-model-integration)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [aider/main.py](https://github.com/Aider-AI/aider/blob/main/aider/main.py)
- [aider/io.py](https://github.com/Aider-AI/aider/blob/main/aider/io.py)
- [aider/coders/base_coder.py](https://github.com/Aider-AI/aider/blob/main/aider/coders/base_coder.py)
- [aider/repo.py](https://github.com/Aider-AI/aider/blob/main/aider/repo.py)
- [aider/coders/__init__.py](https://github.com/Aider-AI/aider/blob/main/aider/coders/__init__.py)
- [aider/getinput.py](https://github.com/Aider-AI/aider/blob/main/aider/getinput.py)
</details>

# Core Architecture

## Overview

Aider is an AI pair programming tool that integrates with Large Language Models (LLMs) to enable collaborative coding directly in the terminal. The core architecture is designed around a modular system that separates concerns between user interaction, repository management, code editing, and LLM communication.

The architecture follows a layered approach where the main entry point handles CLI parsing and orchestration, while specialized modules manage input/output operations, repository interactions, and code modification. This separation allows Aider to work with various LLM providers while maintaining a consistent interface for users.

## System Architecture Diagram

```mermaid
graph TD
    A[CLI Entry Point] --> B[InputOutput Manager]
    A --> C[Repository Manager]
    A --> D[Coder Engine]
    B --> E[prompt_toolkit]
    C --> F[Git Operations]
    D --> G[LLM Adapter]
    G --> H[Anthropic/OpenAI/Local Models]
    D --> I[File System Operations]
```

## Core Components

### Entry Point and CLI Handling

The `main()` function in `aider/main.py` serves as the primary entry point, responsible for parsing command-line arguments, initializing core components, and managing the main application loop. This function coordinates the interaction between the InputOutput manager, repository handler, and coder engine.

资料来源：[aider/main.py:1-100]()

The CLI argument parsing utilizes Python's `argparse` module to support various configuration options including model selection, API key specification, auto-commit behavior, and diff display settings. The main function accepts `input` and `output` keyword arguments, enabling programmatic usage and testability.

### InputOutput System

The InputOutput class in `aider/io.py` provides a unified interface for all user interaction, handling console output formatting, user confirmation prompts, and input collection. This class abstracts away the complexity of terminal handling and color output.

资料来源：[aider/io.py:1-80]()

The InputOutput system supports the following key features:

| Feature | Description | Configuration |
|---------|-------------|---------------|
| Pretty Output | Formatted console output with colors | `pretty` parameter |
| Auto-yes Mode | Skip confirmation prompts | `yes` parameter |
| Color Configuration | Customizable output colors | `user_input_color`, `tool_output_color`, `tool_error_color` |
| NO_COLOR Support | Respects environment variable | Automatic detection |
| History Management | Input and chat history files | `input_history_file`, `chat_history_file` |

#### Color Handling

The InputOutput class implements sophisticated color handling that respects the `NO_COLOR` environment variable. When `NO_COLOR` is set and non-empty, the system automatically disables colored output regardless of other configuration settings.

```python
no_color = os.environ.get("NO_COLOR")
if no_color is not None and no_color != "":
    pretty = False
```

资料来源：[aider/io.py:40-45]()

This design follows the NO_COLOR standard and ensures compatibility with terminals and build systems that do not support ANSI color codes.

### Repository Management

The repository module (`aider/repo.py`) handles all Git operations, providing Aider with the ability to track file changes, manage commits, and maintain a history of AI-assisted modifications. This integration is fundamental to Aider's workflow, enabling users to review, diff, and undo changes using familiar Git tools.

资料来源：[aider/repo.py:1-100]()

### Coder Engine Architecture

The coder system forms the core of Aider's code modification capabilities. The base coder class defines the interface and common functionality that all language-specific coders inherit. This abstraction allows Aider to work with different programming languages while maintaining consistent editing behavior.

资料来源：[aider/coders/base_coder.py:1-150]()

```mermaid
classDiagram
    class BaseCoder {
        +edit_file()
        +run()
        +commit()
        +check_git()
    }
    class CoderA {
        +run()
    }
    class CoderB {
        +run()
    }
    BaseCoder <|-- CoderA
    BaseCoder <|-- CoderB
```

The coder engine communicates with LLMs through adapters that normalize the interface across different providers. This design enables Aider to support multiple LLM backends including Anthropic Claude, OpenAI GPT models, DeepSeek, and local models.

## Data Flow

```mermaid
sequenceDiagram
    participant User
    participant IO as InputOutput
    participant Repo as Repository
    participant Coder as Coder Engine
    participant LLM as Language Model
    
    User->>IO: Submit request
    IO->>Coder: Forward message
    Coder->>Repo: Check git status
    Repo-->>Coder: Return status
    Coder->>LLM: Send context + request
    LLM-->>Coder: Return response
    Coder->>Repo: Apply changes
    Repo-->>Coder: Commit result
    Coder->>IO: Display result
    IO-->>User: Show output
```

## Configuration and Initialization

The initialization sequence follows a specific order to ensure all components are properly configured before use:

1. Parse CLI arguments and load configuration from environment variables
2. Initialize InputOutput with appropriate settings
3. Create repository manager and validate git status
4. Instantiate coder engine with LLM adapter
5. Begin interactive session

| Step | Component | Key Responsibilities |
|------|-----------|---------------------|
| 1 | ArgumentParser | CLI parsing, config loading |
| 2 | InputOutput | Console setup, color configuration |
| 3 | Repo | Git initialization, file tracking |
| 4 | Coder | LLM connection, edit management |
| 5 | Session | Main loop, user interaction |

## Environment Variable Configuration

Aider supports extensive configuration through environment variables, allowing customization of core behaviors:

| Variable | Default | Purpose |
|----------|---------|---------|
| `NO_COLOR` | None | Disable all color output |
| `AIDER_AUTO_COMMITS` | 1 | Enable auto-commit feature |
| `AIDER_SHOW_DIFFS` | 0 | Display diffs on commit |
| `AIDER_MODEL` | None | Default LLM model |
| `AIDER_API_KEY` | None | API key for LLM provider |

资料来源：[aider/main.py:80-120]()

## Testing Architecture

The InputOutput system supports dependency injection for testing purposes. The `input` and `output` parameters allow tests to provide mock or StringIO-based streams, enabling comprehensive testing of user interaction flows without terminal dependencies.

```python
def __init__(self, ..., input=None, output=None, ...):
    self.input = input
    self.output = output
```

资料来源：[aider/io.py:25-30]()

This design pattern facilitates unit testing and integration testing by decoupling the I/O operations from the main logic, allowing tests to simulate various input scenarios and capture output for verification.

## Module Dependencies

```mermaid
graph LR
    A[main.py] --> B[io.py]
    A --> C[repo.py]
    A --> D[coders/__init__.py]
    B --> E[prompt_toolkit]
    D --> F[base_coder.py]
    F --> G[llm adapters]
```

The dependency structure ensures that core functionality is isolated in foundational modules while higher-level components build upon them. This architecture supports maintainability and enables independent testing of each component.

---

<a id='page-main-flow'></a>

## Main Application Flow

### 相关页面

相关主题：[Core Architecture](#page-core-architecture)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [aider/main.py](https://github.com/Aider-AI/aider/blob/main/aider/main.py)
- [aider/__main__.py](https://github.com/Aider-AI/aider/blob/main/aider/__main__.py)
- [aider/commands.py](https://github.com/Aider-AI/aider/blob/main/aider/commands.py)
- [aider/sendchat.py](https://github.com/Aider-AI/aider/blob/main/aider/sendchat.py)
- [aider/getinput.py](https://github.com/Aider-AI/aider/blob/main/aider/getinput.py)
</details>

# Main Application Flow

## Overview

The Main Application Flow encompasses the entire lifecycle of an Aider session, from initialization through user interaction to AI-assisted code editing. Aider is an AI pair programming tool that integrates with Large Language Models (LLMs) to help developers modify codebases through natural language commands.

The application flow is designed around a command-driven architecture where user input is parsed, executed, or sent to the LLM for processing. Aider supports multiple LLM providers including Anthropic (Claude), OpenAI, DeepSeek, and local models.

## Application Entry Points

### Primary Entry: `__main__.py`

The `aider/__main__.py` file serves as the package entry point when running `python -m aider`. This module delegates to the main function in `aider/main.py`.

```python
# aider/__main__.py delegates to main.py
```

### Main Function: `main.py`

The `main()` function in `aider/main.py` orchestrates the entire application lifecycle. Based on chat transcript examples, it accepts the following keyword arguments:

| Parameter | Type | Purpose |
|-----------|------|---------|
| `input` | file-like object | Input source for REPL (default: sys.stdin) |
| `output` | file-like object | Output destination (default: sys.stdout) |

资料来源：[aider/main.py](https://github.com/Aider-AI/aider/blob/main/aider/main.py)

## Core Components

### InputOutput Class

The `InputOutput` class in `aider/getinput.py` manages all user interaction. It wraps prompt_toolkit's functionality and handles:

- Pretty/colorized terminal output
- User confirmation prompts (`yes` flag)
- Chat history file management
- Input history file management
- Terminal input/output streams

资料来源：[aider/getinput.py](https://github.com/Aider-AI/aider/blob/main/aider/getinput.py)

### Command Processing

Commands in Aider are prefixed with `/` and processed by the `commands.py` module. Available commands include:

| Command | Description |
|---------|-------------|
| `/quit` or `/exit` | Exit the application |
| `/help` | Display available commands |
| `/commit` | Manually commit changes |
| `/diff` | Show current changes |
| `/undo` | Revert last AI change |

资料来源：[aider/commands.py](https://github.com/Aider-AI/aider/blob/main/aider/commands.py)

### Chat Transmission

The `sendchat.py` module handles communication with LLM APIs. It constructs requests, sends them to the configured model, and processes responses.

资料来源：[aider/sendchat.py](https://github.com/Aider-AI/aider/blob/main/aider/sendchat.py)

## Application Flow Diagram

```mermaid
graph TD
    Start([User launches Aider]) --> Init[Initialize Application]
    Init --> LoadConfig[Load Configuration]
    LoadConfig --> SetupIO[Setup InputOutput]
    SetupIO --> CheckModel[Validate LLM Model]
    CheckModel --> RepoMap[Build Repository Map]
    RepoMap --> REPL[Enter REPL Loop]
    
    REPL --> ReadInput[Read User Input]
    ReadInput --> IsCommand{Is Command?}
    IsCommand -->|Yes| ExecCmd[Execute Command]
    ExecCmd --> REPL
    IsCommand -->|No| SendToLLM[Send to LLM]
    
    SendToLLM --> ReceiveResponse[Receive LLM Response]
    ReceiveResponse --> ApplyChanges[Apply Code Changes]
    ApplyChanges --> AutoCommit[Auto-commit Changes]
    AutoCommit --> REPL
    
    ApplyChanges -->|Errors Found| LintTest[Run Lint/Tests]
    LintTest --> FixIssues[Fix Detected Issues]
    FixIssues --> AutoCommit
    
    ReadInput -->|Exit Command| End([Session Ended])
```

## Session Lifecycle

### 1. Initialization Phase

1. Parse command-line arguments and environment variables
2. Initialize the `InputOutput` class with user preferences
3. Configure the LLM model based on `--model` flag or `AIDER_MODEL` environment variable
4. Set up API credentials from `--api-key` or respective environment variables

### 2. Repository Preparation Phase

1. Build a map of the codebase (repository map) for context
2. Identify and load relevant files based on user specification
3. Initialize git integration for change tracking

### 3. Interactive REPL Phase

The core interaction loop operates as follows:

```mermaid
sequenceDiagram
    participant User
    participant REPL
    participant Commands
    participant LLM
    participant Git
    
    User->>REPL: Input command/message
    REPL->>Commands: Check for /command
    alt Is slash command
        Commands->>Commands: Execute built-in
        Commands->>Git: Optionally commit/diff
    else Is chat message
        REPL->>LLM: Send to model
        LLM->>REPL: Return response
        REPL->>Git: Auto-commit changes
    end
    REPL->>User: Display output
```

### 4. Automatic Commit Flow

Aider automatically commits changes after each AI-assisted modification:

```mermaid
graph LR
    A[AI Edits Code] --> B[Generate Commit Message]
    B --> C[Commit to Git]
    C --> D[Store in History]
```

The commit behavior can be controlled via:
- `--no-auto-commits` flag
- `AIDER_AUTO_COMMITS` environment variable (0 to disable)

资料来源：[README.md](https://github.com/Aider-AI/aider/blob/main/README.md)

## Configuration and Environment

### Supported Python Versions

Aider supports Python 3.9 through 3.12.

资料来源：[CONTRIBUTING.md](https://github.com/Aider-AI/aider/blob/main/CONTRIBUTING.md)

### Environment Variables

| Variable | Default | Description |
|----------|---------|-------------|
| `AIDER_MODEL` | gpt-4 | Default LLM model |
| `AIDER_API_KEY` | - | API key for the model |
| `AIDER_AUTO_COMMITS` | 1 | Enable auto-commits |
| `AIDER_SHOW_DIFFS` | 0 | Show diffs on commit |
| `AIDER_HISTORY_FILE` | .aider.history | Chat history file |
| `AIDER_PRETTY` | 1 | Enable colored output |

## Testing Integration

Aider integrates with linting and testing tools:

```mermaid
graph TD
    A[AI Makes Changes] --> B{Config Enabled?}
    B -->|Yes| C[Run Linters]
    C --> D{Issues Found?}
    D -->|Yes| E[AI Fixes Issues]
    E --> F[Run Tests]
    D -->|No| F
    F --> G{Tests Pass?}
    G -->|No| H[AI Fixes Tests]
    H --> F
    G -->|Yes| I[Commit Changes]
```

资料来源：[aider/website/index.html](https://github.com/Aider-AI/aider/blob/main/aider/website/index.html)

## Error Handling

The application handles various error scenarios:

1. **API Errors**: Retry logic with user notification
2. **Git Conflicts**: User confirmation for resolution
3. **Invalid Commands**: Display help message
4. **File Access Errors**: Clear error messages with suggestions

## Data Flow

```mermaid
graph LR
    subgraph Input
        CLI[CLI Args] --> Env[Env Variables]
        Env --> Config[Configuration]
    end
    
    subgraph Processing
        Config --> Main[main.py]
        Main --> IO[InputOutput]
        IO --> REPL[REPL Loop]
        REPL --> Cmd[commands.py]
        REPL --> Chat[sendchat.py]
    end
    
    subgraph Output
        Chat --> Response[LLM Response]
        Response --> Diff[Git Diff]
        Diff --> Commit[Auto-commit]
    end
```

## Key Module Responsibilities

| Module | Responsibility |
|--------|----------------|
| `__main__.py` | Package entry point, calls main() |
| `main.py` | Application orchestration, argument parsing |
| `getinput.py` | User I/O, prompt_toolkit integration |
| `commands.py` | Built-in command processing |
| `sendchat.py` | LLM API communication |

## Conclusion

The Main Application Flow demonstrates Aider's architecture as a well-structured CLI tool that bridges human programming intent with AI capabilities. The flow prioritizes user experience through automatic git integration, clear feedback, and seamless LLM interaction while maintaining testability through configurable input/output streams for testing purposes.

---

<a id='page-model-integration'></a>

## Model Integration System

### 相关页面

相关主题：[Chat Communication Protocol](#page-chat-communication), [Core Architecture](#page-core-architecture)

<details>
<summary>Related Source Files</summary>

以下源码文件用于生成本页说明：

- [aider/llm.py](https://github.com/Aider-AI/aider/blob/main/aider/llm.py) *(Not available in context)*
- [aider/models.py](https://github.com/Aider-AI/aider/blob/main/aider/models.py) *(Not available in context)*
- [aider/sendchat.py](https://github.com/Aider-AI/aider/blob/main/aider/sendchat.py) *(Not available in context)*
- [aider/openrouter.py](https://github.com/Aider-AI/aider/blob/main/aider/openrouter.py) *(Not available in context)*
- [aider/resources/model-metadata.json](https://github.com/Aider-AI/aider/blob/main/aider/resources/model-metadata.json) *(Not available in context)*
- [aider/resources/model-settings.yml](https://github.com/Aider-AI/aider/blob/main/aider/resources/model-settings.yml) *(Not available in context)*

**Note:** The requested source files were not included in the provided context. This page is generated based on context from README.md, requirements files, and website documentation.
</details>

# Model Integration System

The Model Integration System is Aider's core abstraction layer for connecting to and interacting with Large Language Models (LLMs). It provides a unified interface that allows Aider to work with multiple LLM providers including OpenAI, Anthropic, DeepSeek, and OpenRouter, while abstracting away provider-specific implementation details.

## Overview

Aider's architecture separates the concerns of LLM communication from the main application logic. The Model Integration System handles:

- **Provider Abstraction**: Uniform API for different LLM backends
- **Model Configuration**: Settings and metadata for supported models
- **Chat Communication**: Sending prompts and receiving responses
- **Token Management**: Tracking usage and costs
- **Error Handling**: Provider-specific error recovery

资料来源：[README.md](https://github.com/Aider-AI/aider/blob/main/README.md)

## Architecture Overview

```mermaid
graph TD
    A[User Interface] --> B[Core Application]
    B --> C[Model Integration Layer]
    C --> D[LLM Provider Adapters]
    
    D --> E[OpenAI API]
    D --> F[Anthropic API]
    D --> G[DeepSeek API]
    D --> H[OpenRouter Gateway]
    
    C --> I[Model Settings]
    C --> J[Model Metadata]
    
    style C fill:#e1f5fe
    style D fill:#fff3e0
```

## Supported Models

Based on the project's documentation, Aider supports the following model families:

| Provider | Models | API Type |
|----------|--------|----------|
| OpenAI | GPT-4o, o1, o3-mini, GPT-3.5-turbo | REST API |
| Anthropic | Claude 3.7 Sonnet, Claude 3 Opus | REST API |
| DeepSeek | DeepSeek models | REST API |
| OpenRouter | 100+ third-party models | Unified Gateway |
| Local Models | Various via OLLAMA | Local API |

资料来源：[aider/website/index.html](https://github.com/Aider-AI/aider/blob/main/aider/website/index.html)

## Core Components

### Model Configuration

Models are configured through command-line arguments and environment variables:

```bash
# Using model flag
aider --model sonnet --api-key anthropic=<key>

# Using DeepSeek
aider --model deepseek --api-key deepseek=<key>

# Using OpenAI
aider --model o3-mini --api-key openai=<key>
```

### Environment Variables

| Variable | Purpose | Example |
|----------|---------|---------|
| `AIDER_MODEL` | Default model selection | `sonnet`, `gpt-4o` |
| `ANTHROPIC_API_KEY` | Anthropic authentication | `sk-ant-...` |
| `OPENAI_API_KEY` | OpenAI authentication | `sk-...` |
| `DEEPSEEK_API_KEY` | DeepSeek authentication | `<key>` |
| `OPENROUTER_API_KEY` | OpenRouter authentication | `sk-or-...` |

资料来源：[aider/website/_includes/get-started.md](https://github.com/Aider-AI/aider/blob/main/aider/website/_includes/get-started.md)

## Dependency Architecture

The Model Integration System relies on several key dependencies for LLM communication:

```mermaid
graph LR
    A[LLM Integration] --> B[OpenAI Python SDK]
    A --> C[Anthropic SDK]
    A --> D[llama-index-core]
    A --> E[transformers]
    A --> F[sentence-transformers]
    A --> G[tiktoken]
    
    B --> H[grpcio]
    C --> I[aiohttp]
    D --> J[torch]
    E --> K[huggingface-hub]
```

### Key Dependencies

| Package | Version | Purpose |
|---------|---------|---------|
| `openai` | Latest | OpenAI API client |
| `anthropic` | Latest | Anthropic Claude client |
| `llama-index-core` | Latest | Indexing and retrieval |
| `transformers` | 5.3.0 | HuggingFace model support |
| `sentence-transformers` | Latest | Embedding generation |
| `tiktoken` | 0.12.0 | Token counting |
| `torch` | 2.10.0 | ML computation backend |

资料来源：[requirements/requirements-help.txt](https://github.com/Aider-AI/aider/blob/main/requirements/requirements-help.txt)

## Model Communication Flow

```mermaid
sequenceDiagram
    participant User
    participant App as Aider Core
    participant LLM as LLM Adapter
    participant API as Provider API
    
    User->>App: User prompt
    App->>LLM: Prepare request
    LLM->>API: API call with model
    API->>LLM: Response
    LLM->>App: Parsed response
    App->>User: Display result
    
    Note over LLM,API: Token usage tracked
```

## Configuration Files

### Model Metadata

Model metadata files contain information about supported models including:

- **Context window size**: Maximum tokens the model can process
- **Output limits**: Maximum response tokens
- **Pricing information**: Cost per token
- **Capability flags**: Tool use, vision support, etc.

### Model Settings

Settings files configure per-model behavior:

- Temperature parameters
- System prompt templates
- Retry configurations
- Timeout values

资料来源：[scripts/my_models.py](https://github.com/Aider-AI/aider/blob/main/scripts/my_models.py)

## Token Tracking

The system tracks token usage across sessions:

```python
# Example token statistics structure
model_stats = {
    "claude-3-7-sonnet-20260219": 125000,
    "gpt-4o": 85000,
    "deepseek-chat": 62000,
}
```

Usage analytics record:
- Model name
- Total input tokens
- Total output tokens
- Percentage of overall usage

## Integration Points

### Main Application Integration

The model integration connects with:

1. **Input/Output System** (`aider/getinput.py`): Handles user interaction
2. **File Management** (`aider/main.py`): Reads code context
3. **Git Integration** (`aider/git.py`): Commits changes automatically
4. **Linting/Testing** (`aider/linter.py`): Validates code changes

### IDE Integration

Aider can be used from within IDEs by adding comments to code that trigger model interactions.

资料来源：[aider/website/examples/complex-change.md](https://github.com/Aider-AI/aider/blob/main/aider/website/examples/complex-change.md)

## Supported Programming Languages

The Model Integration System works across 100+ programming languages:

| Category | Languages |
|----------|-----------|
| Web | JavaScript, TypeScript, HTML, CSS |
| Systems | Python, Rust, Go, C++, C |
| Scripting | Ruby, PHP, Perl, Lua |
| Functional | Haskell, Scala, Clojure, F# |
| Other | Java, Kotlin, Swift, R, Julia |

资料来源：[aider/website/index.html](https://github.com/Aider-AI/aider/blob/main/aider/website/index.html)

## Error Handling

The system implements provider-specific error recovery:

- Rate limiting detection and backoff
- Authentication failure handling
- Network timeout management
- Model-specific error mapping

## Future Extensibility

The architecture supports adding new providers through:

1. Implementing the adapter interface
2. Adding provider configuration
3. Updating model metadata
4. Registering in the model registry

This modular design allows Aider to quickly adopt new LLM providers as they become available.

## Related Documentation

- [Installation Guide](https://aider.chat/docs/install.html)
- [Usage Guide](https://aider.chat/docs/usage.html)
- [Connecting to LLMs](https://aider.chat/docs/llms.html)
- [Configuration Options](https://aider.chat/docs/config.html)

---

<a id='page-chat-communication'></a>

## Chat Communication Protocol

### 相关页面

相关主题：[Model Integration System](#page-model-integration), [Code Editing Strategies](#page-coder-strategies)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [aider/sendchat.py](https://github.com/Aider-AI/aider/blob/main/aider/sendchat.py)
- [aider/mdstream.py](https://github.com/Aider-AI/aider/blob/main/aider/mdstream.py)
- [aider/chat_chunks.py](https://github.com/Aider-AI/aider/blob/main/aider/chat_chunks.py)
- [aider/coders/base_prompts.py](https://github.com/Aider-AI/aider/blob/main/aider/coders/base_prompts.py)
- [aider/coders/editblock_prompts.py](https://github.com/Aider-AI/aider/blob/main/aider/coders/editblock_prompts.py)
- [aider/coders/wholefile_func_coder.py](https://github.com/Aider-AI/aider/blob/main/aider/coders/wholefile_func_coder.py)
</details>

# Chat Communication Protocol

## Overview

The Chat Communication Protocol in Aider defines how the application exchanges messages with Large Language Models (LLMs) to enable AI pair programming. This protocol orchestrates the sending of prompts, streaming of responses, parsing of code edits, and handling of various message formats between the user, Aider's codebase, and the LLM API.

Aider supports multiple edit response formats to accommodate different LLM capabilities and user preferences:

- **Edit blocks** (`editblock`) - Uses fenced code blocks with `<<<<<<< ORIGINAL` and `=======` separators
- **Whole file** (`wholefile`) - Returns complete updated file contents
- **Whole function** (`whole-func`) - Uses function call API for structured file updates
- **Diff function** (`diff-func`) - Uses function call API with diff-style edits

资料来源：[aider/coders/editblock_prompts.py]()

## Architecture

```mermaid
graph TD
    subgraph "User Interface Layer"
        CLI[Command Line Interface]
        IO[InputOutput / getinput.py]
    end
    
    subgraph "Coder Layer"
        BASE[Coder Base Class]
        EDIT[EditblockCoder]
        WHOLE[WholeFileCoder]
        FUNC[WholeFuncCoder]
    end
    
    subgraph "Communication Layer"
        SEND[sendchat.py]
        STREAM[mdstream.py]
        CHUNKS[chat_chunks.py]
    end
    
    subgraph "LLM Backend"
        API[LLM API Provider]
    end
    
    CLI --> IO
    CLI --> BASE
    BASE --> SEND
    SEND --> STREAM
    SEND --> API
    STREAM --> CHUNKS
    CHUNKS --> BASE
    CHUNKS --> EDIT
    CHUNKS --> WHOLE
    CHUNKS --> FUNC
```

## Core Components

### Message Prompts System

The prompt system in Aider is built on a class hierarchy rooted in `CoderPrompts`. Prompts are modular, allowing different coder types to customize their system messages and conversation flows.

#### Base Prompt Structure

```python
class CoderPrompts:
    main_system = """Base system prompt for aider..."""
    example_messages = []
    system_reminder = ""
    files_content_prefix = """These are some files..."""
```

资料来源：[aider/coders/base_prompts.py:1-10]()

### Edit Block Prompts

The `EditblockPrompts` class extends `CoderPrompts` to generate prompts specifically designed for models that return edits in diff format:

```python
class EditblockPrompts(CoderPrompts):
    # Defines how to format edit instructions to the LLM
    # Uses fenced code blocks with ORIGINAL/UPDATED markers
```

资料来源：[aider/coders/editblock_prompts.py]()

## Response Formats

### Edit Block Format

The default format uses fenced code blocks with conflict-style markers:

````markdown
```python
demo.py
<<<<<<< ORIGINAL
    print("hello")
=======
    print("goodbye")
>>>>>>> UPDATED
```
````

The parser extracts the filename from the language identifier, then identifies the `ORIGINAL` and `UPDATED` sections using the conflict markers.

资料来源：[aider/website/_posts/2023-07-02-benchmarks.md]()

### Whole File Format

Returns complete file contents in a fenced code block:

````
Here is the updated copy of your file demo.py:

demo.py
```python
def main():
    print("goodbye")
```
````

资料来源：[aider/website/_posts/2023-07-02-benchmarks.md]()

### Function Call Formats

#### Whole Function Format

Uses the function call API with structured JSON:

```json
{
    "explanation": "Changed hello to goodbye.",
    "files": [
        {
            "path": "demo.py",
            "content": "def main():\n    print(\"goodbye\")\n"
        }
    ]
}
```

资料来源：[aider/website/_posts/2023-07-02-benchmarks.md]()

#### Diff Function Format

Combines diff-style edits with function call API for structured output:

| Format Type | Input Method | Output Method | Best For |
|-------------|--------------|---------------|----------|
| `editblock` | Chat completions | Markdown diff | Most LLMs |
| `wholefile` | Chat completions | Full file content | Claude |
| `whole-func` | Function calls | Structured JSON | Advanced models |
| `diff-func` | Function calls | JSON diff | Code-specific models |

## Message Streaming

### Markdown Stream Processing

The `mdstream.py` module handles streaming responses from LLM APIs, parsing them incrementally to support real-time display of responses.

```mermaid
sequenceDiagram
    participant User
    participant CLI
    participant SendChat
    participant Stream
    participant LLM as LLM API
    
    User->>CLI: Execute command
    CLI->>SendChat: Send prompt
    SendChat->>LLM: Stream request
    LLM-->>SendChat: Token stream
    SendChat->>Stream: Process tokens
    Stream-->>CLI: Markdown chunks
    CLI-->>User: Real-time display
```

资料来源：[aider/mdstream.py]()

### Chat Chunk Processing

The `chat_chunks.py` module parses streamed content into discrete, actionable chunks that can be processed by the appropriate coder:

| Chunk Type | Description | Parser Used |
|------------|-------------|-------------|
| `read` | File read requests | Text extraction |
| `edit` | Code modifications | Diff parser |
| `message` | User/assistant messages | Markdown renderer |
| `error` | Error responses | Error formatter |

资料来源：[aider/chat_chunks.py]()

## Workflow: Edit Request and Application

```mermaid
graph LR
    A[User Request] --> B[Construct Prompt]
    B --> C[Send to LLM]
    C --> D[Stream Response]
    D --> E[Parse Edit Blocks]
    E --> F{Format Valid?}
    F -->|Yes| G[Validate Edit]
    F -->|No| H[Request Retry]
    G --> I{Edit Safe?}
    I -->|Yes| J[Apply Edit]
    I -->|No| K[User Confirmation]
    K --> J
    J --> L[Commit Changes]
    H --> C
```

### Edit Validation

Before applying edits, Aider validates:

1. **Syntax validity** - The edited code is syntactically correct
2. **Semantic consistency** - Imports and references remain valid
3. **Safety checks** - Destructive operations are flagged for confirmation

资料来源：[aider/coders/editblock_prompts.py]()

## Configuration Options

### Prompt Customization

| Parameter | Default | Description |
|-----------|---------|-------------|
| `main_system` | Base aider system | Primary instructions to the LLM |
| `system_reminder` | Context reminder | Reminders appended to system |
| `example_messages` | Empty list | Few-shot examples |
| `files_content_prefix` | File intro text | How to introduce file context |

资料来源：[aider/coders/base_prompts.py:1-20]()

### Response Format Selection

```python
# In coder initialization
format_type = "editblock"  # Options: editblock, wholefile, whole-func, diff-func
```

## Integration with LLM Providers

The communication protocol is provider-agnostic, supporting:

- **OpenAI** (GPT-4, GPT-3.5, o3-mini)
- **Anthropic** (Claude 3.7 Sonnet, Claude Opus)
- **DeepSeek**
- **Local models** via OpenAI-compatible APIs

Each provider may have preferred response formats configured in their respective coder implementations.

## Error Handling

| Error Type | Cause | Recovery Action |
|------------|-------|-----------------|
| Parse failure | Malformed response | Retry with clarification |
| Invalid edit | Syntax error in proposed change | Show error, request correction |
| API timeout | Network or provider issue | Automatic retry with backoff |
| Rate limit | Provider throttling | Wait and retry |

## Security Considerations

- **No code execution** - Aider never executes LLM-provided code directly
- **Git tracking** - All changes are committed through git for audit trail
- **Confirmation prompts** - Destructive or significant changes require user approval
- **Input sanitization** - File paths and content are validated before processing

## Summary

The Chat Communication Protocol is the backbone of Aider's interaction with LLMs. It defines:

- How prompts are constructed from user input and codebase context
- How responses are streamed and parsed in real-time
- How different edit formats are handled across LLM providers
- How edits are validated, applied, and committed safely

This protocol enables Aider to serve as a reliable AI pair programming partner, bridging human intent with precise code modifications across diverse development environments.

---

<a id='page-coder-strategies'></a>

## Code Editing Strategies

### 相关页面

相关主题：[Edit Format Handling](#page-edit-formats), [Chat Communication Protocol](#page-chat-communication)

<details>
<summary>Related Source Files</summary>

The following source files were used to generate this page:

- [aider/coders/editblock_coder.py](https://github.com/Aider-AI/aider/blob/main/aider/coders/editblock_coder.py)
- [aider/coders/wholefile_coder.py](https://github.com/Aider-AI/aider/blob/main/aider/coders/wholefile_coder.py)
- [aider/coders/udiff_coder.py](https://github.com/Aider-AI/aider/blob/main/aider/coders/udiff_coder.py)
- [aider/coders/patch_coder.py](https://github.com/Aider-AI/aider/blob/main/aider/coders/patch_coder.py)
- [aider/coders/base_coder.py](https://github.com/Aider-AI/aider/blob/main/aider/coders/base_coder.py)
- [aider/coders/search_replace.py](https://github.com/Aider-AI/aider/blob/main/aider/coders/search_replace.py)
</details>

# Code Editing Strategies

## Overview

Aider supports multiple code editing strategies that determine how AI model outputs are converted into file modifications. Each strategy has distinct characteristics suited for different use cases, model capabilities, and editing scenarios.

The editing system in aider is built around a modular architecture where different coder classes handle specific edit formats. The base functionality is defined in `base_coder.py`, with specialized implementations for each editing approach.

## Architecture

### Edit Strategy Class Hierarchy

```mermaid
graph TD
    A[base_coder.py<br>BaseCoder] --> B[wholefile_coder.py<br>WholeFileCoder]
    A --> C[editblock_coder.py<br>EditBlockCoder]
    A --> D[search_replace.py<br>SearchReplaceCoder]
    A --> E[udiff_coder.py<br>UDiffCoder]
    A --> F[patch_coder.py<br>PatchCoder]
    
    B --> G[Whole File Editing<br>Complete file replacement]
    C --> H[Edit Block<br>ORIGINAL/UPDATE markers]
    D --> I[Search/Replace<br>Pattern matching edits]
    E --> J[Unified Diff<br>diff -u format]
    F --> K[Patch<br>git apply style]
```

### Edit Flow

```mermaid
sequenceDiagram
    participant User
    participant Coder as BaseCoder
    participant Parser as Edit Parser
    participant File as File System
    
    User->>Coder: Request code change
    Coder->>Coder: Send to LLM with format instructions
    LLM-->>Coder: Return edit in specified format
    Coder->>Parser: Parse edit response
    Parser->>Parser: Validate edit structure
    Parser->>File: Apply changes
    File-->>Coder: Confirmation
    Coder-->>User: Display result
```

## Edit Strategies

### 1. Edit Block Format

The edit block format uses `<<<<<<< ORIGINAL` and `=======` markers to delineate changes. This is the default and most widely supported format.

**File:** `aider/coders/editblock_coder.py`

```python
# Example structure
<<<<<<< ORIGINAL
    print("hello")
=======
    print("goodbye")
>>>>>>> UPDATED
```

**Characteristics:**
- Most compatible with various LLM models
- Explicit ORIGINAL and UPDATED sections
- Works well for localized changes
- Requires the model to include surrounding context

**Configuration:**

| Parameter | Description | Default |
|-----------|-------------|---------|
| `fencing` | Language for code fences | varies by model |
| `max_fences` | Maximum number of fences per response | auto-detected |

资料来源：[aider/coders/editblock_coder.py](https://github.com/Aider-AI/aider/blob/main/aider/coders/editblock_coder.py)

---

### 2. Whole File Editing

The whole file strategy requests complete replacement of file contents rather than incremental changes.

**File:** `aider/coders/wholefile_coder.py`

**Characteristics:**
- Model returns complete file content
- No risk of partial edit mismatches
- Higher token overhead for large files
- Uses function call API when available

**Response Format:**
```json
{
    "explanation": "Changed hello to goodbye.",
    "files": [
        {
            "path": "demo.py",
            "content": "def main():\n    print(\"goodbye\")\n"
        }
    ]
}
```

资料来源：[aider/coders/wholefile_coder.py](https://github.com/Aider-AI/aider/blob/main/aider/coders/wholefile_coder.py)

---

### 3. Unified Diff Format

The unified diff format uses standard `diff -u` style output for specifying changes.

**File:** `aider/coders/udiff_coder.py`

```diff
--- a/demo.py
+++ b/demo.py
@@ -1,3 +1,3 @@
 def main():
-    print("hello")
+    print("goodbye")
```

**Characteristics:**
- Industry-standard diff format
- Familiar to developers using version control
- Clear addition and deletion markers
- Includes context lines automatically

资料来源：[aider/coders/udiff_coder.py](https://github.com/Aider-AI/aider/blob/main/aider/coders/udiff_coder.py)

---

### 4. Patch Format

The patch format provides git-apply compatible patches for file modifications.

**File:** `aider/coders/patch_coder.py`

**Characteristics:**
- Direct compatibility with `git apply`
- Header includes file path information
- Binary diffing support
- Strip count configuration for nested paths

资料来源：[aider/coders/patch_coder.py](https://github.com/Aider-AI/aider/blob/main/aider/coders/patch_coder.py)

---

### 5. Search/Replace Format

The search/replace format uses explicit `search_for` and `replace_with` directives.

**File:** `aider/coders/search_replace.py`

```python
search_for: print("hello")
replace_with: print("goodbye")
```

**Characteristics:**
- Explicit intent specification
- Works well for simple substitutions
- No need for surrounding context
- Model-friendly for targeted changes

**API Parameters:**

| Parameter | Type | Description |
|-----------|------|-------------|
| `edit_format` | string | Must be "search_replace" |
| `search_replace` | object | Contains search_for and replace_with keys |
| `pathname` | string | Target file path |

资料来源：[aider/coders/search_replace.py](https://github.com/Aider-AI/aider/blob/main/aider/coders/search_replace.py)

---

## Base Coder Functionality

**File:** `aider/coders/base_coder.py`

The `BaseCoder` class provides common functionality inherited by all edit strategies:

### Core Responsibilities

```mermaid
graph LR
    A[User Request] --> B[BaseCoder]
    B --> C[LLM Communication]
    B --> D[Edit Parsing]
    B --> E[File Operations]
    B --> F[Git Integration]
    
    C --> G[Send prompts with format instructions]
    D --> H[Validate and extract edits]
    E --> I[Read/write file system]
    F --> J[Auto-commit changes]
```

### Common Methods

| Method | Description |
|--------|-------------|
| `run()` | Main interaction loop with LLM |
| `get_edits()` | Parse and apply edits from response |
| `check_retry()` | Validate edit structure, retry on failure |
| `commit()` | Git commit with generated message |

资料来源：[aider/coders/base_coder.py](https://github.com/Aider-AI/aider/blob/main/aider/coders/base_coder.py)

## Edit Response Processing

### Parsing Pipeline

```mermaid
flowchart TD
    A[LLM Response] --> B{Edit Format Valid?}
    B -->|Yes| C[Extract File Paths]
    B -->|No| D[Request Retry]
    C --> E{File Exists?}
    D --> A
    E -->|Yes| F[Apply Edits]
    E -->|No| G[Create New File]
    F --> H[Validate Syntax]
    G --> H
    H --> I[Git Commit]
    H --> J[Error Report]
```

### Validation Steps

1. **Format Check**: Verify correct marker usage (`<<<<<<<`, `=======`, `>>>>>>>`)
2. **Path Verification**: Confirm target files exist or are valid for creation
3. **Syntax Validation**: Run linters if configured
4. **Test Execution**: Run tests if enabled

### Error Handling

| Error Type | Recovery Action |
|------------|-----------------|
| Malformed ORIGINAL/UPDATE blocks | Request retry with clarification |
| File not found | Create file or prompt user |
| Syntax error | Report to LLM for correction |
| Test failure | Rollback and request fix |

## Configuration

### Edit Format Selection

```bash
# Command line selection
aider --edit-format edit

# Environment variable
AIDER_EDIT_FORMAT=editblock
```

### Supported Format Values

| Format | Coder Class | Best For |
|--------|-------------|----------|
| `edit` or `editblock` | EditBlockCoder | General purpose |
| `whole` or `wholefile` | WholeFileCoder | Complete replacements |
| `udiff` | UDiffCoder | Standard diff workflows |
| `patch` | PatchCoder | Git operations |
| `search_replace` | SearchReplaceCoder | Simple substitutions |

## Best Practices

### Selecting an Edit Strategy

| Scenario | Recommended Strategy |
|----------|----------------------|
| Small localized changes | Edit Block |
| Complete file rewrites | Whole File |
| Working with version control | Unified Diff |
| Multiple small changes | Search/Replace |
| Complex multi-file changes | Patch |

### Optimization Tips

1. **Token Efficiency**: Use edit blocks for small changes to minimize token usage
2. **Context Windows**: Consider whole-file for files under 4KB
3. **Reliability**: Edit blocks provide better error messages for malformed responses
4. **Model Capabilities**: Some models perform better with specific formats

## Summary

Aider's code editing system provides five distinct strategies, each optimized for different scenarios and model capabilities. The modular architecture allows seamless switching between formats while maintaining consistent git integration and error handling. Understanding these strategies enables developers to choose the most effective approach for their specific use case and model selection.

---

<a id='page-edit-formats'></a>

## Edit Format Handling

### 相关页面

相关主题：[Code Editing Strategies](#page-coder-strategies)

<details>
<summary>Related Source Files</summary>

以下源码文件用于生成本页说明：

- [aider/coders/editblock_prompts.py](https://github.com/Aider-AI/aider/blob/main/aider/coders/editblock_prompts.py)
- [aider/coders/editblock_func_coder.py](https://github.com/Aider-AI/aider/blob/main/aider/coders/editblock_func_coder.py)
- [aider/coders/editblock_fenced_prompts.py](https://github.com/Aider-AI/aider/blob/main/aider/coders/editblock_fenced_prompts.py)
- [aider/website/_posts/2023-07-02-benchmarks.md](https://github.com/Aider-AI/aider/blob/main/aider/website/_posts/2023-07-02-benchmarks.md)
- [aider/website/examples/semantic-search-replace.md](https://github.com/Aider-AI/aider/blob/main/aider/website/examples/semantic-search-replace.md)
</details>

# Edit Format Handling

Aider supports multiple edit formats that define how Large Language Models (LLMs) communicate code changes back to the tool. Each format specifies a structured protocol for representing file modifications, including search patterns to locate code and replacement content.

## Overview

The edit format handling system is a core component of Aider's architecture that bridges communication between LLMs and the local filesystem. When an LLM proposes changes to code, it must express them using a specific format that Aider can parse, validate, and apply.

```mermaid
graph LR
    A[LLM Response] --> B[Edit Format Parser]
    B --> C{Valid Format?}
    C -->|Yes| D[Apply Edits to Files]
    C -->|No| E[Error Handling]
    D --> F[Git Commit]
    E --> G[Request Retry]
    G --> A
```

资料来源：[aider/website/_posts/2023-07-02-benchmarks.md:25-40]()

## Supported Edit Formats

Aider supports several edit formats, each with different trade-offs in expressiveness, parsing complexity, and LLM compatibility.

| Format | Description | Use Case |
|--------|-------------|----------|
| `search_replace` | Search/Replace block format | Default format, works with most LLMs |
| `diff` | Unified diff format | Version control oriented changes |
| `whole` | Replace entire file content | Simple file-level operations |
| `diff-func` | Function call API format | Structured JSON-based edits |

资料来源：[aider/website/_posts/2023-07-02-benchmarks.md:25-40]()

## Search/Replace Block Format

The search/replace format is the primary edit mechanism in Aider. It uses special markers to delimit sections of code that should be replaced.

### Block Structure

Each search/replace block follows this pattern:

```markdown
path/to/file.py
<<<<<<< SEARCH
existing code lines to find
=======
new code lines to insert
>>>>>>> REPLACE
```

资料来源：[aider/coders/editblock_prompts.py:1-25]()

### Prompt Instructions

The system includes detailed instructions for LLMs on how to construct valid search/replace blocks. These instructions are embedded in the edit format prompts and include:

1. **File Path Requirements**: The full file path must appear alone on a line before each block
2. **Unique Matching**: Search sections must exactly match existing content, including whitespace and comments
3. **Sequential Processing**: Search/replace blocks are processed in order, with each replacement affecting subsequent blocks
4. **Multi-file Support**: Multiple files can be edited in a single response

资料来源：[aider/coders/editblock_fenced_prompts.py:1-30]()

### Validation Rules

The search section of each block must:

- Match the original file content character-for-character
- Include all whitespace and newlines exactly as they appear
- Be unique within the file to prevent ambiguous replacements
- Include sufficient context lines for uniqueness

资料来源：[aider/coders/editblock_prompts.py:20-30]()

## Function Call Format (diff-func)

The `diff-func` format uses structured function calls to express edits, providing a machine-readable alternative to text-based search/replace blocks.

### Request Structure

```json
{
  "explanation": "Step by step plan for the changes",
  "edits": [
    {
      "path": "demo.py",
      "original_lines": ["    print(\"hello\")"],
      "updated_lines": ["    print(\"goodbye\")"]
    }
  ]
}
```

资料来源：[aider/coders/editblock_func_coder.py:1-30]()

### Edit Object Schema

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `path` | string | Yes | Path of file to edit |
| `original_lines` | array of strings | Yes | Lines to search for in original file |
| `updated_lines` | array of strings | Yes | New content to replace matched lines |

资料来源：[aider/coders/editblock_func_coder.py:50-80]()

### Deprecation Notice

The current implementation of `EditBlockFunctionCoder` is marked as deprecated:

```python
def __init__(self, code_format, *args, **kwargs):
    raise RuntimeError("Deprecated, needs to be refactored to support get_edits/apply_edits")
```

资料来源：[aider/coders/editblock_func_coder.py:35-37]()

## Edit Application Workflow

```mermaid
sequenceDiagram
    participant LLM
    participant Parser
    participant Validator
    participant FileSystem
    participant Git
    
    LLM->>Parser: Send response with edits
    Parser->>Parser: Extract edit blocks
    Parser->>Validator: Validate search patterns
    Validator->>FileSystem: Read target files
    Validator->>Validator: Verify exact matches
    Validator->>FileSystem: Apply replacements
    FileSystem->>Git: Stage changes
    Git->>Git: Create commit
```

## Error Handling

When an edit cannot be applied, Aider provides detailed error messages to help the LLM retry with corrected edits.

### Common Error Scenarios

| Error Type | Cause | Recovery Action |
|------------|-------|-----------------|
| `Malformed ORIGINAL/UPDATE blocks` | Missing or misaligned markers | Retry with correctly formatted blocks |
| `No exact match found` | Search content differs from file | Verify whitespace and content |
| `Multiple matches found` | Search pattern not unique | Add more context lines |

资料来源：[aider/website/examples/semantic-search-replace.md:1-20]()

### Error Reporting Format

Aider reports errors through the IO subsystem:

```python
self.io.tool_error("Malformed ORIGINAL/UPDATE blocks, retrying...")
self.io.tool_error(Text(err))
```

资料来源：[aider/website/examples/semantic-search-replace.md:10-15]()

## Integration with Commands

The edit format handling integrates with Aider's command system through the `Commands` class, which manages the coder lifecycle and edit format selection.

```python
coder = Coder.create(
    io=self.io,
    from_coder=self.coder,
    edit_format=edit_format,
    summarize_from_coder=False,
)
```

资料来源：[aider/commands.py:1-30]()

## Best Practices

### For LLM Generation

1. Always include the full file path on its own line before each edit block
2. Ensure search sections contain exact matches including all whitespace
3. Use sufficient context lines to uniquely identify the target location
4. Process files in a logical order when making multiple changes

### For Users

1. Use `/edit-format` command to switch between available formats
2. Enable linting and testing to validate changes automatically
3. Review git diffs before committing AI-generated changes

资料来源：[README.md:1-50]()

## Configuration

Edit format behavior can be configured through Aider's settings:

| Setting | Description | Default |
|---------|-------------|---------|
| `edit_format` | Preferred edit format | `search_replace` |
| `auto_lint` | Run linter after edits | `true` |
| `auto_test` | Run tests after edits | `false` |

## Related Components

The edit format handling system depends on several core components:

- **Base Coder** (`base_coder.py`): Defines the interface for all coder implementations
- **Edit Block Prompts** (`editblock_prompts.py`): Contains LLM instructions for each format
- **IO Subsystem** (`io.py`): Handles error reporting and user communication
- **Git Integration**: Automatically commits applied changes

资料来源：[aider/coders/editblock_prompts.py:1-50]()
资料来源：[aider/coders/editblock_func_coder.py:1-80]()

---

<a id='page-git-integration'></a>

## Git Integration

# Aider Repository Analysis

## Overview

Aider is an AI pair programming tool that runs in the terminal, allowing developers to collaborate with Large Language Models (LLMs) on code editing tasks. It integrates with git for version control and supports multiple LLM providers including DeepSeek, Claude, and OpenAI models.

## Project Structure

| Directory/File | Purpose |
|----------------|---------|
| `aider/` | Main Python package containing core application code |
| `aider/coders/` | Code editing and generation modules |
| `aider/website/` | Jekyll-based documentation site |
| `requirements/` | Dependency specifications |
| `README.md` | Project documentation and getting started |
| `CONTRIBUTING.md` | Developer guidelines |

## Key Source Files

| File | Description |
|------|-------------|
| `aider/main.py` | Application entry point, argument parsing integration |
| `aider/args.py` | Command-line argument definitions including git settings |
| `aider/repo.py` | Git repository operations |
| `aider/prompts.py` | System prompts for LLM interactions and commit message generation |
| `aider/history.py` | Chat history management |
| `aider/coders/base_coder.py` | Base class for code editing operations |

## Git Integration

Aider provides comprehensive git integration with the following features:

### Command-Line Options (from `aider/args.py:1-100`)

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `--git` | BooleanOptional | True | Enable/disable git repo detection |
| `--gitignore` | BooleanOptional | True | Add `.aider*` to `.gitignore` |
| `--add-gitignore-files` | BooleanOptional | False | Include `.gitignore` files in editing scope |
| `--aiderignore` | Path | `.aiderignore` | Specify aider ignore file |
| `--subtree-only` | Boolean | False | Only consider files in current subtree |
| `--auto-commits` | BooleanOptional | True | Auto commit LLM changes |
| `--dirty-commits` | BooleanOptional | True | Commit dirty state |
| `--show-diffs` | Boolean | False | Show diffs when committing |

### Commit Message Format

From `aider/prompts.py:10-26`, Aider generates Conventional Commits format messages:

- Structure: `<type>: <description>`
- Types: fix, feat, build, chore, ci, docs, style, refactor, perf, test
- Imperative mood required
- Maximum 72 characters

## Development Standards

### Python Compatibility
- Versions: 3.9, 3.10, 3.11, 3.12
- No type hints used in codebase

### Code Style
- PEP 8 compliance
- Maximum line length: 100 characters
- Tools: `isort` for imports, `Black` for formatting
- Pre-commit hooks enforce style

### Testing
- Framework: pytest
- Location: `aider/tests/`
- Naming convention: `test_*.py`

## Dependencies

Key dependencies from `requirements/requirements-browser.txt`:

- `gitpython==3.1.46` - Git operations
- `streamlit` - Browser UI components
- `pandas==2.3.3` - Data handling
- `jinja2==3.1.6` - Templating

## Installation

```bash
python -m pip install aider-install
aider-install
```

## Usage Example

```bash
# DeepSeek
aider --model deepseek --api-key deepseek=<key>

# Claude 3.7 Sonnet  
aider --model sonnet --api-key anthropic=<key>

# o3-mini
aider --model o3-mini --api-key openai=<key>

---

---

## Doramagic 踩坑日志

项目：Aider-AI/aider

摘要：发现 21 个潜在踩坑项，其中 3 个为 high/blocking；最高优先级：安装坑 - 来源证据：Python 3.13 support。

## 1. 安装坑 · 来源证据：Python 3.13 support

- 严重度：high
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Python 3.13 support
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_d422c2c05bc34d938b82095b9b0b7131 | https://github.com/Aider-AI/aider/issues/3037 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 2. 配置坑 · 来源证据：benchmark.py uses `--read-model-settings` but main cli + docs say `--model-settings-file`

- 严重度：high
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：benchmark.py uses `--read-model-settings` but main cli + docs say `--model-settings-file`
- 对用户的影响：可能影响升级、迁移或版本选择。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_04ccacbfaff740caaa5ac6f5280521c8 | https://github.com/Aider-AI/aider/issues/5131 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 3. 安全/权限坑 · 来源证据：Zed Editor Support

- 严重度：high
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Zed Editor Support
- 对用户的影响：可能影响授权、密钥配置或安全边界。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_de9d553c32dc4238bb4601e547645020 | https://github.com/Aider-AI/aider/issues/851 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 4. 安装坑 · 来源证据：feat: Add --one-shot flag for sessionless single-prompt execution

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：feat: Add --one-shot flag for sessionless single-prompt execution
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_4434e2534a6d45e58141e326a1cd97f1 | https://github.com/Aider-AI/aider/issues/5143 | 来源类型 github_issue 暴露的待验证使用条件。

## 5. 配置坑 · 可能修改宿主 AI 配置

- 严重度：medium
- 证据强度：source_linked
- 发现：项目面向 Claude/Cursor/Codex/Gemini/OpenCode 等宿主，或安装命令涉及用户配置目录。
- 对用户的影响：安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。
- 建议检查：列出会写入的配置文件、目录和卸载/回滚步骤。
- 防护动作：涉及宿主配置目录时必须给回滚路径，不能只给安装命令。
- 证据：capability.host_targets | github_repo:638629097 | https://github.com/Aider-AI/aider | host_targets=claude, chatgpt

## 6. 配置坑 · 来源证据：Uncaught NotImplementedError in pathlib.py line 1090

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Uncaught NotImplementedError in pathlib.py line 1090
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_4a2e6220201a4896920a22c45da17ae4 | https://github.com/Aider-AI/aider/issues/5145 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 7. 配置坑 · 来源证据：Uncaught OSError in _win32_console.py line 403

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Uncaught OSError in _win32_console.py line 403
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_f4f7880f667f4a52b7ad9b82e7a4acd2 | https://github.com/Aider-AI/aider/issues/5117 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 8. 配置坑 · 来源证据：Uncaught OSError in pathlib.py line 1222

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Uncaught OSError in pathlib.py line 1222
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_7f5383bfd86147d0929d2366e5b3044c | https://github.com/Aider-AI/aider/issues/5130 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 9. 配置坑 · 来源证据：Uncaught QueryError in repomap.py line 302

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Uncaught QueryError in repomap.py line 302
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_64f88b21f5fd4baa94c7e340b7006423 | https://github.com/Aider-AI/aider/issues/5133 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 10. 配置坑 · 来源证据：git repo corrupted

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：git repo corrupted
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_3cf7b9ede88e4598bacb2a1c5f7cd847 | https://github.com/Aider-AI/aider/issues/2734 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 11. 能力坑 · 能力判断依赖假设

- 严重度：medium
- 证据强度：source_linked
- 发现：README/documentation is current enough for a first validation pass.
- 对用户的影响：假设不成立时，用户拿不到承诺的能力。
- 建议检查：将假设转成下游验证清单。
- 防护动作：假设必须转成验证项；没有验证结果前不能写成事实。
- 证据：capability.assumptions | github_repo:638629097 | https://github.com/Aider-AI/aider | README/documentation is current enough for a first validation pass.

## 12. 维护坑 · 维护活跃度未知

- 严重度：medium
- 证据强度：source_linked
- 发现：未记录 last_activity_observed。
- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。
- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。
- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。
- 证据：evidence.maintainer_signals | github_repo:638629097 | https://github.com/Aider-AI/aider | last_activity_observed missing

## 13. 安全/权限坑 · 下游验证发现风险项

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 对用户的影响：下游已经要求复核，不能在页面中弱化。
- 建议检查：进入安全/权限治理复核队列。
- 防护动作：下游风险存在时必须保持 review/recommendation 降级。
- 证据：downstream_validation.risk_items | github_repo:638629097 | https://github.com/Aider-AI/aider | no_demo; severity=medium

## 14. 安全/权限坑 · 存在评分风险

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 对用户的影响：风险会影响是否适合普通用户安装。
- 建议检查：把风险写入边界卡，并确认是否需要人工复核。
- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。
- 证据：risks.scoring_risks | github_repo:638629097 | https://github.com/Aider-AI/aider | no_demo; severity=medium

## 15. 安全/权限坑 · 来源证据：Proposal: optional pre-commit safety scan with Agent Threat Rules

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Proposal: optional pre-commit safety scan with Agent Threat Rules
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_4fa6fdcc672345afa8c3ff5a452863aa | https://github.com/Aider-AI/aider/issues/5121 | 来源类型 github_issue 暴露的待验证使用条件。

## 16. 安全/权限坑 · 来源证据：Uncaught OSError in pathlib.py line 840

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Uncaught OSError in pathlib.py line 840
- 对用户的影响：可能影响授权、密钥配置或安全边界。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_8e8437da35794c5bb2c53e2b08db3a70 | https://github.com/Aider-AI/aider/issues/5114 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 17. 安全/权限坑 · 来源证据：security: bump GitPython pin (CVE-2026-42215/42284/44243/44244)

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：security: bump GitPython pin (CVE-2026-42215/42284/44243/44244)
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_835507f71220443f8a484ae9e8888821 | https://github.com/Aider-AI/aider/issues/5139 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 18. 安全/权限坑 · 来源证据：security: bump Pillow pin (CVE-2026-42311)

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：security: bump Pillow pin (CVE-2026-42311)
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_842489bdf17244c29e0ea620f9499bde | https://github.com/Aider-AI/aider/issues/5140 | 来源类型 github_issue 暴露的待验证使用条件。

## 19. 安全/权限坑 · 来源证据：security: bump urllib3 pin (CVE-2026-44431)

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：security: bump urllib3 pin (CVE-2026-44431)
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_76fb6fb4c31b436fbe62c89100c8084f | https://github.com/Aider-AI/aider/issues/5141 | 来源类型 github_issue 暴露的待验证使用条件。

## 20. 维护坑 · issue/PR 响应质量未知

- 严重度：low
- 证据强度：source_linked
- 发现：issue_or_pr_quality=unknown。
- 对用户的影响：用户无法判断遇到问题后是否有人维护。
- 建议检查：抽样最近 issue/PR，判断是否长期无人处理。
- 防护动作：issue/PR 响应未知时，必须提示维护风险。
- 证据：evidence.maintainer_signals | github_repo:638629097 | https://github.com/Aider-AI/aider | issue_or_pr_quality=unknown

## 21. 维护坑 · 发布节奏不明确

- 严重度：low
- 证据强度：source_linked
- 发现：release_recency=unknown。
- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。
- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。
- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。
- 证据：evidence.maintainer_signals | github_repo:638629097 | https://github.com/Aider-AI/aider | release_recency=unknown

<!-- canonical_name: Aider-AI/aider; human_manual_source: deepwiki_human_wiki -->
