You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
▲ Explain the major function of the project and how it works by referencing the most important and relevant code snippets.
The project, paul-gauthier/aider, is an open-source AI pair programming tool that allows users to collaborate with LLMs (Large Language Models) to edit code in their local git repositories. It provides a command-line interface and an experimental browser-based UI.
Here's how it works:
Initialization:
The user launches aider with optional arguments specifying the files to edit, the LLM to use, and other settings.
The tool checks for a git repository and sets up the environment.
It loads model settings and metadata from .aider.model.settings.yml and .aider.model.metadata.json files, respectively.
It creates a RepoMap to provide context about the repository to the LLM. This map includes summaries of files and important identifiers.
The user can continue to provide instructions, ask questions, or use commands to manage the chat session.
aider continues to loop through these steps, providing a continuous interactive experience.
aider is a powerful tool that leverages the capabilities of LLMs to assist developers in their coding tasks. It provides a user-friendly interface, handles code editing and version control, and offers additional features like linting and testing. This makes it a valuable tool for anyone looking to enhance their coding workflow with the power of AI.
▲ How does the LLM understand the entire given repository?
The LLM doesn't directly understand the entire repository in the way a human programmer does. Instead, aider provides a condensed representation of the repository, called a "repo map," to the LLM. This map helps the LLM grasp the overall structure and key elements of the codebase.
Here's how the repo map works:
Building the Repo Map:
aider uses tree-sitter (previously ctags) to analyze the source code files in the repository.
tree-sitter parses the code into an Abstract Syntax Tree (AST), which represents the code's structure.
It extracts important identifiers like function and class names, their definitions, and references to them within the code.
Prioritizing Information:
The extracted information is then used to build a graph where each node represents a file in the repository.
Edges between nodes represent dependencies between files, based on references to identifiers defined in other files.
A graph ranking algorithm (PageRank) is applied to this graph to determine the most important files and identifiers.
Creating a Concise Representation:
aider selects the most important files and identifiers based on their PageRank scores and the user-defined token budget (--map-tokens).
It then generates a concise representation of the repo map, including summaries of the selected files and their key identifiers.
Providing Context to the LLM:
The repo map is included in the prompt sent to the LLM along with the user's request.
This provides the LLM with a high-level understanding of the repository's structure and key elements.
Example:
Imagine a repository with a utils.py file containing utility functions and a main.py file using those functions. The repo map might look like this:
utils.py:
function
get_data(url)
process_data(data)
main.py:
function
main()
# ... uses get_data and process_data from utils.py
This map helps the LLM understand that main.py depends on functions defined in utils.py. If the user asks to modify main.py, the LLM can use this information to understand the context and potentially suggest edits that involve functions from utils.py.
Key Points:
The repo map is a simplified representation of the repository, not a complete understanding.
It focuses on the most important elements and dependencies, making it efficient for the LLM to process.
It helps the LLM understand the context of the code being edited, improving the quality of its suggestions.
The repo map is dynamically adjusted based on the user's requests and the current chat history, ensuring that the most relevant information is provided.
By providing this concise and context-aware representation of the repository, aider helps the LLM understand the codebase and generate more accurate and relevant code edits.
# Contributing to the Project
We welcome contributions in the form of bug reports, feature requests,
and pull requests (PRs). This document describes how you can
contribute.
## Bug Reports and Feature Requests
Please submit bug reports and feature requests as GitHub issues. This
helps us to keep track of them and discuss potential solutions or
enhancements.
## LLM Benchmark Results
Contributions of
[LLM benchmark results](https://aider.chat/docs/leaderboards/)
are welcome!
See the
[benchmark README](https://github.com/paul-gauthier/aider/blob/main/benchmark/README.md)
for information on running aider's code editing benchmarks.
Submit results by opening a PR with edits to the
[benchmark results data files](https://github.com/paul-gauthier/aider/blob/main/_data/).
## Pull Requests
We appreciate your pull requests. For small changes, feel free to
submit a PR directly. If you are considering a large or significant
change, please discuss it in a GitHub issue before submitting the
PR. This will save both you and the maintainers time, and it helps to
ensure that your contributions can be integrated smoothly.
## Licensing
By contributing to this project, you agree that your contributions
will be licensed under the Apache License 2.0. Additionally, you
understand and agree that contributions may be subject to a different
license, should the project maintainers decide to change the licensing
terms.
## Setting up a Development Environment### Clone the Repository
### Create a Virtual Environment
It is recommended to create a virtual environment outside of the repository to keep your development environment isolated.
#### Using `venv` (Python 3.9 and later)
python -m venv /path/to/venv
#### Using `virtualenv` (for older Python versions)
pip install virtualenv
virtualenv /path/to/venv
### Activate the Virtual Environment
#### On Windows
/path/to/venv/Scripts/activate
#### On Unix or macOS
source /path/to/venv/bin/activate
### Install the Project in Editable Mode
This step allows you to make changes to the source code and have them take effect immediately without reinstalling the package.
pip install -e .
### Install the Project Dependencies
pip install -r requirements.txt
For development, at least install the development dependencies:
pip install -r requirements/requirements-dev.txt
Consider installing other optional dependencies from the `requirements/` directory, if your development work needs them.
Note that these dependency files are generated by `./scripts/pip-compile.sh` and then committed. See [Managing Dependencies](#managing-dependencies).
### Install Pre-commit Hooks (Optional)
The project uses pre-commit hooks for code formatting and linting. If you want to install and use these hooks, run:
pre-commit install
This will automatically run the pre-commit hooks when you commit changes to the repository.
Now you should have a fully functional development environment for the Aider project. You can start making changes, running tests, and contributing to the project.
### Handy Opinionated Setup Commands for MacOS / Linux
Here's an example of following the setup instructions above, for your copy/paste pleasure if your system works the same. Start in the project directory.
### Running Tests
Just run `pytest`.
### Building the Docker Image
The project includes a `Dockerfile` for building a Docker image. You can build the image by running:
docker build -t aider -f docker/Dockerfile .
### Building the Documentation
The project's documentation is built using Jekyll and hosted on GitHub Pages. To build the documentation locally, follow these steps:
1. Install Ruby and Bundler (if not already installed).
2. Navigate to the `aider/website` directory.
3. Install the required gems:
bundle install
4. Build the documentation:
bundle exec jekyll build
The built documentation will be available in the `aider/website/_site` directory.
## Coding Standards
### Python Compatibility
Aider supports Python versions 3.9, 3.10, 3.11, and 3.12. When contributing code, ensure compatibility with these supported Python versions.
### Code Style
The project follows the [PEP 8](https://www.python.org/dev/peps/pep-0008/) style guide for Python code, with a maximum line length of 100 characters. Additionally, the project uses [isort](https://pycqa.github.io/isort/) and [Black](https://black.readthedocs.io/en/stable/) for sorting imports and code formatting, respectively. Please install the pre-commit hooks to automatically format your code before committing changes.
### No Type Hints
The project does not use type hints.
### Testing
The project uses [pytest](https://docs.pytest.org/en/latest/) for running unit tests. The test files are located in the `aider/tests` directory and follow the naming convention `test_*.py`.
#### Running Tests
To run the entire test suite, use the following command from the project root directory:
pytest
You can also run specific test files or test cases by providing the file path or test name:
#### Continuous Integration
The project uses GitHub Actions for continuous integration. The testing workflows are defined in the following files:
- `.github/workflows/ubuntu-tests.yml`: Runs tests on Ubuntu for Python versions 3.9 through 3.12.
- `.github/workflows/windows-tests.yml`: Runs that on Windows
These workflows are triggered on push and pull request events to the `main` branch, ignoring changes to the `aider/website/**` and `README.md` files.
#### Docker Build and Test
The `.github/workflows/docker-build-test.yml` workflow is used to build a Docker image for the project on every push or pull request event to the `main` branch. It checks out the code, sets up Docker, logs in to DockerHub, and then builds the Docker image without pushing it to the registry.
#### Writing Tests
When contributing new features or making changes to existing code, ensure that you write appropriate tests to maintain code coverage. Follow the existing patterns and naming conventions used in the `aider/tests` directory.
If you need to mock or create test data, consider adding it to the test files or creating separate fixtures or utility functions within the `aider/tests` directory.
#### Test Requirements
The project uses `pytest` as the testing framework, which is installed as a development dependency. To install the development dependencies, run the following command:
pip install -r requirements-dev.txt
### Managing Dependencies
When introducing new dependencies, make sure to add them to the appropriate `requirements.in` file (e.g., `requirements.in` for main dependencies, `requirements-dev.in` for development dependencies). Then, run the following commands to update the corresponding `requirements.txt` file:
pip install pip-tools
./scripts/pip-compile.sh
You can also pass one argument to `pip-compile.sh`, which will flow through to `pip-compile`. For example:
./scripts/pip-compile.sh --upgrade
### Pre-commit Hooks
The project uses [pre-commit](https://pre-commit.com/) hooks to automatically format code, lint, and run other checks before committing changes. After cloning the repository, run the following command to set up the pre-commit hooks:
pre-commit install
pre-commit will then run automatically on each `git commit` command. You can use the following command line to run pre-commit manually:
pre-commit run --all-files
paul-gauthier/aider/blob/main/HISTORY.md:
# Release history### Aider v0.50.0- Infinite output for DeepSeek Coder, Mistral models in addition to Anthropic's models.
- New `--deepseek` switch to use DeepSeek Coder.
- DeepSeek Coder uses 8k token output.
- New `--chat-mode <mode>` switch to launch in ask/help/code modes.
- New `/code <message>` command request a code edit while in `ask` mode.
- Web scraper is more robust if page never idles.
- Improved token and cost reporting for infinite output.
- Improvements and bug fixes for `/read` only files.
- Switched from `setup.py` to `pyproject.toml`, by @branchvincent.
- Bug fix to persist files added during `/ask`.
- Bug fix for chat history size in `/tokens`.
- Aider wrote 66% of the code in this release.
### Aider v0.49.1- Bugfix to `/help`.
### Aider v0.49.0- Add read-only files to the chat context with `/read` and `--read`, including from outside the git repo.
-`/diff` now shows diffs of all changes resulting from your request, including lint and test fixes.
- New `/clipboard` command to paste images or text from the clipboard, replaces `/add-clipboard-image`.
- Now shows the markdown scraped when you add a url with `/web`.
- When [scripting aider](https://aider.chat/docs/scripting.html) messages can now contain in-chat `/` commands.
- Aider in docker image now suggests the correct command to update to latest version.
- Improved retries on API errors (was easy to test during Sonnet outage).
- Added `--mini` for `gpt-4o-mini`.
- Bugfix to keep session cost accurate when using `/ask` and `/help`.
- Performance improvements for repo map calculation.
-`/tokens` now shows the active model.
- Enhanced commit message attribution options:
- New `--attribute-commit-message-author` to prefix commit messages with 'aider: ' if aider authored the changes, replaces `--attribute-commit-message`.
- New `--attribute-commit-message-committer` to prefix all commit messages with 'aider: '.
- Aider wrote 61% of the code in this release.
### Aider v0.48.1- Added `openai/gpt-4o-2024-08-06`.
- Worked around litellm bug that removes OpenRouter app headers when using `extra_headers`.
- Improved progress indication during repo map processing.
- Corrected instructions for upgrading the docker container to latest aider version.
- Removed obsolete 16k token limit on commit diffs, use per-model limits.
### Aider v0.48.0- Performance improvements for large/mono repos.
- Added `--subtree-only` to limit aider to current directory subtree.
- Should help with large/mono repo performance.
- New `/add-clipboard-image` to add images to the chat from your clipboard.
- Use `--map-tokens 1024` to use repo map with any model.
- Support for Sonnet's 8k output window.
-[Aider already supported infinite output from Sonnet.](https://aider.chat/2024/07/01/sonnet-not-lazy.html)- Workaround litellm bug for retrying API server errors.
- Upgraded dependencies, to pick up litellm bug fixes.
- Aider wrote 44% of the code in this release.
### Aider v0.47.1- Improvements to conventional commits prompting.
### Aider v0.47.0-[Commit message](https://aider.chat/docs/git.html#commit-messages) improvements:
- Added Conventional Commits guidelines to commit message prompt.
- Added `--commit-prompt` to customize the commit message prompt.
- Added strong model as a fallback for commit messages (and chat summaries).
-[Linting](https://aider.chat/docs/usage/lint-test.html) improvements:
- Ask before fixing lint errors.
- Improved performance of `--lint` on all dirty files in repo.
- Improved lint flow, now doing code edit auto-commit before linting.
- Bugfix to properly handle subprocess encodings (also for `/run`).
- Improved [docker support](https://aider.chat/docs/install/docker.html):
- Resolved permission issues when using `docker run --user xxx`.
- New `paulgauthier/aider-full` docker image, which includes all extras.
- Switching to code and ask mode no longer summarizes the chat history.
- Added graph of aider's contribution to each release.
- Generic auto-completions are provided for `/commands` without a completion override.
- Fixed broken OCaml tags file.
- Bugfix in `/run` add to chat approval logic.
- Aider wrote 58% of the code in this release.
### Aider v0.46.1- Downgraded stray numpy dependency back to 1.26.4.
### Aider v0.46.0- New `/ask <question>` command to ask about your code, without making any edits.
- New `/chat-mode <mode>` command to switch chat modes:
- ask: Ask questions about your code without making any changes.
- code: Ask for changes to your code (using the best edit format).
- help: Get help about using aider (usage, config, troubleshoot).
- Add `file: CONVENTIONS.md` to `.aider.conf.yml` to always load a specific file.
- Or `file: [file1, file2, file3]` to always load multiple files.
- Enhanced token usage and cost reporting. Now works when streaming too.
- Filename auto-complete for `/add` and `/drop` is now case-insensitive.
- Commit message improvements:
- Updated commit message prompt to use imperative tense.
- Fall back to main model if weak model is unable to generate a commit message.
- Stop aider from asking to add the same url to the chat multiple times.
- Updates and fixes to `--no-verify-ssl`:
- Fixed regression that broke it in v0.42.0.
- Disables SSL certificate verification when `/web` scrapes websites.
- Improved error handling and reporting in `/web` scraping functionality
- Fixed syntax error in Elm's tree-sitter scm file (by @cjoach).
- Handle UnicodeEncodeError when streaming text to the terminal.
- Updated dependencies to latest versions.
- Aider wrote 45% of the code in this release.
### Aider v0.45.1- Use 4o-mini as the weak model wherever 3.5-turbo was used.
### Aider v0.45.0- GPT-4o mini scores similar to the original GPT 3.5, using whole edit format.
- Aider is better at offering to add files to the chat on Windows.
- Bugfix corner cases for `/undo` with new files or new repos.
- Now shows last 4 characters of API keys in `--verbose` output.
- Bugfix to precedence of multiple `.env` files.
- Bugfix to gracefully handle HTTP errors when installing pandoc.
- Aider wrote 42% of the code in this release.
### Aider v0.44.0- Default pip install size reduced by 3-12x.
- Added 3 package extras, which aider will offer to install when needed:
-`aider-chat[help]`-`aider-chat[browser]`-`aider-chat[playwright]`- Improved regex for detecting URLs in user chat messages.
- Bugfix to globbing logic when absolute paths are included in `/add`.
- Simplified output of `--models`.
- The `--check-update` switch was renamed to `--just-check-updated`.
- The `--skip-check-update` switch was renamed to `--[no-]check-update`.
- Aider wrote 29% of the code in this release (157/547 lines).
### Aider v0.43.4- Added scipy back to main requirements.txt.
### Aider v0.43.3- Added build-essentials back to main Dockerfile.
### Aider v0.43.2- Moved HuggingFace embeddings deps into [hf-embed] extra.
- Added [dev] extra.
### Aider v0.43.1- Replace the torch requirement with the CPU only version, because the GPU versions are huge.
### Aider v0.43.0- Use `/help <question>` to [ask for help about using aider](https://aider.chat/docs/troubleshooting/support.html), customizing settings, troubleshooting, using LLMs, etc.
- Allow multiple use of `/undo`.
- All config/env/yml/json files now load from home, git root, cwd and named command line switch.
- New `$HOME/.aider/caches` dir for app-wide expendable caches.
- Default `--model-settings-file` is now `.aider.model.settings.yml`.
- Default `--model-metadata-file` is now `.aider.model.metadata.json`.
- Bugfix affecting launch with `--no-git`.
- Aider wrote 9% of the 424 lines edited in this release.
### Aider v0.42.0- Performance release:
- 5X faster launch!
- Faster auto-complete in large git repos (users report ~100X speedup)!
### Aider v0.41.0-[Allow Claude 3.5 Sonnet to stream back >4k tokens!](https://aider.chat/2024/07/01/sonnet-not-lazy.html)- It is the first model capable of writing such large coherent, useful code edits.
- Do large refactors or generate multiple files of new code in one go.
- Aider now uses `claude-3-5-sonnet-20240620` by default if `ANTHROPIC_API_KEY` is set in the environment.
-[Enabled image support](https://aider.chat/docs/usage/images-urls.html) for 3.5 Sonnet and for GPT-4o & 3.5 Sonnet via OpenRouter (by @yamitzky).
- Added `--attribute-commit-message` to prefix aider's commit messages with "aider:".
- Fixed regression in quality of one-line commit messages.
- Automatically retry on Anthropic `overloaded_error`.
- Bumped dependency versions.
### Aider v0.40.6- Fixed `/undo` so it works regardless of `--attribute` settings.
### Aider v0.40.5- Bump versions to pickup latest litellm to fix streaming issue with Gemini
-https://github.com/BerriAI/litellm/issues/4408### Aider v0.40.1- Improved context awareness of repomap.
- Restored proper `--help` functionality.
### Aider v0.40.0- Improved prompting to discourage Sonnet from wasting tokens emitting unchanging code (#705).
- Improved error info for token limit errors.
- Options to suppress adding "(aider)" to the [git author and committer names](https://aider.chat/docs/git.html#commit-attribution).
- Use `--model-settings-file` to customize per-model settings, like use of repo-map (by @caseymcc).
- Improved invocation of flake8 linter for python code.
### Aider v0.39.0- Use `--sonnet` for Claude 3.5 Sonnet, which is the top model on [aider's LLM code editing leaderboard](https://aider.chat/docs/leaderboards/#claude-35-sonnet-takes-the-top-spot).
- All `AIDER_xxx` environment variables can now be set in `.env` (by @jpshack-at-palomar).
- Use `--llm-history-file` to log raw messages sent to the LLM (by @daniel-vainsencher).
- Commit messages are no longer prefixed with "aider:". Instead the git author and committer names have "(aider)" added.
### Aider v0.38.0- Use `--vim` for [vim keybindings](https://aider.chat/docs/usage/commands.html#vi) in the chat.
-[Add LLM metadata](https://aider.chat/docs/llms/warnings.html#specifying-context-window-size-and-token-costs) via `.aider.models.json` file (by @caseymcc).
- More detailed [error messages on token limit errors](https://aider.chat/docs/troubleshooting/token-limits.html).
- Single line commit messages, without the recent chat messages.
- Ensure `--commit --dry-run` does nothing.
- Have playwright wait for idle network to better scrape js sites.
- Documentation updates, moved into website/ subdir.
- Moved tests/ into aider/tests/.
### Aider v0.37.0- Repo map is now optimized based on text of chat history as well as files added to chat.
- Improved prompts when no files have been added to chat to solicit LLM file suggestions.
- Aider will notice if you paste a URL into the chat, and offer to scrape it.
- Performance improvements the repo map, especially in large repos.
- Aider will not offer to add bare filenames like `make` or `run` which may just be words.
- Properly override `GIT_EDITOR` env for commits if it is already set.
- Detect supported audio sample rates for `/voice`.
- Other small bug fixes.
### Aider v0.36.0-[Aider can now lint your code and fix any errors](https://aider.chat/2024/05/22/linting.html).
- Aider automatically lints and fixes after every LLM edit.
- You can manually lint-and-fix files with `/lint` in the chat or `--lint` on the command line.
- Aider includes built in basic linters for all supported tree-sitter languages.
- You can also configure aider to use your preferred linter with `--lint-cmd`.
- Aider has additional support for running tests and fixing problems.
- Configure your testing command with `--test-cmd`.
- Run tests with `/test` or from the command line with `--test`.
- Aider will automatically attempt to fix any test failures.
### Aider v0.35.0- Aider now uses GPT-4o by default.
- GPT-4o tops the [aider LLM code editing leaderboard](https://aider.chat/docs/leaderboards/) at 72.9%, versus 68.4% for Opus.
- GPT-4o takes second on [aider's refactoring leaderboard](https://aider.chat/docs/leaderboards/#code-refactoring-leaderboard) with 62.9%, versus Opus at 72.3%.
- Added `--restore-chat-history` to restore prior chat history on launch, so you can continue the last conversation.
- Improved reflection feedback to LLMs using the diff edit format.
- Improved retries on `httpx` errors.
### Aider v0.34.0- Updated prompting to use more natural phrasing about files, the git repo, etc. Removed reliance on read-write/read-only terminology.
- Refactored prompting to unify some phrasing across edit formats.
- Enhanced the canned assistant responses used in prompts.
- Added explicit model settings for `openrouter/anthropic/claude-3-opus`, `gpt-3.5-turbo`- Added `--show-prompts` debug switch.
- Bugfix: catch and retry on all litellm exceptions.
### Aider v0.33.0- Added native support for [Deepseek models](https://aider.chat/docs/llms.html#deepseek) using `DEEPSEEK_API_KEY` and `deepseek/deepseek-chat`, etc rather than as a generic OpenAI compatible API.
### Aider v0.32.0-[Aider LLM code editing leaderboards](https://aider.chat/docs/leaderboards/) that rank popular models according to their ability to edit code.
- Leaderboards include GPT-3.5/4 Turbo, Opus, Sonnet, Gemini 1.5 Pro, Llama 3, Deepseek Coder & Command-R+.
- Gemini 1.5 Pro now defaults to a new diff-style edit format (diff-fenced), enabling it to work better with larger code bases.
- Support for Deepseek-V2, via more a flexible config of system messages in the diff edit format.
- Improved retry handling on errors from model APIs.
- Benchmark outputs results in YAML, compatible with leaderboard.
### Aider v0.31.0-[Aider is now also AI pair programming in your browser!](https://aider.chat/2024/05/02/browser.html) Use the `--browser` switch to launch an experimental browser based version of aider.
- Switch models during the chat with `/model <name>` and search the list of available models with `/models <query>`.
### Aider v0.30.1- Adding missing `google-generativeai` dependency
### Aider v0.30.0- Added [Gemini 1.5 Pro](https://aider.chat/docs/llms.html#free-models) as a recommended free model.
- Allow repo map for "whole" edit format.
- Added `--models <MODEL-NAME>` to search the available models.
- Added `--no-show-model-warnings` to silence model warnings.
### Aider v0.29.2- Improved [model warnings](https://aider.chat/docs/llms.html#model-warnings) for unknown or unfamiliar models
### Aider v0.29.1- Added better support for groq/llama3-70b-8192
### Aider v0.29.0- Added support for [directly connecting to Anthropic, Cohere, Gemini and many other LLM providers](https://aider.chat/docs/llms.html).
- Added `--weak-model <model-name>` which allows you to specify which model to use for commit messages and chat history summarization.
- New command line switches for working with popular models:
-`--4-turbo-vision`-`--opus`-`--sonnet`-`--anthropic-api-key`- Improved "whole" and "diff" backends to better support [Cohere's free to use Command-R+ model](https://aider.chat/docs/llms.html#cohere).
- Allow `/add` of images from anywhere in the filesystem.
- Fixed crash when operating in a repo in a detached HEAD state.
- Fix: Use the same default model in CLI and python scripting.
### Aider v0.28.0- Added support for new `gpt-4-turbo-2024-04-09` and `gpt-4-turbo` models.
- Benchmarked at 61.7% on Exercism benchmark, comparable to `gpt-4-0613` and worse than the `gpt-4-preview-XXXX` models. See [recent Exercism benchmark results](https://aider.chat/2024/03/08/claude-3.html).
- Benchmarked at 34.1% on the refactoring/laziness benchmark, significantly worse than the `gpt-4-preview-XXXX` models. See [recent refactor bencmark results](https://aider.chat/2024/01/25/benchmarks-0125.html).
- Aider continues to default to `gpt-4-1106-preview` as it performs best on both benchmarks, and significantly better on the refactoring/laziness benchmark.
### Aider v0.27.0- Improved repomap support for typescript, by @ryanfreckleton.
- Bugfix: Only /undo the files which were part of the last commit, don't stomp other dirty files
- Bugfix: Show clear error message when OpenAI API key is not set.
- Bugfix: Catch error for obscure languages without tags.scm file.
### Aider v0.26.1- Fixed bug affecting parsing of git config in some environments.
### Aider v0.26.0- Use GPT-4 Turbo by default.
- Added `-3` and `-4` switches to use GPT 3.5 or GPT-4 (non-Turbo).
- Bug fix to avoid reflecting local git errors back to GPT.
- Improved logic for opening git repo on launch.
### Aider v0.25.0- Issue a warning if user adds too much code to the chat.
-https://aider.chat/docs/faq.html#how-can-i-add-all-the-files-to-the-chat- Vocally refuse to add files to the chat that match `.aiderignore`- Prevents bug where subsequent git commit of those files will fail.
- Added `--openai-organization-id` argument.
- Show the user a FAQ link if edits fail to apply.
- Made past articles part of https://aider.chat/blog/### Aider v0.24.1- Fixed bug with cost computations when --no-steam in effect
### Aider v0.24.0- New `/web <url>` command which scrapes the url, turns it into fairly clean markdown and adds it to the chat.
- Updated all OpenAI model names, pricing info
- Default GPT 3.5 model is now `gpt-3.5-turbo-0125`.
- Bugfix to the `!` alias for `/run`.
### Aider v0.23.0- Added support for `--model gpt-4-0125-preview` and OpenAI's alias `--model gpt-4-turbo-preview`. The `--4turbo` switch remains an alias for `--model gpt-4-1106-preview` at this time.
- New `/test` command that runs a command and adds the output to the chat on non-zero exit status.
- Improved streaming of markdown to the terminal.
- Added `/quit` as alias for `/exit`.
- Added `--skip-check-update` to skip checking for the update on launch.
- Added `--openrouter` as a shortcut for `--openai-api-base https://openrouter.ai/api/v1`- Fixed bug preventing use of env vars `OPENAI_API_BASE, OPENAI_API_TYPE, OPENAI_API_VERSION, OPENAI_API_DEPLOYMENT_ID`.
### Aider v0.22.0- Improvements for unified diff editing format.
- Added ! as an alias for /run.
- Autocomplete for /add and /drop now properly quotes filenames with spaces.
- The /undo command asks GPT not to just retry reverted edit.
### Aider v0.21.1- Bugfix for unified diff editing format.
- Added --4turbo and --4 aliases for --4-turbo.
### Aider v0.21.0- Support for python 3.12.
- Improvements to unified diff editing format.
- New `--check-update` arg to check if updates are available and exit with status code.
### Aider v0.20.0- Add images to the chat to automatically use GPT-4 Vision, by @joshuavial- Bugfixes:
- Improved unicode encoding for `/run` command output, by @ctoth- Prevent false auto-commits on Windows, by @ctoth### Aider v0.19.1- Removed stray debug output.
### Aider v0.19.0-[Significantly reduced "lazy" coding from GPT-4 Turbo due to new unified diff edit format](https://aider.chat/docs/unified-diffs.html)- Score improves from 20% to 61% on new "laziness benchmark".
- Aider now uses unified diffs by default for `gpt-4-1106-preview`.
- New `--4-turbo` command line switch as a shortcut for `--model gpt-4-1106-preview`.
### Aider v0.18.1- Upgraded to new openai python client v1.3.7.
### Aider v0.18.0- Improved prompting for both GPT-4 and GPT-4 Turbo.
- Far fewer edit errors from GPT-4 Turbo (`gpt-4-1106-preview`).
- Significantly better benchmark results from the June GPT-4 (`gpt-4-0613`). Performance leaps from 47%/64% up to 51%/71%.
- Fixed bug where in-chat files were marked as both read-only and ready-write, sometimes confusing GPT.
- Fixed bug to properly handle repos with submodules.
### Aider v0.17.0- Support for OpenAI's new 11/06 models:
- gpt-4-1106-preview with 128k context window
- gpt-3.5-turbo-1106 with 16k context window
-[Benchmarks for OpenAI's new 11/06 models](https://aider.chat/docs/benchmarks-1106.html)- Streamlined [API for scripting aider, added docs](https://aider.chat/docs/faq.html#can-i-script-aider)- Ask for more concise SEARCH/REPLACE blocks. [Benchmarked](https://aider.chat/docs/benchmarks.html) at 63.9%, no regression.
- Improved repo-map support for elisp.
- Fixed crash bug when `/add` used on file matching `.gitignore`- Fixed misc bugs to catch and handle unicode decoding errors.
### Aider v0.16.3- Fixed repo-map support for C#.
### Aider v0.16.2- Fixed docker image.
### Aider v0.16.1- Updated tree-sitter dependencies to streamline the pip install process
### Aider v0.16.0-[Improved repository map using tree-sitter](https://aider.chat/docs/repomap.html)- Switched from "edit block" to "search/replace block", which reduced malformed edit blocks. [Benchmarked](https://aider.chat/docs/benchmarks.html) at 66.2%, no regression.
- Improved handling of malformed edit blocks targeting multiple edits to the same file. [Benchmarked](https://aider.chat/docs/benchmarks.html) at 65.4%, no regression.
- Bugfix to properly handle malformed `/add` wildcards.
### Aider v0.15.0- Added support for `.aiderignore` file, which instructs aider to ignore parts of the git repo.
- New `--commit` cmd line arg, which just commits all pending changes with a sensible commit message generated by gpt-3.5.
- Added universal ctags and multiple architectures to the [aider docker image](https://aider.chat/docs/install/docker.html)-`/run` and `/git` now accept full shell commands, like: `/run (cd subdir; ls)`- Restored missing `--encoding` cmd line switch.
### Aider v0.14.2- Easily [run aider from a docker image](https://aider.chat/docs/install/docker.html)- Fixed bug with chat history summarization.
- Fixed bug if `soundfile` package not available.
### Aider v0.14.1- /add and /drop handle absolute filenames and quoted filenames
- /add checks to be sure files are within the git repo (or root)
- If needed, warn users that in-chat file paths are all relative to the git repo
- Fixed /add bug in when aider launched in repo subdir
- Show models supported by api/key if requested model isn't available
### Aider v0.14.0-[Support for Claude2 and other LLMs via OpenRouter](https://aider.chat/docs/faq.html#accessing-other-llms-with-openrouter) by @joshuavial- Documentation for [running the aider benchmarking suite](https://github.com/paul-gauthier/aider/tree/main/benchmark)- Aider now requires Python >= 3.9
### Aider v0.13.0-[Only git commit dirty files that GPT tries to edit](https://aider.chat/docs/faq.html#how-did-v0130-change-git-usage)- Send chat history as prompt/context for Whisper voice transcription
- Added `--voice-language` switch to constrain `/voice` to transcribe to a specific language
- Late-bind importing `sounddevice`, as it was slowing down aider startup
- Improved --foo/--no-foo switch handling for command line and yml config settings
### Aider v0.12.0-[Voice-to-code](https://aider.chat/docs/usage/voice.html) support, which allows you to code with your voice.
- Fixed bug where /diff was causing crash.
- Improved prompting for gpt-4, refactor of editblock coder.
-[Benchmarked](https://aider.chat/docs/benchmarks.html) at 63.2% for gpt-4/diff, no regression.
### Aider v0.11.1- Added a progress bar when initially creating a repo map.
- Fixed bad commit message when adding new file to empty repo.
- Fixed corner case of pending chat history summarization when dirty committing.
- Fixed corner case of undefined `text` when using `--no-pretty`.
- Fixed /commit bug from repo refactor, added test coverage.
-[Benchmarked](https://aider.chat/docs/benchmarks.html) at 53.4% for gpt-3.5/whole (no regression).
### Aider v0.11.0- Automatically summarize chat history to avoid exhausting context window.
- More detail on dollar costs when running with `--no-stream`- Stronger GPT-3.5 prompt against skipping/eliding code in replies (51.9% [benchmark](https://aider.chat/docs/benchmarks.html), no regression)
- Defend against GPT-3.5 or non-OpenAI models suggesting filenames surrounded by asterisks.
- Refactored GitRepo code out of the Coder class.
### Aider v0.10.1- /add and /drop always use paths relative to the git root
- Encourage GPT to use language like "add files to the chat" to ask users for permission to edit them.
### Aider v0.10.0- Added `/git` command to run git from inside aider chats.
- Use Meta-ENTER (Esc+ENTER in some environments) to enter multiline chat messages.
- Create a `.gitignore` with `.aider*` to prevent users from accidentaly adding aider files to git.
- Check pypi for newer versions and notify user.
- Updated keyboard interrupt logic so that 2 ^C in 2 seconds always forces aider to exit.
- Provide GPT with detailed error if it makes a bad edit block, ask for a retry.
- Force `--no-pretty` if aider detects it is running inside a VSCode terminal.
-[Benchmarked](https://aider.chat/docs/benchmarks.html) at 64.7% for gpt-4/diff (no regression)
### Aider v0.9.0- Support for the OpenAI models in [Azure](https://aider.chat/docs/faq.html#azure)- Added `--show-repo-map`- Improved output when retrying connections to the OpenAI API
- Redacted api key from `--verbose` output
- Bugfix: recognize and add files in subdirectories mentioned by user or GPT
-[Benchmarked](https://aider.chat/docs/benchmarks.html) at 53.8% for gpt-3.5-turbo/whole (no regression)
### Aider v0.8.3- Added `--dark-mode` and `--light-mode` to select colors optimized for terminal background
- Install docs link to [NeoVim plugin](https://github.com/joshuavial/aider.nvim) by @joshuavial- Reorganized the `--help` output
- Bugfix/improvement to whole edit format, may improve coding editing for GPT-3.5
- Bugfix and tests around git filenames with unicode characters
- Bugfix so that aider throws an exception when OpenAI returns InvalidRequest
- Bugfix/improvement to /add and /drop to recurse selected directories
- Bugfix for live diff output when using "whole" edit format
### Aider v0.8.2- Disabled general availability of gpt-4 (it's rolling out, not 100% available yet)
### Aider v0.8.1- Ask to create a git repo if none found, to better track GPT's code changes
- Glob wildcards are now supported in `/add` and `/drop` commands
- Pass `--encoding` into ctags, require it to return `utf-8`- More robust handling of filepaths, to avoid 8.3 windows filenames
- Added [FAQ](https://aider.chat/docs/faq.html)- Marked GPT-4 as generally available
- Bugfix for live diffs of whole coder with missing filenames
- Bugfix for chats with multiple files
- Bugfix in editblock coder prompt
### Aider v0.8.0-[Benchmark comparing code editing in GPT-3.5 and GPT-4](https://aider.chat/docs/benchmarks.html)- Improved Windows support:
- Fixed bugs related to path separators in Windows
- Added a CI step to run all tests on Windows
- Improved handling of Unicode encoding/decoding
- Explicitly read/write text files with utf-8 encoding by default (mainly benefits Windows)
- Added `--encoding` switch to specify another encoding
- Gracefully handle decoding errors
- Added `--code-theme` switch to control the pygments styling of code blocks (by @kwmiebach)
- Better status messages explaining the reason when ctags is disabled
### Aider v0.7.2:- Fixed a bug to allow aider to edit files that contain triple backtick fences.
### Aider v0.7.1:- Fixed a bug in the display of streaming diffs in GPT-3.5 chats
### Aider v0.7.0:- Graceful handling of context window exhaustion, including helpful tips.
- Added `--message` to give GPT that one instruction and then exit after it replies and any edits are performed.
- Added `--no-stream` to disable streaming GPT responses.
- Non-streaming responses include token usage info.
- Enables display of cost info based on OpenAI advertised pricing.
- Coding competence benchmarking tool against suite of programming tasks based on Execism's python repo.
-https://github.com/exercism/python- Major refactor in preparation for supporting new function calls api.
- Initial implementation of a function based code editing backend for 3.5.
- Initial experiments show that using functions makes 3.5 less competent at coding.
- Limit automatic retries when GPT returns a malformed edit response.
### Aider v0.6.2* Support for `gpt-3.5-turbo-16k`, and all OpenAI chat models
* Improved ability to correct when gpt-4 omits leading whitespace in code edits
* Added `--openai-api-base` to support API proxies, etc.
### Aider v0.5.0- Added support for `gpt-3.5-turbo` and `gpt-4-32k`.
- Added `--map-tokens` to set a token budget for the repo map, along with a PageRank based algorithm for prioritizing which files and identifiers to include in the map.
- Added in-chat command `/tokens` to report on context window token usage.
- Added in-chat command `/clear` to clear the conversation history.
paul-gauthier/aider/blob/main/README.md:
<!-- Edit README.md, not index.md --># Aider is AI pair programming in your terminal
Aider lets you pair program with LLMs,
to edit code in your local git repository.
Start a new project or work with an existing git repo.
Aider works best with GPT-4o & Claude 3.5 Sonnet and can
[connect to almost any LLM](https://aider.chat/docs/llms.html).
<palign="center">
<img
src="https://aider.chat/assets/screencast.svg"
alt="aider screencast"
>
</p>
<palign="center">
<ahref="https://discord.gg/Tv2uQnR88V">
<img src="https://img.shields.io/badge/Join-Discord-blue.svg"/>
</a>
<ahref="https://aider.chat/docs/install.html">
<img src="https://img.shields.io/badge/Read-Docs-green.svg"/>
</a>
</p>
## Getting started<!--[[[cog# We can't "include" here.# Because this page is rendered by GitHub as the repo READMEcog.out(open("aider/website/_includes/get-started.md").read())]]]-->
You can get started quickly like this:
python -m pip install aider-chat
Change directory into a git repo
cd /to/your/git/repo
Work with Claude 3.5 Sonnet on your repo
export ANTHROPIC_API_KEY=your-key-goes-here
aider
Work with GPT-4o on your repo
export OPENAI_API_KEY=your-key-goes-here
aider
<!--[[[end]]]-->
See the
[installation instructions](https://aider.chat/docs/install.html)
and other
[documentation](https://aider.chat/docs/usage.html)
for more details.
## Features
- Run aider with the files you want to edit: `aider <file1> <file2> ...`
- Ask for changes:
- Add new features or test cases.
- Describe a bug.
- Paste in an error message or or GitHub issue URL.
- Refactor code.
- Update docs.
- Aider will edit your files to complete your request.
- Aider [automatically git commits](https://aider.chat/docs/git.html) changes with a sensible commit message.
- Aider works with [most popular languages](https://aider.chat/docs/languages.html): python, javascript, typescript, php, html, css, and more...
- Aider works best with GPT-4o & Claude 3.5 Sonnet and can [connect to almost any LLM](https://aider.chat/docs/llms.html).
- Aider can edit multiple files at once for complex requests.
- Aider uses a [map of your entire git repo](https://aider.chat/docs/repomap.html), which helps it work well in larger codebases.
- Edit files in your editor while chatting with aider,
and it will always use the latest version.
Pair program with AI.
- [Add images to the chat](https://aider.chat/docs/usage/images-urls.html) (GPT-4o, Claude 3.5 Sonnet, etc).
- [Add URLs to the chat](https://aider.chat/docs/usage/images-urls.html) and aider will read their content.
- [Code with your voice](https://aider.chat/docs/usage/voice.html).
## Top tier performance
[Aider has one of the top scores on SWE Bench](https://aider.chat/2024/06/02/main-swe-bench.html).
SWE Bench is a challenging software engineering benchmark where aider
solved *real* GitHub issues from popular open source
projects like django, scikitlearn, matplotlib, etc.
## More info
- [Documentation](https://aider.chat/)
- [Installation](https://aider.chat/docs/install.html)
- [Usage](https://aider.chat/docs/usage.html)
- [Tutorial videos](https://aider.chat/docs/usage/tutorials.html)
- [Connecting to LLMs](https://aider.chat/docs/llms.html)
- [Configuration](https://aider.chat/docs/config.html)
- [Troubleshooting](https://aider.chat/docs/troubleshooting.html)
- [LLM Leaderboards](https://aider.chat/docs/leaderboards/)
- [GitHub](https://github.com/paul-gauthier/aider)
- [Discord](https://discord.gg/Tv2uQnR88V)
- [Blog](https://aider.chat/blog/)
## Kind words from users
- *The best free open source AI coding assistant.* -- [IndyDevDan](https://youtu.be/YALpX8oOn78)
- *The best AI coding assistant so far.* -- [Matthew Berman](https://www.youtube.com/watch?v=df8afeb1FY8)
- *Aider ... has easily quadrupled my coding productivity.* -- [SOLAR_FIELDS](https://news.ycombinator.com/item?id=36212100)
- *It's a cool workflow... Aider's ergonomics are perfect for me.* -- [qup](https://news.ycombinator.com/item?id=38185326)
- *It's really like having your senior developer live right in your Git repo - truly amazing!* -- [rappster](https://github.com/paul-gauthier/aider/issues/124)
- *What an amazing tool. It's incredible.* -- [valyagolev](https://github.com/paul-gauthier/aider/issues/6#issue-1722897858)
- *Aider is such an astounding thing!* -- [cgrothaus](https://github.com/paul-gauthier/aider/issues/82#issuecomment-1631876700)
- *It was WAY faster than I would be getting off the ground and making the first few working versions.* -- [Daniel Feldman](https://twitter.com/d_feldman/status/1662295077387923456)
- *THANK YOU for Aider! It really feels like a glimpse into the future of coding.* -- [derwiki](https://news.ycombinator.com/item?id=38205643)
- *It's just amazing. It is freeing me to do things I felt were out my comfort zone before.* -- [Dougie](https://discord.com/channels/1131200896827654144/1174002618058678323/1174084556257775656)
- *This project is stellar.* -- [funkytaco](https://github.com/paul-gauthier/aider/issues/112#issuecomment-1637429008)
- *Amazing project, definitely the best AI coding assistant I've used.* -- [joshuavial](https://github.com/paul-gauthier/aider/issues/84)
- *I absolutely love using Aider ... It makes software development feel so much lighter as an experience.* -- [principalideal0](https://discord.com/channels/1131200896827654144/1133421607499595858/1229689636012691468)
- *I have been recovering from multiple shoulder surgeries ... and have used aider extensively. It has allowed me to continue productivity.* -- [codeninja](https://www.reddit.com/r/OpenAI/s/nmNwkHy1zG)
- *I am an aider addict. I'm getting so much more work done, but in less time.* -- [dandandan](https://discord.com/channels/1131200896827654144/1131200896827654149/1135913253483069470)
- *After wasting $100 on tokens trying to find something better, I'm back to Aider. It blows everything else out of the water hands down, there's no competition whatsoever.* -- [SystemSculpt](https://discord.com/channels/1131200896827654144/1131200896827654149/1178736602797846548)
- *Aider is amazing, coupled with Sonnet 3.5 it’s quite mind blowing.* -- [Josh Dingus](https://discord.com/channels/1131200896827654144/1133060684540813372/1262374225298198548)
- *Hands down, this is the best AI coding assistant tool so far.* -- [IndyDevDan](https://www.youtube.com/watch?v=MPYFPvxfGZs)
- *[Aider] changed my daily coding workflows. It's mind-blowing how a single Python application can change your life.* -- [maledorak](https://discord.com/channels/1131200896827654144/1131200896827654149/1258453375620747264)
- *Best agent for actual dev work in existing codebases.* -- [Nick Dobos](https://twitter.com/NickADobos/status/1690408967963652097?s=20)
paul-gauthier/aider/blob/main/aider/init.py:
__version__="0.50.1-dev"
paul-gauthier/aider/blob/main/aider/main.py:
from .mainimportmainif__name__=="__main__":
main()
paul-gauthier/aider/blob/main/aider/args.py:
#!/usr/bin/env pythonimportargparseimportosimportsysimportconfigargparsefromaiderimport__version__fromaider.args_formatterimport (
DotEnvFormatter,
MarkdownHelpFormatter,
YamlHelpFormatter,
)
from .dumpimportdump# noqa: F401defdefault_env_file(git_root):
returnos.path.join(git_root, ".env") ifgit_rootelse".env"defget_parser(default_config_files, git_root):
parser=configargparse.ArgumentParser(
description="aider is GPT powered coding in your terminal",
add_config_file_help=True,
default_config_files=default_config_files,
auto_env_var_prefix="AIDER_",
)
group=parser.add_argument_group("Main")
group.add_argument(
"files", metavar="FILE", nargs="*", help="files to edit with an LLM (optional)"
)
group.add_argument(
"--openai-api-key",
metavar="OPENAI_API_KEY",
env_var="OPENAI_API_KEY",
help="Specify the OpenAI API key",
)
group.add_argument(
"--anthropic-api-key",
metavar="ANTHROPIC_API_KEY",
env_var="ANTHROPIC_API_KEY",
help="Specify the Anthropic API key",
)
group.add_argument(
"--model",
metavar="MODEL",
default=None,
help="Specify the model to use for the main chat",
)
opus_model="claude-3-opus-20240229"group.add_argument(
"--opus",
action="store_const",
dest="model",
const=opus_model,
help=f"Use {opus_model} model for the main chat",
)
sonnet_model="claude-3-5-sonnet-20240620"group.add_argument(
"--sonnet",
action="store_const",
dest="model",
const=sonnet_model,
help=f"Use {sonnet_model} model for the main chat",
)
gpt_4_model="gpt-4-0613"group.add_argument(
"--4",
"-4",
action="store_const",
dest="model",
const=gpt_4_model,
help=f"Use {gpt_4_model} model for the main chat",
)
gpt_4o_model="gpt-4o"group.add_argument(
"--4o",
action="store_const",
dest="model",
const=gpt_4o_model,
help=f"Use {gpt_4o_model} model for the main chat",
)
gpt_4o_mini_model="gpt-4o-mini"group.add_argument(
"--mini",
action="store_const",
dest="model",
const=gpt_4o_mini_model,
help=f"Use {gpt_4o_mini_model} model for the main chat",
)
gpt_4_turbo_model="gpt-4-1106-preview"group.add_argument(
"--4-turbo",
action="store_const",
dest="model",
const=gpt_4_turbo_model,
help=f"Use {gpt_4_turbo_model} model for the main chat",
)
gpt_3_model_name="gpt-3.5-turbo"group.add_argument(
"--35turbo",
"--35-turbo",
"--3",
"-3",
action="store_const",
dest="model",
const=gpt_3_model_name,
help=f"Use {gpt_3_model_name} model for the main chat",
)
deepseek_model="deepseek/deepseek-coder"group.add_argument(
"--deepseek",
action="store_const",
dest="model",
const=deepseek_model,
help=f"Use {deepseek_model} model for the main chat",
)
##########group=parser.add_argument_group("Model Settings")
group.add_argument(
"--models",
metavar="MODEL",
help="List known models which match the (partial) MODEL name",
)
group.add_argument(
"--openai-api-base",
metavar="OPENAI_API_BASE",
env_var="OPENAI_API_BASE",
help="Specify the api base url",
)
group.add_argument(
"--openai-api-type",
metavar="OPENAI_API_TYPE",
env_var="OPENAI_API_TYPE",
help="Specify the api_type",
)
group.add_argument(
"--openai-api-version",
metavar="OPENAI_API_VERSION",
env_var="OPENAI_API_VERSION",
help="Specify the api_version",
)
group.add_argument(
"--openai-api-deployment-id",
metavar="OPENAI_API_DEPLOYMENT_ID",
env_var="OPENAI_API_DEPLOYMENT_ID",
help="Specify the deployment_id",
)
group.add_argument(
"--openai-organization-id",
metavar="OPENAI_ORGANIZATION_ID",
env_var="OPENAI_ORGANIZATION_ID",
help="Specify the OpenAI organization ID",
)
group.add_argument(
"--model-settings-file",
metavar="MODEL_SETTINGS_FILE",
default=".aider.model.settings.yml",
help="Specify a file with aider model settings for unknown models",
)
group.add_argument(
"--model-metadata-file",
metavar="MODEL_METADATA_FILE",
default=".aider.model.metadata.json",
help="Specify a file with context window and costs for unknown models",
)
group.add_argument(
"--verify-ssl",
action=argparse.BooleanOptionalAction,
default=True,
help="Verify the SSL cert when connecting to models (default: True)",
)
group.add_argument(
"--edit-format",
"--chat-mode",
metavar="EDIT_FORMAT",
default=None,
help="Specify what edit format the LLM should use (default depends on model)",
)
group.add_argument(
"--weak-model",
metavar="WEAK_MODEL",
default=None,
help=(
"Specify the model to use for commit messages and chat history summarization (default"" depends on --model)"
),
)
group.add_argument(
"--show-model-warnings",
action=argparse.BooleanOptionalAction,
default=True,
help="Only work with models that have meta-data available (default: True)",
)
group.add_argument(
"--map-tokens",
type=int,
default=None,
help="Max number of tokens to use for repo map, use 0 to disable (default: 1024)",
)
group.add_argument(
"--max-chat-history-tokens",
type=int,
default=None,
help=(
"Maximum number of tokens to use for chat history. If not specified, uses the model's"" max_chat_history_tokens."
),
)
# This is a duplicate of the argument in the preparser and is a no-op by this time of# argument parsing, but it's here so that the help is displayed as expected.group.add_argument(
"--env-file",
metavar="ENV_FILE",
default=default_env_file(git_root),
help="Specify the .env file to load (default: .env in git root)",
)
##########group=parser.add_argument_group("History Files")
default_input_history_file= (
os.path.join(git_root, ".aider.input.history") ifgit_rootelse".aider.input.history"
)
default_chat_history_file= (
os.path.join(git_root, ".aider.chat.history.md") ifgit_rootelse".aider.chat.history.md"
)
group.add_argument(
"--input-history-file",
metavar="INPUT_HISTORY_FILE",
default=default_input_history_file,
help=f"Specify the chat input history file (default: {default_input_history_file})",
)
group.add_argument(
"--chat-history-file",
metavar="CHAT_HISTORY_FILE",
default=default_chat_history_file,
help=f"Specify the chat history file (default: {default_chat_history_file})",
)
group.add_argument(
"--restore-chat-history",
action=argparse.BooleanOptionalAction,
default=False,
help="Restore the previous chat history messages (default: False)",
)
group.add_argument(
"--llm-history-file",
metavar="LLM_HISTORY_FILE",
default=None,
help="Log the conversation with the LLM to this file (for example, .aider.llm.history)",
)
##########group=parser.add_argument_group("Output Settings")
group.add_argument(
"--dark-mode",
action="store_true",
help="Use colors suitable for a dark terminal background (default: False)",
default=False,
)
group.add_argument(
"--light-mode",
action="store_true",
help="Use colors suitable for a light terminal background (default: False)",
default=False,
)
group.add_argument(
"--pretty",
action=argparse.BooleanOptionalAction,
default=True,
help="Enable/disable pretty, colorized output (default: True)",
)
group.add_argument(
"--stream",
action=argparse.BooleanOptionalAction,
default=True,
help="Enable/disable streaming responses (default: True)",
)
group.add_argument(
"--user-input-color",
default="#00cc00",
help="Set the color for user input (default: #00cc00)",
)
group.add_argument(
"--tool-output-color",
default=None,
help="Set the color for tool output (default: None)",
)
group.add_argument(
"--tool-error-color",
default="#FF2222",
help="Set the color for tool error messages (default: red)",
)
group.add_argument(
"--assistant-output-color",
default="#0088ff",
help="Set the color for assistant output (default: #0088ff)",
)
group.add_argument(
"--code-theme",
default="default",
help=(
"Set the markdown code theme (default: default, other options include monokai,"" solarized-dark, solarized-light)"
),
)
group.add_argument(
"--show-diffs",
action="store_true",
help="Show diffs when committing changes (default: False)",
default=False,
)
##########group=parser.add_argument_group("Git Settings")
group.add_argument(
"--git",
action=argparse.BooleanOptionalAction,
default=True,
help="Enable/disable looking for a git repo (default: True)",
)
group.add_argument(
"--gitignore",
action=argparse.BooleanOptionalAction,
default=True,
help="Enable/disable adding .aider* to .gitignore (default: True)",
)
default_aiderignore_file= (
os.path.join(git_root, ".aiderignore") ifgit_rootelse".aiderignore"
)
group.add_argument(
"--aiderignore",
metavar="AIDERIGNORE",
default=default_aiderignore_file,
help="Specify the aider ignore file (default: .aiderignore in git root)",
)
group.add_argument(
"--subtree-only",
action="store_true",
help="Only consider files in the current subtree of the git repository",
default=False,
)
group.add_argument(
"--auto-commits",
action=argparse.BooleanOptionalAction,
default=True,
help="Enable/disable auto commit of LLM changes (default: True)",
)
group.add_argument(
"--dirty-commits",
action=argparse.BooleanOptionalAction,
default=True,
help="Enable/disable commits when repo is found dirty (default: True)",
)
group.add_argument(
"--attribute-author",
action=argparse.BooleanOptionalAction,
default=True,
help="Attribute aider code changes in the git author name (default: True)",
)
group.add_argument(
"--attribute-committer",
action=argparse.BooleanOptionalAction,
default=True,
help="Attribute aider commits in the git committer name (default: True)",
)
group.add_argument(
"--attribute-commit-message-author",
action=argparse.BooleanOptionalAction,
default=False,
help="Prefix commit messages with 'aider: ' if aider authored the changes (default: False)",
)
group.add_argument(
"--attribute-commit-message-committer",
action=argparse.BooleanOptionalAction,
default=False,
help="Prefix all commit messages with 'aider: ' (default: False)",
)
group.add_argument(
"--commit",
action="store_true",
help="Commit all pending changes with a suitable commit message, then exit",
default=False,
)
group.add_argument(
"--commit-prompt",
metavar="PROMPT",
help="Specify a custom prompt for generating commit messages",
)
group.add_argument(
"--dry-run",
action=argparse.BooleanOptionalAction,
default=False,
help="Perform a dry run without modifying files (default: False)",
)
group=parser.add_argument_group("Fixing and committing")
group.add_argument(
"--lint",
action="store_true",
help="Lint and fix provided files, or dirty files if none provided",
default=False,
)
group.add_argument(
"--lint-cmd",
action="append",
help=(
'Specify lint commands to run for different languages, eg: "python: flake8'' --select=..." (can be used multiple times)'
),
default=[],
)
group.add_argument(
"--auto-lint",
action=argparse.BooleanOptionalAction,
default=True,
help="Enable/disable automatic linting after changes (default: True)",
)
group.add_argument(
"--test-cmd",
help="Specify command to run tests",
default=[],
)
group.add_argument(
"--auto-test",
action=argparse.BooleanOptionalAction,
default=False,
help="Enable/disable automatic testing after changes (default: False)",
)
group.add_argument(
"--test",
action="store_true",
help="Run tests and fix problems found",
default=False,
)
##########group=parser.add_argument_group("Other Settings")
group.add_argument(
"--file",
action="append",
metavar="FILE",
help="specify a file to edit (can be used multiple times)",
)
group.add_argument(
"--read",
action="append",
metavar="FILE",
help="specify a read-only file (can be used multiple times)",
)
group.add_argument(
"--vim",
action="store_true",
help="Use VI editing mode in the terminal (default: False)",
default=False,
)
group.add_argument(
"--voice-language",
metavar="VOICE_LANGUAGE",
default="en",
help="Specify the language for voice using ISO 639-1 code (default: auto)",
)
group.add_argument(
"--version",
action="version",
version=f"%(prog)s {__version__}",
help="Show the version number and exit",
)
group.add_argument(
"--just-check-update",
action="store_true",
help="Check for updates and return status in the exit code",
default=False,
)
group.add_argument(
"--check-update",
action=argparse.BooleanOptionalAction,
help="Check for new aider versions on launch",
default=True,
)
group.add_argument(
"--apply",
metavar="FILE",
help="Apply the changes from the given file instead of running the chat (debug)",
)
group.add_argument(
"--yes",
action="store_true",
help="Always say yes to every confirmation",
default=None,
)
group.add_argument(
"-v",
"--verbose",
action="store_true",
help="Enable verbose output",
default=False,
)
group.add_argument(
"--show-repo-map",
action="store_true",
help="Print the repo map and exit (debug)",
default=False,
)
group.add_argument(
"--show-prompts",
action="store_true",
help="Print the system prompts and exit (debug)",
default=False,
)
group.add_argument(
"--exit",
action="store_true",
help="Do all startup activities then exit before accepting user input (debug)",
default=False,
)
group.add_argument(
"--message",
"--msg",
"-m",
metavar="COMMAND",
help=(
"Specify a single message to send the LLM, process reply then exit (disables chat mode)"
),
)
group.add_argument(
"--message-file",
"-f",
metavar="MESSAGE_FILE",
help=(
"Specify a file containing the message to send the LLM, process reply, then exit"" (disables chat mode)"
),
)
group.add_argument(
"--encoding",
default="utf-8",
help="Specify the encoding for input and output (default: utf-8)",
)
group.add_argument(
"-c",
"--config",
is_config_file=True,
metavar="CONFIG_FILE",
help=(
"Specify the config file (default: search for .aider.conf.yml in git root, cwd"" or home directory)"
),
)
group.add_argument(
"--gui",
"--browser",
action="store_true",
help="Run aider in your browser",
default=False,
)
returnparserdefget_md_help():
os.environ["COLUMNS"] ="70"sys.argv= ["aider"]
parser=get_parser([], None)
# This instantiates all the action.env_var valuesparser.parse_known_args()
parser.formatter_class=MarkdownHelpFormatterreturnargparse.ArgumentParser.format_help(parser)
returnparser.format_help()
defget_sample_yaml():
os.environ["COLUMNS"] ="100"sys.argv= ["aider"]
parser=get_parser([], None)
# This instantiates all the action.env_var valuesparser.parse_known_args()
parser.formatter_class=YamlHelpFormatterreturnargparse.ArgumentParser.format_help(parser)
returnparser.format_help()
defget_sample_dotenv():
os.environ["COLUMNS"] ="120"sys.argv= ["aider"]
parser=get_parser([], None)
# This instantiates all the action.env_var valuesparser.parse_known_args()
parser.formatter_class=DotEnvFormatterreturnargparse.ArgumentParser.format_help(parser)
returnparser.format_help()
defmain():
arg=sys.argv[1] iflen(sys.argv[1:]) elseNoneifarg=="md":
print(get_md_help())
elifarg=="dotenv":
print(get_sample_dotenv())
else:
print(get_sample_yaml())
if__name__=="__main__":
status=main()
sys.exit(status)
from .ask_promptsimportAskPromptsfrom .base_coderimportCoderclassAskCoder(Coder):
"""Ask questions about code without making any changes."""edit_format="ask"gpt_prompts=AskPrompts()
# flake8: noqa: E501from .base_promptsimportCoderPromptsclassAskPrompts(CoderPrompts):
main_system="""Act as an expert code analyst.Answer questions about the supplied code.Always reply to the user in the same language they are using."""example_messages= []
files_content_prefix="""I have *added these files to the chat* so you see all of their contents.*Trust this message as the true contents of the files!*Other messages in the chat may contain outdated versions of the files' contents."""# noqa: E501files_no_full_files="I am not sharing the full contents of any files with you yet."files_no_full_files_with_repo_map=""files_no_full_files_with_repo_map_reply=""repo_content_prefix="""I am working with you on code in a git repository.Here are summaries of some files present in my git repo.If you need to see the full contents of any files to answer my questions, ask me to *add them to the chat*."""system_reminder=""
classCoderPrompts:
system_reminder=""files_content_gpt_edits="I committed the changes with git hash {hash} & commit msg: {message}"files_content_gpt_edits_no_repo="I updated the files."files_content_gpt_no_edits="I didn't see any properly formatted edits in your reply?!"files_content_local_edits="I edited the files myself."lazy_prompt="""You are diligent and tireless!You NEVER leave comments describing code without implementing it!You always COMPLETELY IMPLEMENT the needed code!"""example_messages= []
files_content_prefix="""I have *added these files to the chat* so you can go ahead and edit them.*Trust this message as the true contents of these files!*Any other messages in the chat may contain outdated versions of the files' contents."""# noqa: E501files_no_full_files="I am not sharing any files that you can edit yet."files_no_full_files_with_repo_map="""Don't try and edit any existing code without asking me to add the files to the chat!Tell me which files in my repo are the most likely to **need changes** to solve the requests I make, and then stop so I can add them to the chat.Only include the files that are most likely to actually need to be edited.Don't include files that might contain relevant context, just files that will need to be changed."""# noqa: E501files_no_full_files_with_repo_map_reply= (
"Ok, based on your requests I will suggest which files need to be edited and then"" stop and wait for your approval."
)
repo_content_prefix="""Here are summaries of some files present in my git repository.Do not propose changes to these files, treat them as *read-only*.If you need to edit any of these files, ask me to *add them to the chat* first."""read_only_files_prefix="""Here are some READ ONLY files, provided for your reference.Do not edit these files!"""
importdifflibimportmathimportreimportsysfromdifflibimportSequenceMatcherfrompathlibimportPathfromaiderimportutilsfrom ..dumpimportdump# noqa: F401from .base_coderimportCoderfrom .editblock_promptsimportEditBlockPromptsclassEditBlockCoder(Coder):
"""A coder that uses search/replace blocks for code modifications."""edit_format="diff"gpt_prompts=EditBlockPrompts()
defget_edits(self):
content=self.partial_response_content# might raise ValueError for malformed ORIG/UPD blocksedits=list(find_original_update_blocks(content, self.fence))
returneditsdefapply_edits(self, edits):
failed= []
passed= []
foreditinedits:
path, original, updated=editfull_path=self.abs_root_path(path)
content=self.io.read_text(full_path)
new_content=do_replace(full_path, content, original, updated, self.fence)
ifnotnew_content:
# try patching any of the other files in the chatforfull_pathinself.abs_fnames:
content=self.io.read_text(full_path)
new_content=do_replace(full_path, content, original, updated, self.fence)
ifnew_content:
breakifnew_content:
self.io.write_text(full_path, new_content)
passed.append(edit)
else:
failed.append(edit)
ifnotfailed:
returnblocks="block"iflen(failed) ==1else"blocks"res=f"# {len(failed)} SEARCH/REPLACE {blocks} failed to match!\n"foreditinfailed:
path, original, updated=editfull_path=self.abs_root_path(path)
content=self.io.read_text(full_path)
res+=f"""## SearchReplaceNoExactMatch: This SEARCH block failed to exactly match lines in {path}<<<<<<< SEARCH{original}======={updated}>>>>>>> REPLACE"""did_you_mean=find_similar_lines(original, content)
ifdid_you_mean:
res+=f"""Did you mean to match some of these actual lines from {path}?{self.fence[0]}{did_you_mean}{self.fence[1]}"""ifupdatedincontentandupdated:
res+=f"""Are you sure you need this SEARCH/REPLACE block?The REPLACE lines are already in {path}!"""res+= (
"The SEARCH section must exactly match an existing block of lines including all white"" space, comments, indentation, docstrings, etc\n"
)
ifpassed:
pblocks="block"iflen(passed) ==1else"blocks"res+=f"""# The other {len(passed)} SEARCH/REPLACE {pblocks} were applied successfully.Don't re-send them.Just reply with fixed versions of the {blocks} above that failed to match."""raiseValueError(res)
defprep(content):
ifcontentandnotcontent.endswith("\n"):
content+="\n"lines=content.splitlines(keepends=True)
returncontent, linesdefperfect_or_whitespace(whole_lines, part_lines, replace_lines):
# Try for a perfect matchres=perfect_replace(whole_lines, part_lines, replace_lines)
ifres:
returnres# Try being flexible about leading whitespaceres=replace_part_with_missing_leading_whitespace(whole_lines, part_lines, replace_lines)
ifres:
returnresdefperfect_replace(whole_lines, part_lines, replace_lines):
part_tup=tuple(part_lines)
part_len=len(part_lines)
foriinrange(len(whole_lines) -part_len+1):
whole_tup=tuple(whole_lines[i : i+part_len])
ifpart_tup==whole_tup:
res=whole_lines[:i] +replace_lines+whole_lines[i+part_len :]
return"".join(res)
defreplace_most_similar_chunk(whole, part, replace):
"""Best efforts to find the `part` lines in `whole` and replace them with `replace`"""whole, whole_lines=prep(whole)
part, part_lines=prep(part)
replace, replace_lines=prep(replace)
res=perfect_or_whitespace(whole_lines, part_lines, replace_lines)
ifres:
returnres# drop leading empty line, GPT sometimes adds them spuriously (issue #25)iflen(part_lines) >2andnotpart_lines[0].strip():
skip_blank_line_part_lines=part_lines[1:]
res=perfect_or_whitespace(whole_lines, skip_blank_line_part_lines, replace_lines)
ifres:
returnres# Try to handle when it elides code with ...try:
res=try_dotdotdots(whole, part, replace)
ifres:
returnresexceptValueError:
passreturn# Try fuzzy matchingres=replace_closest_edit_distance(whole_lines, part, part_lines, replace_lines)
ifres:
returnresdeftry_dotdotdots(whole, part, replace):
""" See if the edit block has ... lines. If not, return none. If yes, try and do a perfect edit with the ... chunks. If there's a mismatch or otherwise imperfect edit, raise ValueError. If perfect edit succeeds, return the updated whole. """dots_re=re.compile(r"(^\s*\.\.\.\n)", re.MULTILINE|re.DOTALL)
part_pieces=re.split(dots_re, part)
replace_pieces=re.split(dots_re, replace)
iflen(part_pieces) !=len(replace_pieces):
raiseValueError("Unpaired ... in SEARCH/REPLACE block")
iflen(part_pieces) ==1:
# no dots in this edit block, just return Nonereturn# Compare odd strings in part_pieces and replace_piecesall_dots_match=all(part_pieces[i] ==replace_pieces[i] foriinrange(1, len(part_pieces), 2))
ifnotall_dots_match:
raiseValueError("Unmatched ... in SEARCH/REPLACE block")
part_pieces= [part_pieces[i] foriinrange(0, len(part_pieces), 2)]
replace_pieces= [replace_pieces[i] foriinrange(0, len(replace_pieces), 2)]
pairs=zip(part_pieces, replace_pieces)
forpart, replaceinpairs:
ifnotpartandnotreplace:
continueifnotpartandreplace:
ifnotwhole.endswith("\n"):
whole+="\n"whole+=replacecontinueifwhole.count(part) ==0:
raiseValueErrorifwhole.count(part) >1:
raiseValueErrorwhole=whole.replace(part, replace, 1)
returnwholedefreplace_part_with_missing_leading_whitespace(whole_lines, part_lines, replace_lines):
# GPT often messes up leading whitespace.# It usually does it uniformly across the ORIG and UPD blocks.# Either omitting all leading whitespace, or including only some of it.# Outdent everything in part_lines and replace_lines by the max fixed amount possibleleading= [len(p) -len(p.lstrip()) forpinpart_linesifp.strip()] + [
len(p) -len(p.lstrip()) forpinreplace_linesifp.strip()
]
ifleadingandmin(leading):
num_leading=min(leading)
part_lines= [p[num_leading:] ifp.strip() elsepforpinpart_lines]
replace_lines= [p[num_leading:] ifp.strip() elsepforpinreplace_lines]
# can we find an exact match not including the leading whitespacenum_part_lines=len(part_lines)
foriinrange(len(whole_lines) -num_part_lines+1):
add_leading=match_but_for_leading_whitespace(
whole_lines[i : i+num_part_lines], part_lines
)
ifadd_leadingisNone:
continuereplace_lines= [add_leading+rlineifrline.strip() elserlineforrlineinreplace_lines]
whole_lines=whole_lines[:i] +replace_lines+whole_lines[i+num_part_lines :]
return"".join(whole_lines)
returnNonedefmatch_but_for_leading_whitespace(whole_lines, part_lines):
num=len(whole_lines)
# does the non-whitespace all agree?ifnotall(whole_lines[i].lstrip() ==part_lines[i].lstrip() foriinrange(num)):
return# are they all offset the same?add=set(
whole_lines[i][: len(whole_lines[i]) -len(part_lines[i])]
foriinrange(num)
ifwhole_lines[i].strip()
)
iflen(add) !=1:
returnreturnadd.pop()
defreplace_closest_edit_distance(whole_lines, part, part_lines, replace_lines):
similarity_thresh=0.8max_similarity=0most_similar_chunk_start=-1most_similar_chunk_end=-1scale=0.1min_len=math.floor(len(part_lines) * (1-scale))
max_len=math.ceil(len(part_lines) * (1+scale))
forlengthinrange(min_len, max_len):
foriinrange(len(whole_lines) -length+1):
chunk=whole_lines[i : i+length]
chunk="".join(chunk)
similarity=SequenceMatcher(None, chunk, part).ratio()
ifsimilarity>max_similarityandsimilarity:
max_similarity=similaritymost_similar_chunk_start=imost_similar_chunk_end=i+lengthifmax_similarity<similarity_thresh:
returnmodified_whole= (
whole_lines[:most_similar_chunk_start]
+replace_lines+whole_lines[most_similar_chunk_end:]
)
modified_whole="".join(modified_whole)
returnmodified_wholeDEFAULT_FENCE= ("`"*3, "`"*3)
defstrip_quoted_wrapping(res, fname=None, fence=DEFAULT_FENCE):
""" Given an input string which may have extra "wrapping" around it, remove the wrapping. For example: filename.ext ``` We just want this content Not the filename and triple quotes ``` """ifnotres:
returnresres=res.splitlines()
iffnameandres[0].strip().endswith(Path(fname).name):
res=res[1:]
ifres[0].startswith(fence[0]) andres[-1].startswith(fence[1]):
res=res[1:-1]
res="\n".join(res)
ifresandres[-1] !="\n":
res+="\n"returnresdefdo_replace(fname, content, before_text, after_text, fence=None):
before_text=strip_quoted_wrapping(before_text, fname, fence)
after_text=strip_quoted_wrapping(after_text, fname, fence)
fname=Path(fname)
# does it want to make a new file?ifnotfname.exists() andnotbefore_text.strip():
fname.touch()
content=""ifcontentisNone:
returnifnotbefore_text.strip():
# append to existing file, or start a new filenew_content=content+after_textelse:
new_content=replace_most_similar_chunk(content, before_text, after_text)
returnnew_contentHEAD="<<<<<<< SEARCH"DIVIDER="======="UPDATED=">>>>>>> REPLACE"separators="|".join([HEAD, DIVIDER, UPDATED])
split_re=re.compile(r"^((?:"+separators+r")[ ]*\n)", re.MULTILINE|re.DOTALL)
missing_filename_err= (
"Bad/missing filename. The filename must be alone on the line before the opening fence"" {fence[0]}"
)
defstrip_filename(filename, fence):
filename=filename.strip()
iffilename=="...":
returnstart_fence=fence[0]
iffilename.startswith(start_fence):
returnfilename=filename.rstrip(":")
filename=filename.lstrip("#")
filename=filename.strip()
filename=filename.strip("`")
filename=filename.strip("*")
filename=filename.replace("\\_", "_")
returnfilenamedeffind_original_update_blocks(content, fence=DEFAULT_FENCE):
# make sure we end with a newline, otherwise the regex will miss <<UPD on the last lineifnotcontent.endswith("\n"):
content=content+"\n"pieces=re.split(split_re, content)
pieces.reverse()
processed= []
# Keep using the same filename in cases where GPT produces an edit block# without a filename.current_filename=Nonetry:
whilepieces:
cur=pieces.pop()
ifcurin (DIVIDER, UPDATED):
processed.append(cur)
raiseValueError(f"Unexpected {cur}")
ifcur.strip() !=HEAD:
processed.append(cur)
continueprocessed.append(cur) # original_markerfilename=find_filename(processed[-2].splitlines(), fence)
ifnotfilename:
ifcurrent_filename:
filename=current_filenameelse:
raiseValueError(missing_filename_err.format(fence=fence))
current_filename=filenameoriginal_text=pieces.pop()
processed.append(original_text)
divider_marker=pieces.pop()
processed.append(divider_marker)
ifdivider_marker.strip() !=DIVIDER:
raiseValueError(f"Expected `{DIVIDER}` not {divider_marker.strip()}")
updated_text=pieces.pop()
processed.append(updated_text)
updated_marker=pieces.pop()
processed.append(updated_marker)
ifupdated_marker.strip() !=UPDATED:
raiseValueError(f"Expected `{UPDATED}` not `{updated_marker.strip()}")
yieldfilename, original_text, updated_textexceptValueErrorase:
processed="".join(processed)
err=e.args[0]
raiseValueError(f"{processed}\n^^^ {err}")
exceptIndexError:
processed="".join(processed)
raiseValueError(f"{processed}\n^^^ Incomplete SEARCH/REPLACE block.")
exceptException:
processed="".join(processed)
raiseValueError(f"{processed}\n^^^ Error parsing SEARCH/REPLACE block.")
deffind_filename(lines, fence):
""" Deepseek Coder v2 has been doing this: ```python word_count.py ``` ```python <<<<<<< SEARCH ... This is a more flexible search back for filenames. """# Go back through the 3 preceding lineslines.reverse()
lines=lines[:3]
forlineinlines:
# If we find a filename, donefilename=strip_filename(line, fence)
iffilename:
returnfilename# Only continue as long as we keep seeing fencesifnotline.startswith(fence[0]):
returndeffind_similar_lines(search_lines, content_lines, threshold=0.6):
search_lines=search_lines.splitlines()
content_lines=content_lines.splitlines()
best_ratio=0best_match=Noneforiinrange(len(content_lines) -len(search_lines) +1):
chunk=content_lines[i : i+len(search_lines)]
ratio=SequenceMatcher(None, search_lines, chunk).ratio()
ifratio>best_ratio:
best_ratio=ratiobest_match=chunkbest_match_i=iifbest_ratio<threshold:
return""ifbest_match[0] ==search_lines[0] andbest_match[-1] ==search_lines[-1]:
return"\n".join(best_match)
N=5best_match_end=min(len(content_lines), best_match_i+len(search_lines) +N)
best_match_i=max(0, best_match_i-N)
best=content_lines[best_match_i:best_match_end]
return"\n".join(best)
defmain():
history_md=Path(sys.argv[1]).read_text()
ifnothistory_md:
returnmessages=utils.split_chat_history_markdown(history_md)
formsginmessages:
msg=msg["content"]
edits=list(find_original_update_blocks(msg))
forfname, before, afterinedits:
# Compute diffdiff=difflib.unified_diff(
before.splitlines(keepends=True),
after.splitlines(keepends=True),
fromfile="before",
tofile="after",
)
diff="".join(diff)
dump(before)
dump(after)
dump(diff)
if__name__=="__main__":
main()
# flake8: noqa: E501from .editblock_promptsimportEditBlockPromptsclassEditBlockFencedPrompts(EditBlockPrompts):
example_messages= [
dict(
role="user",
content="Change get_factorial() to use math.factorial",
),
dict(
role="assistant",
content="""To make this change we need to modify `mathweb/flask/app.py` to:1. Import the math package.2. Remove the existing factorial() function.3. Update get_factorial() to call math.factorial instead.Here are the *SEARCH/REPLACE* blocks:{fence[0]}mathweb/flask/app.py<<<<<<< SEARCHfrom flask import Flask=======import mathfrom flask import Flask>>>>>>> REPLACE{fence[1]}{fence[0]}mathweb/flask/app.py<<<<<<< SEARCHdef factorial(n): "compute factorial" if n == 0: return 1 else: return n * factorial(n-1)=======>>>>>>> REPLACE{fence[1]}{fence[0]}mathweb/flask/app.py<<<<<<< SEARCH return str(factorial(n))======= return str(math.factorial(n))>>>>>>> REPLACE{fence[1]}<<<<<<< HEAD""",
),
dict(
role="user",
content="Refactor hello() into its own file.",
),
dict(
role="assistant",
content="""To make this change we need to modify `main.py` and make a new file `hello.py`:1. Make a new hello.py file with hello() in it.2. Remove hello() from main.py and replace it with an import.Here are the *SEARCH/REPLACE* blocks:{fence[0]}hello.py<<<<<<< SEARCH=======def hello(): "print a greeting" print("hello")>>>>>>> REPLACE{fence[1]}{fence[0]}main.py<<<<<<< SEARCHdef hello(): "print a greeting" print("hello")=======from hello import hello>>>>>>> REPLACE{fence[1]}""",
),
]
importjsonfrom ..dumpimportdump# noqa: F401from .base_coderimportCoderfrom .editblock_coderimportdo_replacefrom .editblock_func_promptsimportEditBlockFunctionPromptsclassEditBlockFunctionCoder(Coder):
functions= [
dict(
name="replace_lines",
description="create or update one or more files",
parameters=dict(
type="object",
required=["explanation", "edits"],
properties=dict(
explanation=dict(
type="string",
description=(
"Step by step plan for the changes to be made to the code (future"" tense, markdown format)"
),
),
edits=dict(
type="array",
items=dict(
type="object",
required=["path", "original_lines", "updated_lines"],
properties=dict(
path=dict(
type="string",
description="Path of file to edit",
),
original_lines=dict(
type="array",
items=dict(
type="string",
),
description=(
"A unique stretch of lines from the original file,"" including all whitespace, without skipping any lines"
),
),
updated_lines=dict(
type="array",
items=dict(
type="string",
),
description="New content to replace the `original_lines` with",
),
),
),
),
),
),
),
]
def__init__(self, code_format, *args, **kwargs):
raiseRuntimeError("Deprecated, needs to be refactored to support get_edits/apply_edits")
self.code_format=code_formatifcode_format=="string":
original_lines=dict(
type="string",
description=(
"A unique stretch of lines from the original file, including all"" whitespace and newlines, without skipping any lines"
),
)
updated_lines=dict(
type="string",
description="New content to replace the `original_lines` with",
)
self.functions[0]["parameters"]["properties"]["edits"]["items"]["properties"][
"original_lines"
] =original_linesself.functions[0]["parameters"]["properties"]["edits"]["items"]["properties"][
"updated_lines"
] =updated_linesself.gpt_prompts=EditBlockFunctionPrompts()
super().__init__(*args, **kwargs)
defrender_incremental_response(self, final=False):
ifself.partial_response_content:
returnself.partial_response_contentargs=self.parse_partial_args()
res=json.dumps(args, indent=4)
returnresdef_update_files(self):
name=self.partial_response_function_call.get("name")
ifnameandname!="replace_lines":
raiseValueError(f'Unknown function_call name="{name}", use name="replace_lines"')
args=self.parse_partial_args()
ifnotargs:
returnedits=args.get("edits", [])
edited=set()
foreditinedits:
path=get_arg(edit, "path")
original=get_arg(edit, "original_lines")
updated=get_arg(edit, "updated_lines")
# gpt-3.5 returns lists even when instructed to return a string!ifself.code_format=="list"ortype(original) ==list:
original="\n".join(original)
ifself.code_format=="list"ortype(updated) ==list:
updated="\n".join(updated)
iforiginalandnotoriginal.endswith("\n"):
original+="\n"ifupdatedandnotupdated.endswith("\n"):
updated+="\n"full_path=self.allowed_to_edit(path)
ifnotfull_path:
continuecontent=self.io.read_text(full_path)
content=do_replace(full_path, content, original, updated)
ifcontent:
self.io.write_text(full_path, content)
edited.add(path)
continueself.io.tool_error(f"Failed to apply edit to {path}")
returnediteddefget_arg(edit, arg):
ifargnotinedit:
raiseValueError(f"Missing `{arg}` parameter: {edit}")
returnedit[arg]
# flake8: noqa: E501from .base_promptsimportCoderPromptsclassEditBlockFunctionPrompts(CoderPrompts):
main_system="""Act as an expert software developer.Take requests for changes to the supplied code.If the request is ambiguous, ask questions.Once you understand the request you MUST use the `replace_lines` function to edit the files to make the needed changes."""system_reminder="""ONLY return code using the `replace_lines` function.NEVER return code outside the `replace_lines` function."""files_content_prefix="Here is the current content of the files:\n"files_no_full_files="I am not sharing any files yet."redacted_edit_message="No changes are needed."repo_content_prefix= (
"Below here are summaries of other files! Do not propose changes to these *read-only*"" files without asking me first.\n"
)
# flake8: noqa: E501from .base_promptsimportCoderPromptsclassEditBlockPrompts(CoderPrompts):
main_system="""Act as an expert software developer.Always use best practices when coding.Respect and use existing conventions, libraries, etc that are already present in the code base.{lazy_prompt}Take requests for changes to the supplied code.If the request is ambiguous, ask questions.Always reply to the user in the same language they are using.Once you understand the request you MUST:1. Decide if you need to propose *SEARCH/REPLACE* edits to any files that haven't been added to the chat. You can create new files without asking. But if you need to propose edits to existing files not already added to the chat, you *MUST* tell the user their full path names and ask them to *add the files to the chat*. End your reply and wait for their approval. You can keep asking if you then decide you need to edit more files.2. Think step-by-step and explain the needed changes with a numbered list of short sentences.3. Describe each change with a *SEARCH/REPLACE block* per the examples below. All changes to files must use this *SEARCH/REPLACE block* format. ONLY EVER RETURN CODE IN A *SEARCH/REPLACE BLOCK*!All changes to files must use the *SEARCH/REPLACE block* format.Keep this info about the user's system in mind:{platform}"""example_messages= [
dict(
role="user",
content="Change get_factorial() to use math.factorial",
),
dict(
role="assistant",
content="""To make this change we need to modify `mathweb/flask/app.py` to:1. Import the math package.2. Remove the existing factorial() function.3. Update get_factorial() to call math.factorial instead.Here are the *SEARCH/REPLACE* blocks:mathweb/flask/app.py{fence[0]}python<<<<<<< SEARCHfrom flask import Flask=======import mathfrom flask import Flask>>>>>>> REPLACE{fence[1]}mathweb/flask/app.py{fence[0]}python<<<<<<< SEARCHdef factorial(n): "compute factorial" if n == 0: return 1 else: return n * factorial(n-1)=======>>>>>>> REPLACE{fence[1]}mathweb/flask/app.py{fence[0]}python<<<<<<< SEARCH return str(factorial(n))======= return str(math.factorial(n))>>>>>>> REPLACE{fence[1]}""",
),
dict(
role="user",
content="Refactor hello() into its own file.",
),
dict(
role="assistant",
content="""To make this change we need to modify `main.py` and make a new file `hello.py`:1. Make a new hello.py file with hello() in it.2. Remove hello() from main.py and replace it with an import.Here are the *SEARCH/REPLACE* blocks:hello.py{fence[0]}python<<<<<<< SEARCH=======def hello(): "print a greeting" print("hello")>>>>>>> REPLACE{fence[1]}main.py{fence[0]}python<<<<<<< SEARCHdef hello(): "print a greeting" print("hello")=======from hello import hello>>>>>>> REPLACE{fence[1]}""",
),
]
system_reminder="""# *SEARCH/REPLACE block* Rules:Every *SEARCH/REPLACE block* must use this format:1. The file path alone on a line, verbatim. No bold asterisks, no quotes around it, no escaping of characters, etc.2. The opening fence and code language, eg: {fence[0]}python3. The start of search block: <<<<<<< SEARCH4. A contiguous chunk of lines to search for in the existing source code5. The dividing line: =======6. The lines to replace into the source code7. The end of the replace block: >>>>>>> REPLACE8. The closing fence: {fence[1]}Every *SEARCH* section must *EXACTLY MATCH* the existing source code, character for character, including all comments, docstrings, etc.*SEARCH/REPLACE* blocks will replace *all* matching occurrences.Include enough lines to make the SEARCH blocks uniquely match the lines to change.Keep *SEARCH/REPLACE* blocks concise.Break large *SEARCH/REPLACE* blocks into a series of smaller blocks that each change a small portion of the file.Include just the changing lines, and a few surrounding lines if needed for uniqueness.Do not include long runs of unchanging lines in *SEARCH/REPLACE* blocks.Only create *SEARCH/REPLACE* blocks for files that the user has added to the chat!To move code within a file, use 2 *SEARCH/REPLACE* blocks: 1 to delete it from its current location, 1 to insert it in the new location.If you want to put code in a new file, use a *SEARCH/REPLACE block* with:- A new file path, including dir name if needed- An empty `SEARCH` section- The new file's contents in the `REPLACE` section{lazy_prompt}ONLY EVER RETURN CODE IN A *SEARCH/REPLACE BLOCK*!"""
from ..dumpimportdump# noqa: F401from .base_coderimportCoderfrom .help_promptsimportHelpPromptsclassHelpCoder(Coder):
"""Interactive help and documentation about aider."""edit_format="help"gpt_prompts=HelpPrompts()
defget_edits(self, mode="update"):
return []
defapply_edits(self, edits):
pass
# flake8: noqa: E501from .base_promptsimportCoderPromptsclassHelpPrompts(CoderPrompts):
main_system="""You are an expert on the AI coding tool called Aider.Answer the user's questions about how to use aider.The user is currently chatting with you using aider, to write and edit code.Use the provided aider documentation *if it is relevant to the user's question*.Include a bulleted list of urls to the aider docs that might be relevant for the user to read.Include *bare* urls. *Do not* make [markdown links](http://...).For example:- https://aider.chat/docs/usage.html- https://aider.chat/docs/faq.htmlIf you don't know the answer, say so and suggest some relevant aider doc urls.If asks for something that isn't possible with aider, be clear about that.Don't suggest a solution that isn't supported.Be helpful but concise.Unless the question indicates otherwise, assume the user wants to use aider as a CLI tool.Keep this info about the user's system in mind:{platform}"""example_messages= []
system_reminder=""files_content_prefix="""These are some files we have been discussing that we may want to edit after you answer my questions:"""files_no_full_files="I am not sharing any files with you."files_no_full_files_with_repo_map=""files_no_full_files_with_repo_map_reply=""repo_content_prefix="""Here are summaries of some files present in my git repository.We may look at these in more detail after you answer my questions."""
#!/usr/bin/env pythonimportsysfrompathlibimportPathimportgitfromdiff_match_patchimportdiff_match_patchfromtqdmimporttqdmfromaider.dumpimportdumpfromaider.utilsimportGitTemporaryDirectoryclassRelativeIndenter:
"""Rewrites text files to have relative indentation, which involves reformatting the leading white space on lines. This format makes it easier to search and apply edits to pairs of code blocks which may differ significantly in their overall level of indentation. It removes leading white space which is shared with the preceding line. Original: ``` Foo # indented 8 Bar # indented 4 more than the previous line Baz # same indent as the previous line Fob # same indent as the previous line ``` Becomes: ``` Foo # indented 8 Bar # indented 4 more than the previous line Baz # same indent as the previous line Fob # same indent as the previous line ``` If the current line is *less* indented then the previous line, uses a unicode character to indicate outdenting. Original ``` Foo Bar Baz Fob # indented 4 less than the previous line ``` Becomes: ``` Foo Bar Baz ←←←←Fob # indented 4 less than the previous line ``` This is a similar original to the last one, but every line has been uniformly outdented: ``` Foo Bar Baz Fob # indented 4 less than the previous line ``` It becomes this result, which is very similar to the previous result. Only the white space on the first line differs. From the word Foo onwards, it is identical to the previous result. ``` Foo Bar Baz ←←←←Fob # indented 4 less than the previous line ``` """def__init__(self, texts):
""" Based on the texts, choose a unicode character that isn't in any of them. """chars=set()
fortextintexts:
chars.update(text)
ARROW="←"ifARROWnotinchars:
self.marker=ARROWelse:
self.marker=self.select_unique_marker(chars)
defselect_unique_marker(self, chars):
forcodepointinrange(0x10FFFF, 0x10000, -1):
marker=chr(codepoint)
ifmarkernotinchars:
returnmarkerraiseValueError("Could not find a unique marker")
defmake_relative(self, text):
""" Transform text to use relative indents. """ifself.markerintext:
raiseValueError("Text already contains the outdent marker: {self.marker}")
lines=text.splitlines(keepends=True)
output= []
prev_indent=""forlineinlines:
line_without_end=line.rstrip("\n\r")
len_indent=len(line_without_end) -len(line_without_end.lstrip())
indent=line[:len_indent]
change=len_indent-len(prev_indent)
ifchange>0:
cur_indent=indent[-change:]
elifchange<0:
cur_indent=self.marker*-changeelse:
cur_indent=""out_line=cur_indent+"\n"+line[len_indent:]
# dump(len_indent, change, out_line)# print(out_line)output.append(out_line)
prev_indent=indentres="".join(output)
returnresdefmake_absolute(self, text):
""" Transform text from relative back to absolute indents. """lines=text.splitlines(keepends=True)
output= []
prev_indent=""foriinrange(0, len(lines), 2):
dent=lines[i].rstrip("\r\n")
non_indent=lines[i+1]
ifdent.startswith(self.marker):
len_outdent=len(dent)
cur_indent=prev_indent[:-len_outdent]
else:
cur_indent=prev_indent+dentifnotnon_indent.rstrip("\r\n"):
out_line=non_indent# don't indent a blank lineelse:
out_line=cur_indent+non_indentoutput.append(out_line)
prev_indent=cur_indentres="".join(output)
ifself.markerinres:
# dump(res)raiseValueError("Error transforming text back to absolute indents")
returnres# The patches are created to change S->R.# So all the patch offsets are relative to S.# But O has a lot more content. So all the offsets are very wrong.## But patch_apply() seems to imply that once patch N is located,# then it adjusts the offset of the next patch.## This is great, because once we sync up after a big gap the nearby# patches are close to being located right.# Except when indentation has been changed by GPT.## It would help to use the diff trick to build map_S_offset_to_O_offset().# Then update all the S offsets in the S->R patches to be O offsets.# Do we also need to update the R offsets?## What if this gets funky/wrong?#defmap_patches(texts, patches, debug):
search_text, replace_text, original_text=textsdmp=diff_match_patch()
dmp.Diff_Timeout=5diff_s_o=dmp.diff_main(search_text, original_text)
# diff_r_s = dmp.diff_main(replace_text, search_text)# dmp.diff_cleanupSemantic(diff_s_o)# dmp.diff_cleanupEfficiency(diff_s_o)ifdebug:
html=dmp.diff_prettyHtml(diff_s_o)
Path("tmp.html").write_text(html)
dump(len(search_text))
dump(len(original_text))
forpatchinpatches:
start1=patch.start1start2=patch.start2patch.start1=dmp.diff_xIndex(diff_s_o, start1)
patch.start2=dmp.diff_xIndex(diff_s_o, start2)
ifdebug:
print()
print(start1, repr(search_text[start1 : start1+50]))
print(patch.start1, repr(original_text[patch.start1 : patch.start1+50]))
print(patch.diffs)
print()
returnpatchesexample="""LeftLeft 4 in 4 in 8 in 4 inLeft""""""ri = RelativeIndenter([example])dump(example)rel_example = ri.make_relative(example)dump(repr(rel_example))abs_example = ri.make_absolute(rel_example)dump(abs_example)sys.exit()"""defrelative_indent(texts):
ri=RelativeIndenter(texts)
texts=list(map(ri.make_relative, texts))
returnri, textsline_padding=100defline_pad(text):
padding="\n"*line_paddingreturnpadding+text+paddingdefline_unpad(text):
ifset(text[:line_padding] +text[-line_padding:]) !=set("\n"):
returnreturntext[line_padding:-line_padding]
defdmp_apply(texts, remap=True):
debug=False# debug = Truesearch_text, replace_text, original_text=textsdmp=diff_match_patch()
dmp.Diff_Timeout=5# dmp.Diff_EditCost = 16ifremap:
dmp.Match_Threshold=0.95dmp.Match_Distance=500dmp.Match_MaxBits=128dmp.Patch_Margin=32else:
dmp.Match_Threshold=0.5dmp.Match_Distance=100_000dmp.Match_MaxBits=32dmp.Patch_Margin=8diff=dmp.diff_main(search_text, replace_text, None)
dmp.diff_cleanupSemantic(diff)
dmp.diff_cleanupEfficiency(diff)
patches=dmp.patch_make(search_text, diff)
ifdebug:
html=dmp.diff_prettyHtml(diff)
Path("tmp.search_replace_diff.html").write_text(html)
fordindiff:
print(d[0], repr(d[1]))
forpatchinpatches:
start1=patch.start1print()
print(start1, repr(search_text[start1 : start1+10]))
print(start1, repr(replace_text[start1 : start1+10]))
print(patch.diffs)
# dump(original_text)# dump(search_text)ifremap:
patches=map_patches(texts, patches, debug)
patches_text=dmp.patch_toText(patches)
new_text, success=dmp.patch_apply(patches, original_text)
all_success=Falsenotinsuccessifdebug:
# dump(new_text)print(patches_text)
# print(new_text)dump(success)
dump(all_success)
# print(new_text)ifnotall_success:
returnreturnnew_textdeflines_to_chars(lines, mapping):
new_text= []
forcharinlines:
new_text.append(mapping[ord(char)])
new_text="".join(new_text)
returnnew_textdefdmp_lines_apply(texts, remap=True):
debug=False# debug = Truefortintexts:
assertt.endswith("\n"), tsearch_text, replace_text, original_text=textsdmp=diff_match_patch()
dmp.Diff_Timeout=5# dmp.Diff_EditCost = 16dmp.Match_Threshold=0.1dmp.Match_Distance=100_000dmp.Match_MaxBits=32dmp.Patch_Margin=1all_text=search_text+replace_text+original_textall_lines, _, mapping=dmp.diff_linesToChars(all_text, "")
assertlen(all_lines) ==len(all_text.splitlines())
search_num=len(search_text.splitlines())
replace_num=len(replace_text.splitlines())
original_num=len(original_text.splitlines())
search_lines=all_lines[:search_num]
replace_lines=all_lines[search_num : search_num+replace_num]
original_lines=all_lines[search_num+replace_num :]
assertlen(search_lines) ==search_numassertlen(replace_lines) ==replace_numassertlen(original_lines) ==original_numdiff_lines=dmp.diff_main(search_lines, replace_lines, None)
dmp.diff_cleanupSemantic(diff_lines)
dmp.diff_cleanupEfficiency(diff_lines)
patches=dmp.patch_make(search_lines, diff_lines)
ifdebug:
diff=list(diff_lines)
dmp.diff_charsToLines(diff, mapping)
# dump(diff)html=dmp.diff_prettyHtml(diff)
Path("tmp.search_replace_diff.html").write_text(html)
fordindiff:
print(d[0], repr(d[1]))
new_lines, success=dmp.patch_apply(patches, original_lines)
new_text=lines_to_chars(new_lines, mapping)
all_success=Falsenotinsuccessifdebug:
# print(new_text)dump(success)
dump(all_success)
# print(new_text)ifnotall_success:
returnreturnnew_textdefdiff_lines(search_text, replace_text):
dmp=diff_match_patch()
dmp.Diff_Timeout=5# dmp.Diff_EditCost = 16search_lines, replace_lines, mapping=dmp.diff_linesToChars(search_text, replace_text)
diff_lines=dmp.diff_main(search_lines, replace_lines, None)
dmp.diff_cleanupSemantic(diff_lines)
dmp.diff_cleanupEfficiency(diff_lines)
diff=list(diff_lines)
dmp.diff_charsToLines(diff, mapping)
# dump(diff)udiff= []
ford, linesindiff:
ifd<0:
d="-"elifd>0:
d="+"else:
d=" "forlineinlines.splitlines(keepends=True):
udiff.append(d+line)
returnudiffdefsearch_and_replace(texts):
search_text, replace_text, original_text=textsnum=original_text.count(search_text)
# if num > 1:# raise SearchTextNotUnique()ifnum==0:
returnnew_text=original_text.replace(search_text, replace_text)
returnnew_textdefgit_cherry_pick_osr_onto_o(texts):
search_text, replace_text, original_text=textswithGitTemporaryDirectory() asdname:
repo=git.Repo(dname)
fname=Path(dname) /"file.txt"# Make O->S->Rfname.write_text(original_text)
repo.git.add(str(fname))
repo.git.commit("-m", "original")
original_hash=repo.head.commit.hexshafname.write_text(search_text)
repo.git.add(str(fname))
repo.git.commit("-m", "search")
fname.write_text(replace_text)
repo.git.add(str(fname))
repo.git.commit("-m", "replace")
replace_hash=repo.head.commit.hexsha# go back to Orepo.git.checkout(original_hash)
# cherry pick R onto originaltry:
repo.git.cherry_pick(replace_hash, "--minimal")
exceptgit.exc.GitCommandError:
# merge conflicts!returnnew_text=fname.read_text()
returnnew_textdefgit_cherry_pick_sr_onto_so(texts):
search_text, replace_text, original_text=textswithGitTemporaryDirectory() asdname:
repo=git.Repo(dname)
fname=Path(dname) /"file.txt"fname.write_text(search_text)
repo.git.add(str(fname))
repo.git.commit("-m", "search")
search_hash=repo.head.commit.hexsha# make search->replacefname.write_text(replace_text)
repo.git.add(str(fname))
repo.git.commit("-m", "replace")
replace_hash=repo.head.commit.hexsha# go back to search,repo.git.checkout(search_hash)
# make search->originalfname.write_text(original_text)
repo.git.add(str(fname))
repo.git.commit("-m", "original")
# cherry pick replace onto originaltry:
repo.git.cherry_pick(replace_hash, "--minimal")
exceptgit.exc.GitCommandError:
# merge conflicts!returnnew_text=fname.read_text()
returnnew_textclassSearchTextNotUnique(ValueError):
passall_preprocs= [
# (strip_blank_lines, relative_indent, reverse_lines)
(False, False, False),
(True, False, False),
(False, True, False),
(True, True, False),
# (False, False, True),# (True, False, True),# (False, True, True),# (True, True, True),
]
always_relative_indent= [
(False, True, False),
(True, True, False),
# (False, True, True),# (True, True, True),
]
editblock_strategies= [
(search_and_replace, all_preprocs),
(git_cherry_pick_osr_onto_o, all_preprocs),
(dmp_lines_apply, all_preprocs),
]
never_relative= [
(False, False),
(True, False),
]
udiff_strategies= [
(search_and_replace, all_preprocs),
(git_cherry_pick_osr_onto_o, all_preprocs),
(dmp_lines_apply, all_preprocs),
]
defflexible_search_and_replace(texts, strategies):
"""Try a series of search/replace methods, starting from the most literal interpretation of search_text. If needed, progress to more flexible methods, which can accommodate divergence between search_text and original_text and yet still achieve the desired edits. """forstrategy, preprocsinstrategies:
forpreprocinpreprocs:
res=try_strategy(texts, strategy, preproc)
ifres:
returnresdefreverse_lines(text):
lines=text.splitlines(keepends=True)
lines.reverse()
return"".join(lines)
deftry_strategy(texts, strategy, preproc):
preproc_strip_blank_lines, preproc_relative_indent, preproc_reverse=preprocri=Noneifpreproc_strip_blank_lines:
texts=strip_blank_lines(texts)
ifpreproc_relative_indent:
ri, texts=relative_indent(texts)
ifpreproc_reverse:
texts=list(map(reverse_lines, texts))
res=strategy(texts)
ifresandpreproc_reverse:
res=reverse_lines(res)
ifresandpreproc_relative_indent:
try:
res=ri.make_absolute(res)
exceptValueError:
returnreturnresdefstrip_blank_lines(texts):
# strip leading and trailing blank linestexts= [text.strip("\n") +"\n"fortextintexts]
returntextsdefread_text(fname):
text=Path(fname).read_text()
returntextdefproc(dname):
dname=Path(dname)
try:
search_text=read_text(dname/"search")
replace_text=read_text(dname/"replace")
original_text=read_text(dname/"original")
exceptFileNotFoundError:
return####texts=search_text, replace_text, original_textstrategies= [
# (search_and_replace, all_preprocs),# (git_cherry_pick_osr_onto_o, all_preprocs),# (git_cherry_pick_sr_onto_so, all_preprocs),# (dmp_apply, all_preprocs),
(dmp_lines_apply, all_preprocs),
]
_strategies=editblock_strategies# noqa: F841short_names=dict(
search_and_replace="sr",
git_cherry_pick_osr_onto_o="cp_o",
git_cherry_pick_sr_onto_so="cp_so",
dmp_apply="dmp",
dmp_lines_apply="dmpl",
)
patched=dict()
forstrategy, preprocsinstrategies:
forpreprocinpreprocs:
method=strategy.__name__method=short_names[method]
strip_blank, rel_indent, rev_lines=preprocifstrip_blankorrel_indent:
method+="_"ifstrip_blank:
method+="s"ifrel_indent:
method+="i"ifrev_lines:
method+="r"res=try_strategy(texts, strategy, preproc)
patched[method] =resresults= []
formethod, resinpatched.items():
out_fname=dname/f"original.{method}"ifout_fname.exists():
out_fname.unlink()
ifres:
out_fname.write_text(res)
correct= (dname/"correct").read_text()
ifres==correct:
res="pass"else:
res="WRONG"else:
res="fail"results.append((method, res))
returnresultsdefcolorize_result(result):
colors= {
"pass": "\033[102;30mpass\033[0m", # Green background, black text"WRONG": "\033[101;30mWRONG\033[0m", # Red background, black text"fail": "\033[103;30mfail\033[0m", # Yellow background, black text
}
returncolors.get(result, result) # Default to original result if not founddefmain(dnames):
all_results= []
fordnameintqdm(dnames):
dname=Path(dname)
results=proc(dname)
formethod, resinresults:
all_results.append((dname, method, res))
# print(dname, method, colorize_result(res))# Create a 2D table with directories along the right and methods along the top# Collect all unique methods and directoriesmethods= []
for_, method, _inall_results:
ifmethodnotinmethods:
methods.append(method)
directories=dnames# Sort directories by decreasing number of 'pass' resultspass_counts= {
dname: sum(
res=="pass"fordname_result, _, resinall_resultsifstr(dname) ==str(dname_result)
)
fordnameindirectories
}
directories.sort(key=lambdadname: pass_counts[dname], reverse=True)
# Create a results matrixresults_matrix= {dname: {method: ""formethodinmethods} fordnameindirectories}
# Populate the results matrixfordname, method, resinall_results:
results_matrix[str(dname)][method] =res# Print the 2D table# Print the headerprint("{:<20}".format("Directory"), end="")
formethodinmethods:
print("{:<9}".format(method), end="")
print()
# Print the rows with colorized resultsfordnameindirectories:
print("{:<20}".format(Path(dname).name), end="")
formethodinmethods:
res=results_matrix[dname][method]
colorized_res=colorize_result(res)
res_l=9+len(colorized_res) -len(res)
fmt="{:<"+str(res_l) +"}"print(fmt.format(colorized_res), end="")
print()
if__name__=="__main__":
status=main(sys.argv[1:])
sys.exit(status)
# flake8: noqa: E501from .base_promptsimportCoderPromptsclassSingleWholeFileFunctionPrompts(CoderPrompts):
main_system="""Act as an expert software developer.Take requests for changes to the supplied code.If the request is ambiguous, ask questions.Once you understand the request you MUST use the `write_file` function to update the file to make the changes."""system_reminder="""ONLY return code using the `write_file` function.NEVER return code outside the `write_file` function."""files_content_prefix="Here is the current content of the file:\n"files_no_full_files="I am not sharing any files yet."redacted_edit_message="No changes are needed."# TODO: should this be present for using this with gpt-4?repo_content_prefix=None# TODO: fix the chat history, except we can't keep the whole file
not_unique_error = """UnifiedDiffNotUnique: hunk failed to apply!
{path} contains multiple sets of lines that match the diff you provided!
Try again.
Use additional lines to provide context that uniquely indicates which code needs to be changed.
The diff needs to apply to a unique set of lines in {path}!
{path} contains multiple copies of these {num_lines} lines:
{original}```
"""
other_hunks_applied = (
"Note: some hunks did apply successfully. See the updated source code shown above.\n\n"
)
class UnifiedDiffCoder(Coder):
"""A coder that uses unified diff format for code modifications."""
edit_format = "udiff"
gpt_prompts = UnifiedDiffPrompts()
def get_edits(self):
content = self.partial_response_content
# might raise ValueError for malformed ORIG/UPD blocks
raw_edits = list(find_diffs(content))
last_path = None
edits = []
for path, hunk in raw_edits:
if path:
last_path = path
else:
path = last_path
edits.append((path, hunk))
return edits
def apply_edits(self, edits):
seen = set()
uniq = []
for path, hunk in edits:
hunk = normalize_hunk(hunk)
if not hunk:
continue
this = [path + "\n"] + hunk
this = "".join(this)
if this in seen:
continue
seen.add(this)
uniq.append((path, hunk))
errors = []
for path, hunk in uniq:
full_path = self.abs_root_path(path)
content = self.io.read_text(full_path)
original, _ = hunk_to_before_after(hunk)
try:
content = do_replace(full_path, content, hunk)
except SearchTextNotUnique:
errors.append(
not_unique_error.format(
path=path, original=original, num_lines=len(original.splitlines())
)
)
continue
if not content:
errors.append(
no_match_error.format(
path=path, original=original, num_lines=len(original.splitlines())
)
)
continue
# SUCCESS!
self.io.write_text(full_path, content)
if errors:
errors = "\n\n".join(errors)
if len(errors) < len(uniq):
errors += other_hunks_applied
raise ValueError(errors)
def do_replace(fname, content, hunk):
fname = Path(fname)
before_text, after_text = hunk_to_before_after(hunk)
# does it want to make a new file?
if not fname.exists() and not before_text.strip():
fname.touch()
content = ""
if content is None:
return
# TODO: handle inserting into new file
if not before_text.strip():
# append to existing file, or start a new file
new_content = content + after_text
return new_content
new_content = None
new_content = apply_hunk(content, hunk)
if new_content:
return new_content
def collapse_repeats(s):
return "".join(k for k, g in groupby(s))
def apply_hunk(content, hunk):
before_text, after_text = hunk_to_before_after(hunk)
res = directly_apply_hunk(content, hunk)
if res:
return res
hunk = make_new_lines_explicit(content, hunk)
# just consider space vs not-space
ops = "".join([line[0] for line in hunk])
ops = ops.replace("-", "x")
ops = ops.replace("+", "x")
ops = ops.replace("\n", " ")
cur_op = " "
section = []
sections = []
for i in range(len(ops)):
op = ops[i]
if op != cur_op:
sections.append(section)
section = []
cur_op = op
section.append(hunk[i])
sections.append(section)
if cur_op != " ":
sections.append([])
all_done = True
for i in range(2, len(sections), 2):
preceding_context = sections[i - 2]
changes = sections[i - 1]
following_context = sections[i]
res = apply_partial_hunk(content, preceding_context, changes, following_context)
if res:
content = res
else:
all_done = False
# FAILED!
# this_hunk = preceding_context + changes + following_context
break
if all_done:
return content
def flexi_just_search_and_replace(texts):
strategies = [
(search_and_replace, all_preprocs),
]
return flexible_search_and_replace(texts, strategies)
def make_new_lines_explicit(content, hunk):
before, after = hunk_to_before_after(hunk)
diff = diff_lines(before, content)
back_diff = []
for line in diff:
if line[0] == "+":
continue
# if line[0] == "-":
# line = "+" + line[1:]
back_diff.append(line)
new_before = directly_apply_hunk(before, back_diff)
if not new_before:
return hunk
if len(new_before.strip()) < 10:
return hunk
before = before.splitlines(keepends=True)
new_before = new_before.splitlines(keepends=True)
after = after.splitlines(keepends=True)
if len(new_before) < len(before) * 0.66:
return hunk
new_hunk = difflib.unified_diff(new_before, after, n=max(len(new_before), len(after)))
new_hunk = list(new_hunk)[3:]
return new_hunk
def cleanup_pure_whitespace_lines(lines):
res = [
line if line.strip() else line[-(len(line) - len(line.rstrip("\r\n")))] for line in lines
]
return res
def normalize_hunk(hunk):
before, after = hunk_to_before_after(hunk, lines=True)
before = cleanup_pure_whitespace_lines(before)
after = cleanup_pure_whitespace_lines(after)
diff = difflib.unified_diff(before, after, n=max(len(before), len(after)))
diff = list(diff)[3:]
return diff
def directly_apply_hunk(content, hunk):
before, after = hunk_to_before_after(hunk)
if not before:
return
before_lines, _ = hunk_to_before_after(hunk, lines=True)
before_lines = "".join([line.strip() for line in before_lines])
# Refuse to do a repeated search and replace on a tiny bit of non-whitespace context
if len(before_lines) < 10 and content.count(before) > 1:
return
try:
new_content = flexi_just_search_and_replace([before, after, content])
except SearchTextNotUnique:
new_content = None
return new_content
def apply_partial_hunk(content, preceding_context, changes, following_context):
len_prec = len(preceding_context)
len_foll = len(following_context)
use_all = len_prec + len_foll
# if there is a - in the hunk, we can go all the way to `use=0`
for drop in range(use_all + 1):
use = use_all - drop
for use_prec in range(len_prec, -1, -1):
if use_prec > use:
continue
use_foll = use - use_prec
if use_foll > len_foll:
continue
if use_prec:
this_prec = preceding_context[-use_prec:]
else:
this_prec = []
this_foll = following_context[:use_foll]
res = directly_apply_hunk(content, this_prec + changes + this_foll)
if res:
return res
def find_diffs(content):
# We can always fence with triple-quotes, because all the udiff content
# is prefixed with +/-/space.
if not content.endswith("\n"):
content = content + "\n"
lines = content.splitlines(keepends=True)
line_num = 0
edits = []
while line_num < len(lines):
while line_num < len(lines):
line = lines[line_num]
if line.startswith("```diff"):
line_num, these_edits = process_fenced_block(lines, line_num + 1)
edits += these_edits
break
line_num += 1
# For now, just take 1!
# edits = edits[:1]
return edits
def process_fenced_block(lines, start_line_num):
for line_num in range(start_line_num, len(lines)):
line = lines[line_num]
if line.startswith("```"):
break
block = lines[start_line_num:line_num]
block.append("@@ @@")
if block[0].startswith("--- ") and block[1].startswith("+++ "):
# Extract the file path, considering that it might contain spaces
fname = block[1][4:].strip()
block = block[2:]
else:
fname = None
edits = []
keeper = False
hunk = []
op = " "
for line in block:
hunk.append(line)
if len(line) < 2:
continue
if line.startswith("+++ ") and hunk[-2].startswith("--- "):
if hunk[-3] == "\n":
hunk = hunk[:-3]
else:
hunk = hunk[:-2]
edits.append((fname, hunk))
hunk = []
keeper = False
fname = line[4:].strip()
continue
op = line[0]
if op in "-+":
keeper = True
continue
if op != "@":
continue
if not keeper:
hunk = []
continue
hunk = hunk[:-1]
edits.append((fname, hunk))
hunk = []
keeper = False
return line_num + 1, edits
def hunk_to_before_after(hunk, lines=False):
before = []
after = []
op = " "
for line in hunk:
if len(line) < 2:
op = " "
line = line
else:
op = line[0]
line = line[1:]
if op == " ":
before.append(line)
after.append(line)
elif op == "-":
before.append(line)
elif op == "+":
after.append(line)
if lines:
return before, after
before = "".join(before)
after = "".join(after)
return before, after
# flake8: noqa: E501from .base_promptsimportCoderPromptsclassUnifiedDiffPrompts(CoderPrompts):
main_system="""Act as an expert software developer.{lazy_prompt}Always use best practices when coding.Respect and use existing conventions, libraries, etc that are already present in the code base.Take requests for changes to the supplied code.If the request is ambiguous, ask questions.Always reply to the user in the same language they are using.For each file that needs to be changed, write out the changes similar to a unified diff like `diff -U0` would produce."""example_messages= [
dict(
role="user",
content="Replace is_prime with a call to sympy.",
),
dict(
role="assistant",
content="""Ok, Iwill:
1.Addanimportsofsympy.
2.Removetheis_prime() function.
3.Replacetheexistingcalltois_prime() withacalltosympy.isprime().
Herearethediffsforthosechanges:
```diff---mathweb/flask/app.py+++mathweb/flask/app.py
@@ ... @@
-classMathWeb:
+importsympy++classMathWeb:
@@ ... @@
-defis_prime(x):
-ifx<2:
-returnFalse-foriinrange(2, int(math.sqrt(x)) +1):
-ifx%i==0:
-returnFalse-returnTrue
@@ ... @@
-@app.route('/prime/<int:n>')
-defnth_prime(n):
-count=0-num=1-whilecount<n:
-num+=1-ifis_prime(num):
-count+=1-returnstr(num)
+@app.route('/prime/<int:n>')
+defnth_prime(n):
+count=0+num=1+whilecount<n:
+num+=1+ifsympy.isprime(num):
+count+=1+returnstr(num)
""",
),
]
system_reminder = """# File editing rules:
Return edits similar to unified diffs that diff -U0 would produce.
Make sure you include the first 2 lines with the file paths.
Don't include timestamps with the file paths.
Start each hunk of changes with a @@ ... @@ line.
Don't include line numbers like diff -U0 does.
The user's patch tool doesn't need them.
The user's patch tool needs CORRECT patches that apply cleanly against the current contents of the file!
Think carefully and make sure you include and mark all lines that need to be removed or changed as - lines.
Make sure you mark all new or modified lines with +.
Don't leave out any lines or the diff patch won't apply correctly.
Indentation matters in the diffs!
Start a new hunk for each section of the file that needs changes.
Only output hunks that specify changes with + or - lines.
Skip any hunks that are entirely unchanging lines.
Output hunks in whatever order makes the most sense.
Hunks don't need to be in any particular order.
When editing a function, method, loop, etc use a hunk to replace the entire code block.
Delete the entire existing version with - lines and then add a new, updated version with + lines.
This will help you generate correct code and correct diffs.
To move code within a file, use 2 hunks: 1 to delete it from its current location, 1 to insert it in the new location.
To make a new file, show a diff from --- /dev/null to +++ path/to/new/file.ext.
{lazy_prompt}
"""
paul-gauthier/aider/blob/main/aider/coders/wholefile_coder.py:
```py
from pathlib import Path
from aider import diffs
from ..dump import dump # noqa: F401
from .base_coder import Coder
from .wholefile_prompts import WholeFilePrompts
class WholeFileCoder(Coder):
"""A coder that operates on entire files for code modifications."""
edit_format = "whole"
gpt_prompts = WholeFilePrompts()
def update_cur_messages(self, edited):
if edited:
self.cur_messages += [
dict(role="assistant", content=self.gpt_prompts.redacted_edit_message)
]
else:
self.cur_messages += [dict(role="assistant", content=self.partial_response_content)]
def render_incremental_response(self, final):
try:
return self.get_edits(mode="diff")
except ValueError:
return self.get_multi_response_content()
def get_edits(self, mode="update"):
content = self.get_multi_response_content()
chat_files = self.get_inchat_relative_files()
output = []
lines = content.splitlines(keepends=True)
edits = []
saw_fname = None
fname = None
fname_source = None
new_lines = []
for i, line in enumerate(lines):
if line.startswith(self.fence[0]) or line.startswith(self.fence[1]):
if fname is not None:
# ending an existing block
saw_fname = None
full_path = self.abs_root_path(fname)
if mode == "diff":
output += self.do_live_diff(full_path, new_lines, True)
else:
edits.append((fname, fname_source, new_lines))
fname = None
fname_source = None
new_lines = []
continue
# fname==None ... starting a new block
if i > 0:
fname_source = "block"
fname = lines[i - 1].strip()
fname = fname.strip("*") # handle **filename.py**
fname = fname.rstrip(":")
fname = fname.strip("`")
# Did gpt prepend a bogus dir? It especially likes to
# include the path/to prefix from the one-shot example in
# the prompt.
if fname and fname not in chat_files and Path(fname).name in chat_files:
fname = Path(fname).name
if not fname: # blank line? or ``` was on first line i==0
if saw_fname:
fname = saw_fname
fname_source = "saw"
elif len(chat_files) == 1:
fname = chat_files[0]
fname_source = "chat"
else:
# TODO: sense which file it is by diff size
raise ValueError(
f"No filename provided before {self.fence[0]} in file listing"
)
elif fname is not None:
new_lines.append(line)
else:
for word in line.strip().split():
word = word.rstrip(".:,;!")
for chat_file in chat_files:
quoted_chat_file = f"`{chat_file}`"
if word == quoted_chat_file:
saw_fname = chat_file
output.append(line)
if mode == "diff":
if fname is not None:
# ending an existing block
full_path = (Path(self.root) / fname).absolute()
output += self.do_live_diff(full_path, new_lines, False)
return "\n".join(output)
if fname:
edits.append((fname, fname_source, new_lines))
seen = set()
refined_edits = []
# process from most reliable filename, to least reliable
for source in ("block", "saw", "chat"):
for fname, fname_source, new_lines in edits:
if fname_source != source:
continue
# if a higher priority source already edited the file, skip
if fname in seen:
continue
seen.add(fname)
refined_edits.append((fname, fname_source, new_lines))
return refined_edits
def apply_edits(self, edits):
for path, fname_source, new_lines in edits:
full_path = self.abs_root_path(path)
new_lines = "".join(new_lines)
self.io.write_text(full_path, new_lines)
def do_live_diff(self, full_path, new_lines, final):
if Path(full_path).exists():
orig_lines = self.io.read_text(full_path).splitlines(keepends=True)
show_diff = diffs.diff_partial_update(
orig_lines,
new_lines,
final=final,
).splitlines()
output = show_diff
else:
output = ["```"] + new_lines + ["```"]
return output
# flake8: noqa: E501from .base_promptsimportCoderPromptsclassWholeFileFunctionPrompts(CoderPrompts):
main_system="""Act as an expert software developer.Take requests for changes to the supplied code.If the request is ambiguous, ask questions.Once you understand the request you MUST use the `write_file` function to edit the files to make the needed changes."""system_reminder="""ONLY return code using the `write_file` function.NEVER return code outside the `write_file` function."""files_content_prefix="Here is the current content of the files:\n"files_no_full_files="I am not sharing any files yet."redacted_edit_message="No changes are needed."# TODO: should this be present for using this with gpt-4?repo_content_prefix=None# TODO: fix the chat history, except we can't keep the whole file
# flake8: noqa: E501from .base_promptsimportCoderPromptsclassWholeFilePrompts(CoderPrompts):
main_system="""Act as an expert software developer.Take requests for changes to the supplied code.If the request is ambiguous, ask questions.Always reply to the user in the same language they are using.{lazy_prompt}Once you understand the request you MUST:1. Determine if any code changes are needed.2. Explain any needed changes.3. If changes are needed, output a copy of each file that needs changes."""example_messages= [
dict(
role="user",
content="Change the greeting to be more casual",
),
dict(
role="assistant",
content="""Ok, I will:1. Switch the greeting text from "Hello" to "Hey".show_greeting.py{fence[0]}import sysdef greeting(name): print(f"Hey {{name}}")if __name__ == '__main__': greeting(sys.argv[1]){fence[1]}""",
),
]
system_reminder="""To suggest changes to a file you MUST return the entire content of the updated file.You MUST use this *file listing* format:path/to/filename.js{fence[0]}// entire file content ...// ... goes in between{fence[1]}Every *file listing* MUST use this format:- First line: the filename with any originally provided path- Second line: opening {fence[0]}- ... entire content of the file ...- Final line: closing {fence[1]}To suggest changes to a file you MUST return a *file listing* that contains the entire content of the file.*NEVER* skip, omit or elide content from a *file listing* using "..." or by adding comments like "... rest of code..."!Create a new file you MUST return a *file listing* which includes an appropriate filename, including any appropriate path.{lazy_prompt}"""redacted_edit_message="No changes are needed."
paul-gauthier/aider/blob/main/aider/commands.py:
importosimportreimportsubprocessimportsysimporttempfilefromcollectionsimportOrderedDictfrompathlibimportPathimportgitimportpyperclipfromPILimportImage, ImageGrabfromrich.textimportTextfromaiderimportmodels, prompts, voicefromaider.helpimportHelp, install_help_extrafromaider.llmimportlitellmfromaider.scrapeimportScraper, install_playwrightfromaider.utilsimportis_image_filefrom .dumpimportdump# noqa: F401classSwitchCoder(Exception):
def__init__(self, **kwargs):
self.kwargs=kwargsclassCommands:
voice=Nonescraper=Nonedef__init__(self, io, coder, voice_language=None, verify_ssl=True):
self.io=ioself.coder=coderself.verify_ssl=verify_sslifvoice_language=="auto":
voice_language=Noneself.voice_language=voice_languageself.help=Nonedefcmd_model(self, args):
"Switch to a new LLM"model_name=args.strip()
model=models.Model(model_name)
models.sanity_check_models(self.io, model)
raiseSwitchCoder(main_model=model)
defcmd_chat_mode(self, args):
"Switch to a new chat mode"fromaiderimportcodersef=args.strip()
valid_formats=OrderedDict(
sorted(
(
coder.edit_format,
coder.__doc__.strip().split("\n")[0] ifcoder.__doc__else"No description",
)
forcoderincoders.__all__ifgetattr(coder, "edit_format", None)
)
)
show_formats=OrderedDict(
[
("help", "Get help about using aider (usage, config, troubleshoot)."),
("ask", "Ask questions about your code without making any changes."),
("code", "Ask for changes to your code (using the best edit format)."),
]
)
ifefnotinvalid_formatsandefnotinshow_formats:
ifef:
self.io.tool_error(f'Chat mode "{ef}" should be one of these:\n')
else:
self.io.tool_output("Chat mode should be one of these:\n")
max_format_length=max(len(format) forformatinvalid_formats.keys())
forformat, descriptioninshow_formats.items():
self.io.tool_output(f"- {format:<{max_format_length}} : {description}")
self.io.tool_output("\nOr a valid edit format:\n")
forformat, descriptioninvalid_formats.items():
ifformatnotinshow_formats:
self.io.tool_output(f"- {format:<{max_format_length}} : {description}")
returnsummarize_from_coder=Trueedit_format=efifef=="code":
edit_format=self.coder.main_model.edit_formatsummarize_from_coder=Falseelifef=="ask":
summarize_from_coder=FalseraiseSwitchCoder(
edit_format=edit_format,
summarize_from_coder=summarize_from_coder,
)
defcompletions_model(self):
models=litellm.model_cost.keys()
returnmodelsdefcmd_models(self, args):
"Search the list of available models"args=args.strip()
ifargs:
models.print_matching_models(self.io, args)
else:
self.io.tool_output("Please provide a partial model name to search for.")
defcmd_web(self, args, paginate=True):
"Scrape a webpage, convert to markdown and add to the chat"url=args.strip()
ifnoturl:
self.io.tool_error("Please provide a URL to scrape.")
returnself.io.tool_output(f"Scraping {url}...")
ifnotself.scraper:
res=install_playwright(self.io)
ifnotres:
self.io.tool_error("Unable to initialize playwright.")
self.scraper=Scraper(
print_error=self.io.tool_error, playwright_available=res, verify_ssl=self.verify_ssl
)
content=self.scraper.scrape(url) or""content=f"{url}:\n\n"+contentself.io.tool_output("... done.")
ifpaginate:
withself.io.console.pager():
self.io.console.print(Text(content))
returncontentdefis_command(self, inp):
returninp[0] in"/!"defget_completions(self, cmd):
assertcmd.startswith("/")
cmd=cmd[1:]
fun=getattr(self, f"completions_{cmd}", None)
ifnotfun:
returnreturnsorted(fun())
defget_commands(self):
commands= []
forattrindir(self):
ifnotattr.startswith("cmd_"):
continuecmd=attr[4:]
cmd=cmd.replace("_", "-")
commands.append("/"+cmd)
returncommandsdefdo_run(self, cmd_name, args):
cmd_name=cmd_name.replace("-", "_")
cmd_method_name=f"cmd_{cmd_name}"cmd_method=getattr(self, cmd_method_name, None)
ifcmd_method:
returncmd_method(args)
else:
self.io.tool_output(f"Error: Command {cmd_name} not found.")
defmatching_commands(self, inp):
words=inp.strip().split()
ifnotwords:
returnfirst_word=words[0]
rest_inp=inp[len(words[0]) :]
all_commands=self.get_commands()
matching_commands= [cmdforcmdinall_commandsifcmd.startswith(first_word)]
returnmatching_commands, first_word, rest_inpdefrun(self, inp):
ifinp.startswith("!"):
returnself.do_run("run", inp[1:])
res=self.matching_commands(inp)
ifresisNone:
returnmatching_commands, first_word, rest_inp=resiflen(matching_commands) ==1:
returnself.do_run(matching_commands[0][1:], rest_inp)
eliffirst_wordinmatching_commands:
returnself.do_run(first_word[1:], rest_inp)
eliflen(matching_commands) >1:
self.io.tool_error(f"Ambiguous command: {', '.join(matching_commands)}")
else:
self.io.tool_error(f"Invalid command: {first_word}")
# any method called cmd_xxx becomes a command automatically.# each one must take an args param.defcmd_commit(self, args=None):
"Commit edits to the repo made outside the chat (commit message optional)"ifnotself.coder.repo:
self.io.tool_error("No git repository found.")
returnifnotself.coder.repo.is_dirty():
self.io.tool_error("No more changes to commit.")
returncommit_message=args.strip() ifargselseNoneself.coder.repo.commit(message=commit_message)
defcmd_lint(self, args="", fnames=None):
"Lint and fix provided files or in-chat files if none provided"ifnotself.coder.repo:
self.io.tool_error("No git repository found.")
returnifnotfnames:
fnames=self.coder.get_inchat_relative_files()
# If still no files, get all dirty files in the repoifnotfnamesandself.coder.repo:
fnames=self.coder.repo.get_dirty_files()
ifnotfnames:
self.io.tool_error("No dirty files to lint.")
returnfnames= [self.coder.abs_root_path(fname) forfnameinfnames]
lint_coder=Noneforfnameinfnames:
try:
errors=self.coder.linter.lint(fname)
exceptFileNotFoundErroraserr:
self.io.tool_error(f"Unable to lint {fname}")
self.io.tool_error(str(err))
continueifnoterrors:
continueself.io.tool_error(errors)
ifnotself.io.confirm_ask(f"Fix lint errors in {fname}?", default="y"):
continue# Commit everything before we start fixing lint errorsifself.coder.repo.is_dirty():
self.cmd_commit("")
ifnotlint_coder:
lint_coder=self.coder.clone(
# Clear the chat history, fnamescur_messages=[],
done_messages=[],
fnames=None,
)
lint_coder.add_rel_fname(fname)
lint_coder.run(errors)
lint_coder.abs_fnames=set()
iflint_coderandself.coder.repo.is_dirty():
self.cmd_commit("")
defcmd_clear(self, args):
"Clear the chat history"self.coder.done_messages= []
self.coder.cur_messages= []
defcmd_tokens(self, args):
"Report on the number of tokens used by the current chat context"res= []
self.coder.choose_fence()
# system messagesmain_sys=self.coder.fmt_system_prompt(self.coder.gpt_prompts.main_system)
main_sys+="\n"+self.coder.fmt_system_prompt(self.coder.gpt_prompts.system_reminder)
msgs= [
dict(role="system", content=main_sys),
dict(
role="system",
content=self.coder.fmt_system_prompt(self.coder.gpt_prompts.system_reminder),
),
]
tokens=self.coder.main_model.token_count(msgs)
res.append((tokens, "system messages", ""))
# chat historymsgs=self.coder.done_messages+self.coder.cur_messagesifmsgs:
tokens=self.coder.main_model.token_count(msgs)
res.append((tokens, "chat history", "use /clear to clear"))
# repo mapother_files=set(self.coder.get_all_abs_files()) -set(self.coder.abs_fnames)
ifself.coder.repo_map:
repo_content=self.coder.repo_map.get_repo_map(self.coder.abs_fnames, other_files)
ifrepo_content:
tokens=self.coder.main_model.token_count(repo_content)
res.append((tokens, "repository map", "use --map-tokens to resize"))
fence="`"*3# filesforfnameinself.coder.abs_fnames:
relative_fname=self.coder.get_rel_fname(fname)
content=self.io.read_text(fname)
ifis_image_file(relative_fname):
tokens=self.coder.main_model.token_count_for_image(fname)
else:
# approximatecontent=f"{relative_fname}\n{fence}\n"+content+"{fence}\n"tokens=self.coder.main_model.token_count(content)
res.append((tokens, f"{relative_fname}", "/drop to remove"))
# read-only filesforfnameinself.coder.abs_read_only_fnames:
relative_fname=self.coder.get_rel_fname(fname)
content=self.io.read_text(fname)
ifcontentisnotNoneandnotis_image_file(relative_fname):
# approximatecontent=f"{relative_fname}\n{fence}\n"+content+"{fence}\n"tokens=self.coder.main_model.token_count(content)
res.append((tokens, f"{relative_fname} (read-only)", "/drop to remove"))
self.io.tool_output(
f"Approximate context window usage for {self.coder.main_model.name}, in tokens:"
)
self.io.tool_output()
width=8cost_width=9deffmt(v):
returnformat(int(v), ",").rjust(width)
col_width=max(len(row[1]) forrowinres)
cost_pad=" "*cost_widthtotal=0total_cost=0.0fortk, msg, tipinres:
total+=tkcost=tk* (self.coder.main_model.info.get("input_cost_per_token") or0)
total_cost+=costmsg=msg.ljust(col_width)
self.io.tool_output(f"${cost:7.4f}{fmt(tk)}{msg}{tip}") # noqa: E231self.io.tool_output("="* (width+cost_width+1))
self.io.tool_output(f"${total_cost:7.4f}{fmt(total)} tokens total") # noqa: E231limit=self.coder.main_model.info.get("max_input_tokens") or0ifnotlimit:
returnremaining=limit-totalifremaining>1024:
self.io.tool_output(f"{cost_pad}{fmt(remaining)} tokens remaining in context window")
elifremaining>0:
self.io.tool_error(
f"{cost_pad}{fmt(remaining)} tokens remaining in context window (use /drop or"" /clear to make space)"
)
else:
self.io.tool_error(
f"{cost_pad}{fmt(remaining)} tokens remaining, window exhausted (use /drop or"" /clear to make space)"
)
self.io.tool_output(f"{cost_pad}{fmt(limit)} tokens max context window size")
defcmd_undo(self, args):
"Undo the last git commit if it was done by aider"ifnotself.coder.repo:
self.io.tool_error("No git repository found.")
returnlast_commit=self.coder.repo.repo.head.commitifnotlast_commit.parents:
self.io.tool_error("This is the first commit in the repository. Cannot undo.")
returnprev_commit=last_commit.parents[0]
changed_files_last_commit= [item.a_pathforiteminlast_commit.diff(prev_commit)]
forfnameinchanged_files_last_commit:
ifself.coder.repo.repo.is_dirty(path=fname):
self.io.tool_error(
f"The file {fname} has uncommitted changes. Please stash them before undoing."
)
return# Check if the file was in the repo in the previous committry:
prev_commit.tree[fname]
exceptKeyError:
self.io.tool_error(
f"The file {fname} was not in the repository in the previous commit. Cannot"" undo safely."
)
returnlocal_head=self.coder.repo.repo.git.rev_parse("HEAD")
current_branch=self.coder.repo.repo.active_branch.nametry:
remote_head=self.coder.repo.repo.git.rev_parse(f"origin/{current_branch}")
has_origin=Trueexceptgit.exc.GitCommandError:
has_origin=Falseifhas_origin:
iflocal_head==remote_head:
self.io.tool_error(
"The last commit has already been pushed to the origin. Undoing is not"" possible."
)
returnlast_commit_hash=self.coder.repo.repo.head.commit.hexsha[:7]
last_commit_message=self.coder.repo.repo.head.commit.message.strip()
iflast_commit_hashnotinself.coder.aider_commit_hashes:
self.io.tool_error("The last commit was not made by aider in this chat session.")
self.io.tool_error(
"You could try `/git reset --hard HEAD^` but be aware that this is a destructive"" command!"
)
return# Reset only the files which are part of `last_commit`forfile_pathinchanged_files_last_commit:
self.coder.repo.repo.git.checkout("HEAD~1", file_path)
# Move the HEAD back before the latest commitself.coder.repo.repo.git.reset("--soft", "HEAD~1")
self.io.tool_output(f"Removed: {last_commit_hash}{last_commit_message}")
# Get the current HEAD after undocurrent_head_hash=self.coder.repo.repo.head.commit.hexsha[:7]
current_head_message=self.coder.repo.repo.head.commit.message.strip()
self.io.tool_output(f"Now at: {current_head_hash}{current_head_message}")
ifself.coder.main_model.send_undo_reply:
returnprompts.undo_command_replydefcmd_diff(self, args=""):
"Display the diff of changes since the last message"ifnotself.coder.repo:
self.io.tool_error("No git repository found.")
returncurrent_head=self.coder.repo.get_head()
ifcurrent_headisNone:
self.io.tool_error("Unable to get current commit. The repository might be empty.")
returniflen(self.coder.commit_before_message) <2:
commit_before_message=current_head+"^"else:
commit_before_message=self.coder.commit_before_message[-2]
ifnotcommit_before_messageorcommit_before_message==current_head:
self.io.tool_error("No changes to display since the last message.")
returnself.io.tool_output(f"Diff since {commit_before_message[:7]}...")
diff=self.coder.repo.diff_commits(
self.coder.pretty,
commit_before_message,
"HEAD",
)
# don't use io.tool_output() because we don't want to log or further colorizeprint(diff)
defquote_fname(self, fname):
if" "infnameand'"'notinfname:
fname=f'"{fname}"'returnfnamedefcompletions_read(self):
returnself.completions_add()
defcompletions_add(self):
files=set(self.coder.get_all_relative_files())
files=files-set(self.coder.get_inchat_relative_files())
files= [self.quote_fname(fn) forfninfiles]
returnfilesdefglob_filtered_to_repo(self, pattern):
try:
ifos.path.isabs(pattern):
# Handle absolute pathsraw_matched_files= [Path(pattern)]
else:
raw_matched_files=list(Path(self.coder.root).glob(pattern))
exceptValueErroraserr:
self.io.tool_error(f"Error matching {pattern}: {err}")
raw_matched_files= []
matched_files= []
forfninraw_matched_files:
matched_files+=expand_subdir(fn)
matched_files= [
str(Path(fn).relative_to(self.coder.root))
forfninmatched_filesifPath(fn).is_relative_to(self.coder.root)
]
# if repo, filter against itifself.coder.repo:
git_files=self.coder.repo.get_tracked_files()
matched_files= [fnforfninmatched_filesifstr(fn) ingit_files]
res=list(map(str, matched_files))
returnresdefcmd_add(self, args):
"Add files to the chat so GPT can edit them or review them in detail"added_fnames= []
all_matched_files=set()
filenames=parse_quoted_filenames(args)
forwordinfilenames:
ifPath(word).is_absolute():
fname=Path(word)
else:
fname=Path(self.coder.root) /wordifself.coder.repoandself.coder.repo.ignored_file(fname):
self.io.tool_error(f"Skipping {fname} that matches aiderignore spec.")
continueiffname.exists():
iffname.is_file():
all_matched_files.add(str(fname))
continue# an existing dir, escape any special chars so they won't be globsword=re.sub(r"([\*\?\[\]])", r"[\1]", word)
matched_files=self.glob_filtered_to_repo(word)
ifmatched_files:
all_matched_files.update(matched_files)
continueifself.io.confirm_ask(f"No files matched '{word}'. Do you want to create {fname}?"):
if"*"instr(fname) or"?"instr(fname):
self.io.tool_error(f"Cannot create file with wildcard characters: {fname}")
else:
try:
fname.touch()
all_matched_files.add(str(fname))
exceptOSErrorase:
self.io.tool_error(f"Error creating file {fname}: {e}")
formatched_fileinall_matched_files:
abs_file_path=self.coder.abs_root_path(matched_file)
ifnotabs_file_path.startswith(self.coder.root) andnotis_image_file(matched_file):
self.io.tool_error(
f"Can not add {abs_file_path}, which is not within {self.coder.root}"
)
continueifabs_file_pathinself.coder.abs_fnames:
self.io.tool_error(f"{matched_file} is already in the chat")
elifabs_file_pathinself.coder.abs_read_only_fnames:
ifself.coder.repoandself.coder.repo.path_in_repo(matched_file):
self.coder.abs_read_only_fnames.remove(abs_file_path)
self.coder.abs_fnames.add(abs_file_path)
self.io.tool_output(
f"Moved {matched_file} from read-only to editable files in the chat"
)
added_fnames.append(matched_file)
else:
self.io.tool_error(
f"Cannot add {matched_file} as it's not part of the repository"
)
else:
ifis_image_file(matched_file) andnotself.coder.main_model.accepts_images:
self.io.tool_error(
f"Cannot add image file {matched_file} as the"f" {self.coder.main_model.name} does not support image.\nYou can run `aider"" --4-turbo-vision` to use GPT-4 Turbo with Vision."
)
continuecontent=self.io.read_text(abs_file_path)
ifcontentisNone:
self.io.tool_error(f"Unable to read {matched_file}")
else:
self.coder.abs_fnames.add(abs_file_path)
self.io.tool_output(f"Added {matched_file} to the chat")
self.coder.check_added_files()
added_fnames.append(matched_file)
defcompletions_drop(self):
files=self.coder.get_inchat_relative_files()
read_only_files= [self.coder.get_rel_fname(fn) forfninself.coder.abs_read_only_fnames]
all_files=files+read_only_filesall_files= [self.quote_fname(fn) forfninall_files]
returnall_filesdefcmd_drop(self, args=""):
"Remove files from the chat session to free up context space"ifnotargs.strip():
self.io.tool_output("Dropping all files from the chat session.")
self.coder.abs_fnames=set()
self.coder.abs_read_only_fnames=set()
returnfilenames=parse_quoted_filenames(args)
forwordinfilenames:
# Handle read-only files separately, without glob_filtered_to_reporead_only_matched= [fforfinself.coder.abs_read_only_fnamesifwordinf]
ifread_only_matched:
formatched_fileinread_only_matched:
self.coder.abs_read_only_fnames.remove(matched_file)
self.io.tool_output(f"Removed read-only file {matched_file} from the chat")
matched_files=self.glob_filtered_to_repo(word)
ifnotmatched_files:
matched_files.append(word)
formatched_fileinmatched_files:
abs_fname=self.coder.abs_root_path(matched_file)
ifabs_fnameinself.coder.abs_fnames:
self.coder.abs_fnames.remove(abs_fname)
self.io.tool_output(f"Removed {matched_file} from the chat")
defcmd_git(self, args):
"Run a git command"combined_output=Nonetry:
args="git "+argsenv=dict(subprocess.os.environ)
env["GIT_EDITOR"] ="true"result=subprocess.run(
args,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
env=env,
shell=True,
encoding=self.io.encoding,
errors="replace",
)
combined_output=result.stdoutexceptExceptionase:
self.io.tool_error(f"Error running /git command: {e}")
ifcombined_outputisNone:
returnself.io.tool_output(combined_output)
defcmd_test(self, args):
"Run a shell command and add the output to the chat on non-zero exit code"ifnotargsandself.coder.test_cmd:
args=self.coder.test_cmdifnotcallable(args):
returnself.cmd_run(args, True)
errors=args()
ifnoterrors:
returnself.io.tool_error(errors, strip=False)
returnerrorsdefcmd_run(self, args, add_on_nonzero_exit=False):
"Run a shell command and optionally add the output to the chat (alias: !)"combined_output=Noneinstructions=Nonetry:
result=subprocess.run(
args,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
shell=True,
encoding=self.io.encoding,
errors="replace",
)
combined_output=result.stdoutexceptExceptionase:
self.io.tool_error(f"Error running command: {e}")
ifcombined_outputisNone:
returnself.io.tool_output(combined_output)
ifadd_on_nonzero_exit:
add=result.returncode!=0else:
response=self.io.prompt_ask(
"Add the output to the chat?\n(y/n/instructions)", default=""
).strip()
ifresponse.lower() in ["yes", "y"]:
add=Trueelifresponse.lower() in ["no", "n"]:
add=Falseelse:
add=Trueinstructions=responseifadd:
forlineincombined_output.splitlines():
self.io.tool_output(line, log_only=True)
msg=prompts.run_output.format(
command=args,
output=combined_output,
)
ifinstructions:
msg=instructions+"\n\n"+msgreturnmsgdefcmd_exit(self, args):
"Exit the application"sys.exit()
defcmd_quit(self, args):
"Exit the application"sys.exit()
defcmd_ls(self, args):
"List all known files and indicate which are included in the chat session"files=self.coder.get_all_relative_files()
other_files= []
chat_files= []
read_only_files= []
forfileinfiles:
abs_file_path=self.coder.abs_root_path(file)
ifabs_file_pathinself.coder.abs_fnames:
chat_files.append(file)
else:
other_files.append(file)
# Add read-only filesforabs_file_pathinself.coder.abs_read_only_fnames:
rel_file_path=self.coder.get_rel_fname(abs_file_path)
read_only_files.append(rel_file_path)
ifnotchat_filesandnotother_filesandnotread_only_files:
self.io.tool_output("\nNo files in chat, git repo, or read-only list.")
returnifother_files:
self.io.tool_output("Repo files not in the chat:\n")
forfileinother_files:
self.io.tool_output(f" {file}")
ifread_only_files:
self.io.tool_output("\nRead-only files:\n")
forfileinread_only_files:
self.io.tool_output(f" {file}")
ifchat_files:
self.io.tool_output("\nFiles in chat:\n")
forfileinchat_files:
self.io.tool_output(f" {file}")
defbasic_help(self):
commands=sorted(self.get_commands())
pad=max(len(cmd) forcmdincommands)
pad="{cmd:"+str(pad) +"}"forcmdincommands:
cmd_method_name=f"cmd_{cmd[1:]}".replace("-", "_")
cmd_method=getattr(self, cmd_method_name, None)
cmd=pad.format(cmd=cmd)
ifcmd_method:
description=cmd_method.__doc__self.io.tool_output(f"{cmd}{description}")
else:
self.io.tool_output(f"{cmd} No description available.")
self.io.tool_output()
self.io.tool_output("Use `/help <question>` to ask questions about how to use aider.")
defcmd_help(self, args):
"Ask questions about aider"ifnotargs.strip():
self.basic_help()
returnfromaider.codersimportCoderifnotself.help:
res=install_help_extra(self.io)
ifnotres:
self.io.tool_error("Unable to initialize interactive help.")
returnself.help=Help()
coder=Coder.create(
io=self.io,
from_coder=self.coder,
edit_format="help",
summarize_from_coder=False,
map_tokens=512,
map_mul_no_files=1,
)
user_msg=self.help.ask(args)
user_msg+="""# Announcement lines from when this session of aider was launched:"""user_msg+="\n".join(self.coder.get_announcements()) +"\n"coder.run(user_msg, preproc=False)
ifself.coder.repo_map:
map_tokens=self.coder.repo_map.max_map_tokensmap_mul_no_files=self.coder.repo_map.map_mul_no_fileselse:
map_tokens=0map_mul_no_files=1raiseSwitchCoder(
edit_format=self.coder.edit_format,
summarize_from_coder=False,
from_coder=coder,
map_tokens=map_tokens,
map_mul_no_files=map_mul_no_files,
show_announcements=False,
)
defclone(self):
returnCommands(
self.io,
None,
voice_language=self.voice_language,
verify_ssl=self.verify_ssl,
)
defcmd_ask(self, args):
"Ask questions about the code base without editing any files"returnself._generic_chat_command(args, "ask")
defcmd_code(self, args):
"Ask for changes to your code"returnself._generic_chat_command(args, self.coder.main_model.edit_format)
def_generic_chat_command(self, args, edit_format):
ifnotargs.strip():
self.io.tool_error(f"Please provide a question or topic for the {edit_format} chat.")
returnfromaider.codersimportCodercoder=Coder.create(
io=self.io,
from_coder=self.coder,
edit_format=edit_format,
summarize_from_coder=False,
)
user_msg=argscoder.run(user_msg)
raiseSwitchCoder(
edit_format=self.coder.edit_format,
summarize_from_coder=False,
from_coder=coder,
show_announcements=False,
)
defget_help_md(self):
"Show help about all commands in markdown"res="""|Command|Description||:------|:----------|"""commands=sorted(self.get_commands())
forcmdincommands:
cmd_method_name=f"cmd_{cmd[1:]}".replace("-", "_")
cmd_method=getattr(self, cmd_method_name, None)
ifcmd_method:
description=cmd_method.__doc__res+=f"| **{cmd}** | {description} |\n"else:
res+=f"| **{cmd}** | |\n"res+="\n"returnresdefcmd_voice(self, args):
"Record and transcribe voice input"ifnotself.voice:
if"OPENAI_API_KEY"notinos.environ:
self.io.tool_error("To use /voice you must provide an OpenAI API key.")
returntry:
self.voice=voice.Voice()
exceptvoice.SoundDeviceError:
self.io.tool_error(
"Unable to import `sounddevice` and/or `soundfile`, is portaudio installed?"
)
returnhistory_iter=self.io.get_input_history()
history= []
size=0forlineinhistory_iter:
ifline.startswith("/"):
continueiflineinhistory:
continueifsize+len(line) >1024:
breaksize+=len(line)
history.append(line)
history.reverse()
history="\n".join(history)
try:
text=self.voice.record_and_transcribe(history, language=self.voice_language)
exceptlitellm.OpenAIErroraserr:
self.io.tool_error(f"Unable to use OpenAI whisper model: {err}")
returniftext:
self.io.add_to_input_history(text)
print()
self.io.user_input(text, log_only=False)
print()
returntextdefcmd_clipboard(self, args):
"Add image/text from the clipboard to the chat (optionally provide a name for the image)"try:
# Check for image firstimage=ImageGrab.grabclipboard()
ifisinstance(image, Image.Image):
ifargs.strip():
filename=args.strip()
ext=os.path.splitext(filename)[1].lower()
ifextin (".jpg", ".jpeg", ".png"):
basename=filenameelse:
basename=f"{filename}.png"else:
basename="clipboard_image.png"temp_dir=tempfile.mkdtemp()
temp_file_path=os.path.join(temp_dir, basename)
image_format="PNG"ifbasename.lower().endswith(".png") else"JPEG"image.save(temp_file_path, image_format)
abs_file_path=Path(temp_file_path).resolve()
# Check if a file with the same name already exists in the chatexisting_file=next(
(fforfinself.coder.abs_fnamesifPath(f).name==abs_file_path.name), None
)
ifexisting_file:
self.coder.abs_fnames.remove(existing_file)
self.io.tool_output(f"Replaced existing image in the chat: {existing_file}")
self.coder.abs_fnames.add(str(abs_file_path))
self.io.tool_output(f"Added clipboard image to the chat: {abs_file_path}")
self.coder.check_added_files()
return# If not an image, try to get texttext=pyperclip.paste()
iftext:
self.io.tool_output(text)
returntextself.io.tool_error("No image or text content found in clipboard.")
returnexceptExceptionase:
self.io.tool_error(f"Error processing clipboard content: {e}")
defcmd_read(self, args):
"Add a file to the chat that is for reference, not to be edited"ifnotargs.strip():
self.io.tool_error("Please provide a filename to read.")
returnfilename=args.strip()
abs_path=os.path.abspath(filename)
ifnotos.path.exists(abs_path):
self.io.tool_error(f"File not found: {abs_path}")
returnifnotos.path.isfile(abs_path):
self.io.tool_error(f"Not a file: {abs_path}")
returnself.coder.abs_read_only_fnames.add(abs_path)
self.io.tool_output(f"Added {abs_path} to read-only files.")
defcmd_map(self, args):
"Print out the current repository map"repo_map=self.coder.get_repo_map()
ifrepo_map:
self.io.tool_output(repo_map)
else:
self.io.tool_output("No repository map available.")
defexpand_subdir(file_path):
file_path=Path(file_path)
iffile_path.is_file():
yieldfile_pathreturniffile_path.is_dir():
forfileinfile_path.rglob("*"):
iffile.is_file():
yieldstr(file)
defparse_quoted_filenames(args):
filenames=re.findall(r"\"(.+?)\"|(\S+)", args)
filenames= [nameforsublistinfilenamesfornameinsublistifname]
returnfilenamesdefget_help_md():
fromaider.codersimportCoderfromaider.modelsimportModelcoder=Coder(Model("gpt-3.5-turbo"), None)
md=coder.commands.get_help_md()
returnmddefmain():
md=get_help_md()
print(md)
if__name__=="__main__":
status=main()
sys.exit(status)
paul-gauthier/aider/blob/main/aider/diffs.py:
importdifflibimportsysfrom .dumpimportdump# noqa: F401defmain():
iflen(sys.argv) !=3:
print("Usage: python diffs.py file1 file")
sys.exit(1)
file_orig, file_updated=sys.argv[1], sys.argv[2]
withopen(file_orig, "r", encoding="utf-8") asf:
lines_orig=f.readlines()
withopen(file_updated, "r", encoding="utf-8") asf:
lines_updated=f.readlines()
foriinrange(len(file_updated)):
res=diff_partial_update(lines_orig, lines_updated[:i])
print(res)
input()
defcreate_progress_bar(percentage):
block="█"empty="░"total_blocks=30filled_blocks=int(total_blocks*percentage//100)
empty_blocks=total_blocks-filled_blocksbar=block*filled_blocks+empty*empty_blocksreturnbardefassert_newlines(lines):
ifnotlines:
returnforlineinlines[:-1]:
assertlineandline[-1] =="\n", linedefdiff_partial_update(lines_orig, lines_updated, final=False, fname=None):
""" Given only the first part of an updated file, show the diff while ignoring the block of "deleted" lines that are past the end of the partially complete update. """# dump(lines_orig)# dump(lines_updated)assert_newlines(lines_orig)
assert_newlines(lines_orig)
num_orig_lines=len(lines_orig)
iffinal:
last_non_deleted=num_orig_lineselse:
last_non_deleted=find_last_non_deleted(lines_orig, lines_updated)
# dump(last_non_deleted)iflast_non_deletedisNone:
return""ifnum_orig_lines:
pct=last_non_deleted*100/num_orig_lineselse:
pct=50bar=create_progress_bar(pct)
bar=f" {last_non_deleted:3d} / {num_orig_lines:3d} lines [{bar}] {pct:3.0f}%\n"lines_orig=lines_orig[:last_non_deleted]
ifnotfinal:
lines_updated=lines_updated[:-1] + [bar]
diff=difflib.unified_diff(lines_orig, lines_updated, n=5)
diff=list(diff)[2:]
diff="".join(diff)
ifnotdiff.endswith("\n"):
diff+="\n"foriinrange(3, 10):
backticks="`"*iifbackticksnotindiff:
breakshow=f"{backticks}diff\n"iffname:
show+=f"--- {fname} original\n"show+=f"+++ {fname} updated\n"show+=diffshow+=f"{backticks}\n\n"# print(diff)returnshowdeffind_last_non_deleted(lines_orig, lines_updated):
diff=list(difflib.ndiff(lines_orig, lines_updated))
num_orig=0last_non_deleted_orig=Noneforlineindiff:
# print(f"{num_orig:2d} {num_updated:2d} {line}", end="")code=line[0]
ifcode==" ":
num_orig+=1last_non_deleted_orig=num_origelifcode=="-":
# line only in orignum_orig+=1elifcode=="+":
# line only in updatedpassreturnlast_non_deleted_origif__name__=="__main__":
main()
#!/usr/bin/env pythonimportosimportrandomimportsysimportstreamlitasstfromaiderimporturlsfromaider.codersimportCoderfromaider.dumpimportdump# noqa: F401fromaider.ioimportInputOutputfromaider.mainimportmainascli_mainfromaider.scrapeimportScraperclassCaptureIO(InputOutput):
lines= []
deftool_output(self, msg, log_only=False):
ifnotlog_only:
self.lines.append(msg)
super().tool_output(msg, log_only=log_only)
deftool_error(self, msg):
self.lines.append(msg)
super().tool_error(msg)
defget_captured_lines(self):
lines=self.linesself.lines= []
returnlinesdefsearch(text=None):
results= []
forroot, _, filesinos.walk("aider"):
forfileinfiles:
path=os.path.join(root, file)
ifnottextortextinpath:
results.append(path)
# dump(results)returnresults# Keep state as a resource, which survives browser reloads (since Coder does too)classState:
keys=set()
definit(self, key, val=None):
ifkeyinself.keys:
returnself.keys.add(key)
setattr(self, key, val)
returnTrue@st.cache_resourcedefget_state():
returnState()
@st.cache_resourcedefget_coder():
coder=cli_main(return_coder=True)
ifnotisinstance(coder, Coder):
raiseValueError(coder)
ifnotcoder.repo:
raiseValueError("GUI can currently only be used inside a git repo")
io=CaptureIO(
pretty=False,
yes=True,
dry_run=coder.io.dry_run,
encoding=coder.io.encoding,
)
# coder.io = io # this breaks the input_historycoder.commands.io=ioforlineincoder.get_announcements():
coder.io.tool_output(line)
returncoderclassGUI:
prompt=Noneprompt_as="user"last_undo_empty=Nonerecent_msgs_empty=Noneweb_content_empty=Nonedefannounce(self):
lines=self.coder.get_announcements()
lines=" \n".join(lines)
returnlinesdefshow_edit_info(self, edit):
commit_hash=edit.get("commit_hash")
commit_message=edit.get("commit_message")
diff=edit.get("diff")
fnames=edit.get("fnames")
iffnames:
fnames=sorted(fnames)
ifnotcommit_hashandnotfnames:
returnshow_undo=Falseres=""ifcommit_hash:
res+=f"Commit `{commit_hash}`: {commit_message}\n"ifcommit_hash==self.coder.last_aider_commit_hash:
show_undo=Trueiffnames:
fnames= [f"`{fname}`"forfnameinfnames]
fnames=", ".join(fnames)
res+=f"Applied edits to {fnames}."ifdiff:
withst.expander(res):
st.code(diff, language="diff")
ifshow_undo:
self.add_undo(commit_hash)
else:
withst.container(border=True):
st.write(res)
ifshow_undo:
self.add_undo(commit_hash)
defadd_undo(self, commit_hash):
ifself.last_undo_empty:
self.last_undo_empty.empty()
self.last_undo_empty=st.empty()
undone=self.state.last_undone_commit_hash==commit_hashifnotundone:
withself.last_undo_empty:
ifself.button(f"Undo commit `{commit_hash}`", key=f"undo_{commit_hash}"):
self.do_undo(commit_hash)
defdo_sidebar(self):
withst.sidebar:
st.title("Aider")
# self.cmds_tab, self.settings_tab = st.tabs(["Commands", "Settings"])# self.do_recommended_actions()self.do_add_to_chat()
self.do_recent_msgs()
self.do_clear_chat_history()
# st.container(height=150, border=False)# st.write("### Experimental")st.warning(
"This browser version of aider is experimental. Please share feedback in [GitHub"" issues](https://github.com/paul-gauthier/aider/issues)."
)
defdo_settings_tab(self):
passdefdo_recommended_actions(self):
text="Aider works best when your code is stored in a git repo. \n"text+=f"[See the FAQ for more info]({urls.git})"withst.expander("Recommended actions", expanded=True):
withst.popover("Create a git repo to track changes"):
st.write(text)
self.button("Create git repo", key=random.random(), help="?")
withst.popover("Update your `.gitignore` file"):
st.write("It's best to keep aider's internal files out of your git repo.")
self.button("Add `.aider*` to `.gitignore`", key=random.random(), help="?")
defdo_add_to_chat(self):
# with st.expander("Add to the chat", expanded=True):self.do_add_files()
self.do_add_web_page()
defdo_add_files(self):
fnames=st.multiselect(
"Add files to the chat",
self.coder.get_all_relative_files(),
default=self.state.initial_inchat_files,
placeholder="Files to edit",
disabled=self.prompt_pending(),
help=(
"Only add the files that need to be *edited* for the task you are working"" on. Aider will pull in other relevant code to provide context to the LLM."
),
)
forfnameinfnames:
iffnamenotinself.coder.get_inchat_relative_files():
self.coder.add_rel_fname(fname)
self.info(f"Added {fname} to the chat")
forfnameinself.coder.get_inchat_relative_files():
iffnamenotinfnames:
self.coder.drop_rel_fname(fname)
self.info(f"Removed {fname} from the chat")
defdo_add_web_page(self):
withst.popover("Add a web page to the chat"):
self.do_web()
defdo_add_image(self):
withst.popover("Add image"):
st.markdown("Hello World 👋")
st.file_uploader("Image file", disabled=self.prompt_pending())
defdo_run_shell(self):
withst.popover("Run shell commands, tests, etc"):
st.markdown(
"Run a shell command and optionally share the output with the LLM. This is"" a great way to run your program or run tests and have the LLM fix bugs."
)
st.text_input("Command:")
st.radio(
"Share the command output with the LLM?",
[
"Review the output and decide whether to share",
"Automatically share the output on non-zero exit code (ie, if any tests fail)",
],
)
st.selectbox(
"Recent commands",
[
"my_app.py --doit",
"my_app.py --cleanup",
],
disabled=self.prompt_pending(),
)
defdo_tokens_and_cost(self):
withst.expander("Tokens and costs", expanded=True):
passdefdo_show_token_usage(self):
withst.popover("Show token usage"):
st.write("hi")
defdo_clear_chat_history(self):
text="Saves tokens, reduces confusion"ifself.button("Clear chat history", help=text):
self.coder.done_messages= []
self.coder.cur_messages= []
self.info("Cleared chat history. Now the LLM can't see anything before this line.")
defdo_show_metrics(self):
st.metric("Cost of last message send & reply", "$0.0019", help="foo")
st.metric("Cost to send next message", "$0.0013", help="foo")
st.metric("Total cost this session", "$0.22")
defdo_git(self):
withst.expander("Git", expanded=False):
# st.button("Show last diff")# st.button("Undo last commit")self.button("Commit any pending changes")
withst.popover("Run git command"):
st.markdown("## Run git command")
st.text_input("git", value="git ")
self.button("Run")
st.selectbox(
"Recent git commands",
[
"git checkout -b experiment",
"git stash",
],
disabled=self.prompt_pending(),
)
defdo_recent_msgs(self):
ifnotself.recent_msgs_empty:
self.recent_msgs_empty=st.empty()
ifself.prompt_pending():
self.recent_msgs_empty.empty()
self.state.recent_msgs_num+=1withself.recent_msgs_empty:
self.old_prompt=st.selectbox(
"Resend a recent chat message",
self.state.input_history,
placeholder="Choose a recent chat message",
# label_visibility="collapsed",index=None,
key=f"recent_msgs_{self.state.recent_msgs_num}",
disabled=self.prompt_pending(),
)
ifself.old_prompt:
self.prompt=self.old_promptdefdo_messages_container(self):
self.messages=st.container()
# stuff a bunch of vertical whitespace at the top# to get all the chat text to the bottom# self.messages.container(height=300, border=False)withself.messages:
formsginself.state.messages:
role=msg["role"]
ifrole=="edit":
self.show_edit_info(msg)
elifrole=="info":
st.info(msg["content"])
elifrole=="text":
text=msg["content"]
line=text.splitlines()[0]
withself.messages.expander(line):
st.text(text)
elifrolein ("user", "assistant"):
withst.chat_message(role):
st.write(msg["content"])
# self.cost()else:
st.dict(msg)
definitialize_state(self):
messages= [
dict(role="info", content=self.announce()),
dict(role="assistant", content="How can I help you?"),
]
self.state.init("messages", messages)
self.state.init("last_aider_commit_hash", self.coder.last_aider_commit_hash)
self.state.init("last_undone_commit_hash")
self.state.init("recent_msgs_num", 0)
self.state.init("web_content_num", 0)
self.state.init("prompt")
self.state.init("scraper")
self.state.init("initial_inchat_files", self.coder.get_inchat_relative_files())
if"input_history"notinself.state.keys:
input_history=list(self.coder.io.get_input_history())
seen=set()
input_history= [xforxininput_historyifnot (xinseenorseen.add(x))]
self.state.input_history=input_historyself.state.keys.add("input_history")
defbutton(self, args, **kwargs):
"Create a button, disabled if prompt pending"# Force everything to be disabled if there is a prompt pendingifself.prompt_pending():
kwargs["disabled"] =Truereturnst.button(args, **kwargs)
def__init__(self):
self.coder=get_coder()
self.state=get_state()
# Force the coder to cooperate, regardless of cmd line argsself.coder.yield_stream=Trueself.coder.stream=Trueself.coder.pretty=Falseself.initialize_state()
self.do_messages_container()
self.do_sidebar()
user_inp=st.chat_input("Say something")
ifuser_inp:
self.prompt=user_inpifself.prompt_pending():
self.process_chat()
ifnotself.prompt:
returnself.state.prompt=self.promptifself.prompt_as=="user":
self.coder.io.add_to_input_history(self.prompt)
self.state.input_history.append(self.prompt)
ifself.prompt_as:
self.state.messages.append({"role": self.prompt_as, "content": self.prompt})
ifself.prompt_as=="user":
withself.messages.chat_message("user"):
st.write(self.prompt)
elifself.prompt_as=="text":
line=self.prompt.splitlines()[0]
line+="??"withself.messages.expander(line):
st.text(self.prompt)
# re-render the UI for the prompt_pending statest.rerun()
defprompt_pending(self):
returnself.state.promptisnotNonedefcost(self):
cost=random.random() *0.003+0.001st.caption(f"${cost:0.4f}")
defprocess_chat(self):
prompt=self.state.promptself.state.prompt=None# This duplicates logic from within Coderself.num_reflections=0self.max_reflections=3whileprompt:
withself.messages.chat_message("assistant"):
res=st.write_stream(self.coder.run_stream(prompt))
self.state.messages.append({"role": "assistant", "content": res})
# self.cost()prompt=Noneifself.coder.reflected_message:
ifself.num_reflections<self.max_reflections:
self.num_reflections+=1self.info(self.coder.reflected_message)
prompt=self.coder.reflected_messagewithself.messages:
edit=dict(
role="edit",
fnames=self.coder.aider_edited_files,
)
ifself.state.last_aider_commit_hash!=self.coder.last_aider_commit_hash:
edit["commit_hash"] =self.coder.last_aider_commit_hashedit["commit_message"] =self.coder.last_aider_commit_messagecommits=f"{self.coder.last_aider_commit_hash}~1"diff=self.coder.repo.diff_commits(
self.coder.pretty,
commits,
self.coder.last_aider_commit_hash,
)
edit["diff"] =diffself.state.last_aider_commit_hash=self.coder.last_aider_commit_hashself.state.messages.append(edit)
self.show_edit_info(edit)
# re-render the UI for the non-prompt_pending statest.rerun()
definfo(self, message, echo=True):
info=dict(role="info", content=message)
self.state.messages.append(info)
# We will render the tail of the messages array after this callifecho:
self.messages.info(message)
defdo_web(self):
st.markdown("Add the text content of a web page to the chat")
ifnotself.web_content_empty:
self.web_content_empty=st.empty()
ifself.prompt_pending():
self.web_content_empty.empty()
self.state.web_content_num+=1withself.web_content_empty:
self.web_content=st.text_input(
"URL",
placeholder="https://...",
key=f"web_content_{self.state.web_content_num}",
)
ifnotself.web_content:
returnurl=self.web_contentifnotself.state.scraper:
self.scraper=Scraper(print_error=self.info)
content=self.scraper.scrape(url) or""ifcontent.strip():
content=f"{url}\n\n"+contentself.prompt=contentself.prompt_as="text"else:
self.info(f"No web content found for `{url}`.")
self.web_content=Nonedefdo_undo(self, commit_hash):
self.last_undo_empty.empty()
if (
self.state.last_aider_commit_hash!=commit_hashorself.coder.last_aider_commit_hash!=commit_hash
):
self.info(f"Commit `{commit_hash}` is not the latest commit.")
returnself.coder.commands.io.get_captured_lines()
reply=self.coder.commands.cmd_undo(None)
lines=self.coder.commands.io.get_captured_lines()
lines="\n".join(lines)
lines=lines.splitlines()
lines=" \n".join(lines)
self.info(lines, echo=False)
self.state.last_undone_commit_hash=commit_hashifreply:
self.prompt_as=Noneself.prompt=replydefgui_main():
st.set_page_config(
layout="wide",
page_title="Aider",
page_icon=urls.favicon,
menu_items={
"Get Help": urls.website,
"Report a bug": "https://github.com/paul-gauthier/aider/issues",
"About": "# Aider\nAI pair programming in your browser.",
},
)
# config_options = st.config._config_options# for key, value in config_options.items():# print(f"{key}: {value.value}")GUI()
if__name__=="__main__":
status=gui_main()
sys.exit(status)
importconfigparserimportosimportreimportsysimportthreadingfrompathlibimportPathimportgitfromdotenvimportload_dotenvfromprompt_toolkit.enumsimportEditingModefromaiderimport__version__, models, utilsfromaider.argsimportget_parserfromaider.codersimportCoderfromaider.commandsimportCommands, SwitchCoderfromaider.historyimportChatSummaryfromaider.ioimportInputOutputfromaider.llmimportlitellm# noqa: F401; properly init litellm on launchfromaider.repoimportGitRepofromaider.versioncheckimportcheck_versionfrom .dumpimportdump# noqa: F401defget_git_root():
"""Try and guess the git repo, since the conf.yml can be at the repo root"""try:
repo=git.Repo(search_parent_directories=True)
returnrepo.working_tree_direxceptgit.InvalidGitRepositoryError:
returnNonedefguessed_wrong_repo(io, git_root, fnames, git_dname):
"""After we parse the args, we can determine the real repo. Did we guess wrong?"""try:
check_repo=Path(GitRepo(io, fnames, git_dname).root).resolve()
exceptFileNotFoundError:
return# we had no guess, rely on the "true" repo resultifnotgit_root:
returnstr(check_repo)
git_root=Path(git_root).resolve()
ifcheck_repo==git_root:
returnreturnstr(check_repo)
defsetup_git(git_root, io):
repo=Noneifgit_root:
repo=git.Repo(git_root)
elifio.confirm_ask("No git repo found, create one to track GPT's changes (recommended)?"):
git_root=str(Path.cwd().resolve())
repo=git.Repo.init(git_root)
io.tool_output("Git repository created in the current working directory.")
check_gitignore(git_root, io, False)
ifnotrepo:
returnuser_name=Noneuser_email=Nonewithrepo.config_reader() asconfig:
try:
user_name=config.get_value("user", "name", None)
except (configparser.NoSectionError, configparser.NoOptionError):
passtry:
user_email=config.get_value("user", "email", None)
exceptconfigparser.NoSectionError:
passifuser_nameanduser_email:
returnrepo.working_tree_dirwithrepo.config_writer() asgit_config:
ifnotuser_name:
git_config.set_value("user", "name", "Your Name")
io.tool_error('Update git name with: git config user.name "Your Name"')
ifnotuser_email:
git_config.set_value("user", "email", "[email protected]")
io.tool_error('Update git email with: git config user.email "[email protected]"')
returnrepo.working_tree_dirdefcheck_gitignore(git_root, io, ask=True):
ifnotgit_root:
returntry:
repo=git.Repo(git_root)
ifrepo.ignored(".aider"):
returnexceptgit.exc.InvalidGitRepositoryError:
passpat=".aider*"gitignore_file=Path(git_root) /".gitignore"ifgitignore_file.exists():
content=io.read_text(gitignore_file)
ifcontentisNone:
returnifpatincontent.splitlines():
returnelse:
content=""ifaskandnotio.confirm_ask(f"Add {pat} to .gitignore (recommended)?"):
returnifcontentandnotcontent.endswith("\n"):
content+="\n"content+=pat+"\n"io.write_text(gitignore_file, content)
io.tool_output(f"Added {pat} to .gitignore")
defformat_settings(parser, args):
show=scrub_sensitive_info(args, parser.format_values())
# clean up the headings for consistency w/ new linesheading_env="Environment Variables:"heading_defaults="Defaults:"ifheading_envinshow:
show=show.replace(heading_env, "\n"+heading_env)
show=show.replace(heading_defaults, "\n"+heading_defaults)
show+="\n"show+="Option settings:\n"forarg, valinsorted(vars(args).items()):
ifval:
val=scrub_sensitive_info(args, str(val))
show+=f" - {arg}: {val}\n"# noqa: E221returnshowdefscrub_sensitive_info(args, text):
# Replace sensitive information with last 4 charactersiftextandargs.openai_api_key:
last_4=args.openai_api_key[-4:]
text=text.replace(args.openai_api_key, f"...{last_4}")
iftextandargs.anthropic_api_key:
last_4=args.anthropic_api_key[-4:]
text=text.replace(args.anthropic_api_key, f"...{last_4}")
returntextdefcheck_streamlit_install(io):
returnutils.check_pip_install_extra(
io,
"streamlit",
"You need to install the aider browser feature",
["aider-chat[browser]"],
)
deflaunch_gui(args):
fromstreamlit.webimportclifromaiderimportguiprint()
print("CONTROL-C to exit...")
target=gui.__file__st_args= ["run", target]
st_args+= [
"--browser.gatherUsageStats=false",
"--runner.magicEnabled=false",
"--server.runOnSave=false",
]
if"-dev"in__version__:
print("Watching for file changes.")
else:
st_args+= [
"--global.developmentMode=false",
"--server.fileWatcherType=none",
"--client.toolbarMode=viewer", # minimal?
]
st_args+= ["--"] +argscli.main(st_args)
# from click.testing import CliRunner# runner = CliRunner()# from streamlit.web import bootstrap# bootstrap.load_config_options(flag_options={})# cli.main_run(target, args)# sys.argv = ['streamlit', 'run', '--'] + argsdefparse_lint_cmds(lint_cmds, io):
err=Falseres=dict()
forlint_cmdinlint_cmds:
ifre.match(r"^[a-z]+:.*", lint_cmd):
pieces=lint_cmd.split(":")
lang=pieces[0]
cmd=lint_cmd[len(lang) +1 :]
lang=lang.strip()
else:
lang=Nonecmd=lint_cmdcmd=cmd.strip()
ifcmd:
res[lang] =cmdelse:
io.tool_error(f'Unable to parse --lint-cmd "{lint_cmd}"')
io.tool_error('The arg should be "language: cmd --args ..."')
io.tool_error('For example: --lint-cmd "python: flake8 --select=E9"')
err=Trueiferr:
returnreturnresdefgenerate_search_path_list(default_fname, git_root, command_line_file):
files= []
default_file=Path(default_fname)
files.append(Path.home() /default_file) # homedirifgit_root:
files.append(Path(git_root) /default_file) # git rootfiles.append(default_file.resolve())
ifcommand_line_file:
files.append(command_line_file)
files= [Path(fn).resolve() forfninfiles]
files.reverse()
uniq= []
forfninfiles:
iffnnotinuniq:
uniq.append(fn)
uniq.reverse()
files=uniqfiles=list(map(str, files))
files=list(dict.fromkeys(files))
returnfilesdefregister_models(git_root, model_settings_fname, io, verbose=False):
model_settings_files=generate_search_path_list(
".aider.model.settings.yml", git_root, model_settings_fname
)
try:
files_loaded=models.register_models(model_settings_files)
iflen(files_loaded) >0:
ifverbose:
io.tool_output("Loaded model settings from:")
forfile_loadedinfiles_loaded:
io.tool_output(f" - {file_loaded}") # noqa: E221elifverbose:
io.tool_output("No model settings files loaded")
exceptExceptionase:
io.tool_error(f"Error loading aider model settings: {e}")
return1ifverbose:
io.tool_output("Searched for model settings files:")
forfileinmodel_settings_files:
io.tool_output(f" - {file}")
returnNonedefload_dotenv_files(git_root, dotenv_fname):
dotenv_files=generate_search_path_list(
".env",
git_root,
dotenv_fname,
)
loaded= []
forfnameindotenv_files:
ifPath(fname).exists():
loaded.append(fname)
load_dotenv(fname, override=True)
returnloadeddefregister_litellm_models(git_root, model_metadata_fname, io, verbose=False):
model_metatdata_files=generate_search_path_list(
".aider.model.metadata.json", git_root, model_metadata_fname
)
try:
model_metadata_files_loaded=models.register_litellm_models(model_metatdata_files)
iflen(model_metadata_files_loaded) >0andverbose:
io.tool_output("Loaded model metadata from:")
formodel_metadata_fileinmodel_metadata_files_loaded:
io.tool_output(f" - {model_metadata_file}") # noqa: E221exceptExceptionase:
io.tool_error(f"Error loading model metadata models: {e}")
return1defmain(argv=None, input=None, output=None, force_git_root=None, return_coder=False):
ifargvisNone:
argv=sys.argv[1:]
ifforce_git_root:
git_root=force_git_rootelse:
git_root=get_git_root()
conf_fname=Path(".aider.conf.yml")
default_config_files= [conf_fname.resolve()] # CWDifgit_root:
git_conf=Path(git_root) /conf_fname# git rootifgit_confnotindefault_config_files:
default_config_files.append(git_conf)
default_config_files.append(Path.home() /conf_fname) # homedirdefault_config_files=list(map(str, default_config_files))
parser=get_parser(default_config_files, git_root)
args, unknown=parser.parse_known_args(argv)
# Load the .env file specified in the argumentsloaded_dotenvs=load_dotenv_files(git_root, args.env_file)
# Parse again to include any arguments that might have been defined in .envargs=parser.parse_args(argv)
ifnotargs.verify_ssl:
importhttpxlitellm._load_litellm()
litellm._lazy_module.client_session=httpx.Client(verify=False)
ifargs.dark_mode:
args.user_input_color="#32FF32"args.tool_error_color="#FF3333"args.assistant_output_color="#00FFFF"args.code_theme="monokai"ifargs.light_mode:
args.user_input_color="green"args.tool_error_color="red"args.assistant_output_color="blue"args.code_theme="default"ifreturn_coderandargs.yesisNone:
args.yes=Trueediting_mode=EditingMode.VIifargs.vimelseEditingMode.EMACSio=InputOutput(
args.pretty,
args.yes,
args.input_history_file,
args.chat_history_file,
input=input,
output=output,
user_input_color=args.user_input_color,
tool_output_color=args.tool_output_color,
tool_error_color=args.tool_error_color,
dry_run=args.dry_run,
encoding=args.encoding,
llm_history_file=args.llm_history_file,
editingmode=editing_mode,
)
ifargs.guiandnotreturn_coder:
ifnotcheck_streamlit_install(io):
returnlaunch_gui(argv)
returnifargs.verbose:
forfnameinloaded_dotenvs:
io.tool_output(f"Loaded {fname}")
all_files=args.files+ (args.fileor [])
fnames= [str(Path(fn).resolve()) forfninall_files]
read_only_fnames= [str(Path(fn).resolve()) forfnin (args.reador [])]
iflen(all_files) >1:
good=Trueforfnameinall_files:
ifPath(fname).is_dir():
io.tool_error(f"{fname} is a directory, not provided alone.")
good=Falseifnotgood:
io.tool_error(
"Provide either a single directory of a git repo, or a list of one or more files."
)
return1git_dname=Noneiflen(all_files) ==1:
ifPath(all_files[0]).is_dir():
ifargs.git:
git_dname=str(Path(all_files[0]).resolve())
fnames= []
else:
io.tool_error(f"{all_files[0]} is a directory, but --no-git selected.")
return1# We can't know the git repo for sure until after parsing the args.# If we guessed wrong, reparse because that changes things like# the location of the config.yml and history files.ifargs.gitandnotforce_git_root:
right_repo_root=guessed_wrong_repo(io, git_root, fnames, git_dname)
ifright_repo_root:
returnmain(argv, input, output, right_repo_root, return_coder=return_coder)
ifargs.just_check_update:
update_available=check_version(io, just_check=True, verbose=args.verbose)
return0ifnotupdate_availableelse1ifargs.check_update:
check_version(io, verbose=args.verbose)
ifargs.models:
models.print_matching_models(io, args.models)
return0ifargs.git:
git_root=setup_git(git_root, io)
ifargs.gitignore:
check_gitignore(git_root, io)
ifargs.verbose:
show=format_settings(parser, args)
io.tool_output(show)
cmd_line=" ".join(sys.argv)
cmd_line=scrub_sensitive_info(args, cmd_line)
io.tool_output(cmd_line, log_only=True)
ifargs.anthropic_api_key:
os.environ["ANTHROPIC_API_KEY"] =args.anthropic_api_keyifargs.openai_api_key:
os.environ["OPENAI_API_KEY"] =args.openai_api_keyifargs.openai_api_base:
os.environ["OPENAI_API_BASE"] =args.openai_api_baseifargs.openai_api_version:
os.environ["OPENAI_API_VERSION"] =args.openai_api_versionifargs.openai_api_type:
os.environ["OPENAI_API_TYPE"] =args.openai_api_typeifargs.openai_organization_id:
os.environ["OPENAI_ORGANIZATION"] =args.openai_organization_idregister_models(git_root, args.model_settings_file, io, verbose=args.verbose)
register_litellm_models(git_root, args.model_metadata_file, io, verbose=args.verbose)
ifnotargs.model:
args.model="gpt-4o"ifos.environ.get("ANTHROPIC_API_KEY"):
args.model="claude-3-5-sonnet-20240620"main_model=models.Model(args.model, weak_model=args.weak_model)
lint_cmds=parse_lint_cmds(args.lint_cmd, io)
iflint_cmdsisNone:
return1ifargs.show_model_warnings:
models.sanity_check_models(io, main_model)
repo=Noneifargs.git:
try:
repo=GitRepo(
io,
fnames,
git_dname,
args.aiderignore,
models=main_model.commit_message_models(),
attribute_author=args.attribute_author,
attribute_committer=args.attribute_committer,
attribute_commit_message_author=args.attribute_commit_message_author,
attribute_commit_message_committer=args.attribute_commit_message_committer,
commit_prompt=args.commit_prompt,
subtree_only=args.subtree_only,
)
exceptFileNotFoundError:
passcommands=Commands(io, None, verify_ssl=args.verify_ssl)
summarizer=ChatSummary(
[main_model.weak_model, main_model],
args.max_chat_history_tokensormain_model.max_chat_history_tokens,
)
try:
coder=Coder.create(
main_model=main_model,
edit_format=args.edit_format,
io=io,
repo=repo,
fnames=fnames,
read_only_fnames=read_only_fnames,
show_diffs=args.show_diffs,
auto_commits=args.auto_commits,
dirty_commits=args.dirty_commits,
dry_run=args.dry_run,
map_tokens=args.map_tokens,
verbose=args.verbose,
assistant_output_color=args.assistant_output_color,
code_theme=args.code_theme,
stream=args.stream,
use_git=args.git,
restore_chat_history=args.restore_chat_history,
auto_lint=args.auto_lint,
auto_test=args.auto_test,
lint_cmds=lint_cmds,
test_cmd=args.test_cmd,
commands=commands,
summarizer=summarizer,
)
exceptValueErroraserr:
io.tool_error(str(err))
return1ifreturn_coder:
returncodercoder.show_announcements()
ifargs.show_prompts:
coder.cur_messages+= [
dict(role="user", content="Hello!"),
]
messages=coder.format_messages()
utils.show_messages(messages)
returnifargs.lint:
coder.commands.cmd_lint(fnames=fnames)
ifargs.test:
ifnotargs.test_cmd:
io.tool_error("No --test-cmd provided.")
return1test_errors=coder.commands.cmd_test(args.test_cmd)
iftest_errors:
coder.run(test_errors)
ifargs.commit:
ifargs.dry_run:
io.tool_output("Dry run enabled, skipping commit.")
else:
coder.commands.cmd_commit()
ifargs.lintorargs.testorargs.commit:
returnifargs.show_repo_map:
repo_map=coder.get_repo_map()
ifrepo_map:
io.tool_output(repo_map)
returnifargs.apply:
content=io.read_text(args.apply)
ifcontentisNone:
returncoder.partial_response_content=contentcoder.apply_updates()
returnif"VSCODE_GIT_IPC_HANDLE"inos.environ:
args.pretty=Falseio.tool_output("VSCode terminal detected, pretty output has been disabled.")
io.tool_output('Use /help <question> for help, run "aider --help" to see cmd line args')
ifgit_rootandPath.cwd().resolve() !=Path(git_root).resolve():
io.tool_error(
"Note: in-chat filenames are always relative to the git working dir, not the current"" working dir."
)
io.tool_error(f"Cur working dir: {Path.cwd()}")
io.tool_error(f"Git working dir: {git_root}")
ifargs.message:
io.add_to_input_history(args.message)
io.tool_output()
coder.run(with_message=args.message)
returnifargs.message_file:
try:
message_from_file=io.read_text(args.message_file)
io.tool_output()
coder.run(with_message=message_from_file)
exceptFileNotFoundError:
io.tool_error(f"Message file not found: {args.message_file}")
return1exceptIOErrorase:
io.tool_error(f"Error reading message file: {e}")
return1returnifargs.exit:
returnthread=threading.Thread(target=load_slow_imports)
thread.daemon=Truethread.start()
whileTrue:
try:
coder.run()
returnexceptSwitchCoderasswitch:
kwargs=dict(io=io, from_coder=coder)
kwargs.update(switch.kwargs)
if"show_announcements"inkwargs:
delkwargs["show_announcements"]
coder=Coder.create(**kwargs)
ifswitch.kwargs.get("show_announcements") isnotFalse:
coder.show_announcements()
defload_slow_imports():
# These imports are deferred in various ways to# improve startup time.# This func is called in a thread to load them in the background# while we wait for the user to type their first message.try:
importhttpx# noqa: F401importlitellm# noqa: F401importnetworkx# noqa: F401importnumpy# noqa: F401exceptException:
passif__name__=="__main__":
status=main()
sys.exit(status)
paul-gauthier/aider/blob/main/aider/mdstream.py:
#!/usr/bin/env pythonimportioimporttimefromrich.consoleimportConsolefromrich.liveimportLivefromrich.markdownimportMarkdownfromrich.textimportTextfromaider.dumpimportdump# noqa: F401_text= """
# Header
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
## Sub header
- List 1
- List 2
- List me
- List you
```python
import sys
def greeting():
print("Hello world!")
Sub header too
The end.
""" # noqa: E501
class MarkdownStream:
live = None
when = 0
min_delay = 0.050
live_window = 6
def __init__(self, mdargs=None):
self.printed = []
if mdargs:
self.mdargs = mdargs
else:
self.mdargs = dict()
self.live = Live(Text(""), refresh_per_second=1.0 / self.min_delay)
self.live.start()
def __del__(self):
if self.live:
try:
self.live.stop()
except Exception:
pass
def update(self, text, final=False):
now = time.time()
if not final and now - self.when < self.min_delay:
return
self.when = now
string_io = io.StringIO()
console = Console(file=string_io, force_terminal=True)
markdown = Markdown(text, **self.mdargs)
console.print(markdown)
output = string_io.getvalue()
lines = output.splitlines(keepends=True)
num_lines = len(lines)
if not final:
num_lines -= self.live_window
if final or num_lines > 0:
num_printed = len(self.printed)
show = num_lines - num_printed
if show <= 0:
return
show = lines[num_printed:num_lines]
show = "".join(show)
show = Text.from_ansi(show)
self.live.console.print(show)
self.printed = lines[:num_lines]
if final:
self.live.update(Text(""))
self.live.stop()
self.live = None
else:
rest = lines[num_lines:]
rest = "".join(rest)
# rest = '...\n' + rest
rest = Text.from_ansi(rest)
self.live.update(rest)
if name == "main":
_text = 5 * _text
pm = MarkdownStream()
for i in range(6, len(_text)):
pm.update(_text[:i])
time.sleep(0.01)
pm.update(_text, final=True)
paul-gauthier/aider/blob/main/aider/models.py:
```py
import difflib
import importlib
import json
import math
import os
import platform
import sys
from dataclasses import dataclass, fields
from pathlib import Path
from typing import Optional
import yaml
from PIL import Image
from aider import urls
from aider.dump import dump # noqa: F401
from aider.llm import AIDER_APP_NAME, AIDER_SITE_URL, litellm
DEFAULT_MODEL_NAME = "gpt-4o"
OPENAI_MODELS = """
gpt-4
gpt-4o
gpt-4o-2024-05-13
gpt-4-turbo-preview
gpt-4-0314
gpt-4-0613
gpt-4-32k
gpt-4-32k-0314
gpt-4-32k-0613
gpt-4-turbo
gpt-4-turbo-2024-04-09
gpt-4-1106-preview
gpt-4-0125-preview
gpt-4-vision-preview
gpt-4-1106-vision-preview
gpt-4o-mini
gpt-4o-mini-2024-07-18
gpt-3.5-turbo
gpt-3.5-turbo-0301
gpt-3.5-turbo-0613
gpt-3.5-turbo-1106
gpt-3.5-turbo-0125
gpt-3.5-turbo-16k
gpt-3.5-turbo-16k-0613
"""
OPENAI_MODELS = [ln.strip() for ln in OPENAI_MODELS.splitlines() if ln.strip()]
ANTHROPIC_MODELS = """
claude-2
claude-2.1
claude-3-haiku-20240307
claude-3-opus-20240229
claude-3-sonnet-20240229
claude-3-5-sonnet-20240620
"""
ANTHROPIC_MODELS = [ln.strip() for ln in ANTHROPIC_MODELS.splitlines() if ln.strip()]
@dataclass
class ModelSettings:
# Model class needs to have each of these as well
name: str
edit_format: str = "whole"
weak_model_name: Optional[str] = None
use_repo_map: bool = False
send_undo_reply: bool = False
accepts_images: bool = False
lazy: bool = False
reminder_as_sys_msg: bool = False
examples_as_sys_msg: bool = False
extra_headers: Optional[dict] = None
max_tokens: Optional[int] = None
# https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo
# https://platform.openai.com/docs/models/gpt-3-5-turbo
# https://openai.com/pricing
MODEL_SETTINGS = [
# gpt-3.5
ModelSettings(
"gpt-3.5-turbo",
"whole",
weak_model_name="gpt-4o-mini",
reminder_as_sys_msg=True,
),
ModelSettings(
"gpt-3.5-turbo-0125",
"whole",
weak_model_name="gpt-4o-mini",
reminder_as_sys_msg=True,
),
ModelSettings(
"gpt-3.5-turbo-1106",
"whole",
weak_model_name="gpt-4o-mini",
reminder_as_sys_msg=True,
),
ModelSettings(
"gpt-3.5-turbo-0613",
"whole",
weak_model_name="gpt-4o-mini",
reminder_as_sys_msg=True,
),
ModelSettings(
"gpt-3.5-turbo-16k-0613",
"whole",
weak_model_name="gpt-4o-mini",
reminder_as_sys_msg=True,
),
# gpt-4
ModelSettings(
"gpt-4-turbo-2024-04-09",
"udiff",
weak_model_name="gpt-4o-mini",
use_repo_map=True,
send_undo_reply=True,
accepts_images=True,
lazy=True,
reminder_as_sys_msg=True,
),
ModelSettings(
"gpt-4-turbo",
"udiff",
weak_model_name="gpt-4o-mini",
use_repo_map=True,
send_undo_reply=True,
accepts_images=True,
lazy=True,
reminder_as_sys_msg=True,
),
ModelSettings(
"openai/gpt-4o",
"diff",
weak_model_name="gpt-4o-mini",
use_repo_map=True,
send_undo_reply=True,
accepts_images=True,
lazy=True,
reminder_as_sys_msg=True,
),
ModelSettings(
"openai/gpt-4o-2024-08-06",
"diff",
weak_model_name="gpt-4o-mini",
use_repo_map=True,
send_undo_reply=True,
accepts_images=True,
lazy=True,
reminder_as_sys_msg=True,
),
ModelSettings(
"gpt-4o-2024-08-06",
"diff",
weak_model_name="gpt-4o-mini",
use_repo_map=True,
send_undo_reply=True,
accepts_images=True,
lazy=True,
reminder_as_sys_msg=True,
),
ModelSettings(
"gpt-4o",
"diff",
weak_model_name="gpt-4o-mini",
use_repo_map=True,
send_undo_reply=True,
accepts_images=True,
lazy=True,
reminder_as_sys_msg=True,
),
ModelSettings(
"gpt-4o-mini",
"whole",
weak_model_name="gpt-4o-mini",
accepts_images=True,
lazy=True,
reminder_as_sys_msg=True,
),
ModelSettings(
"openai/gpt-4o-mini",
"whole",
weak_model_name="openai/gpt-4o-mini",
accepts_images=True,
lazy=True,
reminder_as_sys_msg=True,
),
ModelSettings(
"gpt-4-0125-preview",
"udiff",
weak_model_name="gpt-4o-mini",
use_repo_map=True,
send_undo_reply=True,
lazy=True,
reminder_as_sys_msg=True,
examples_as_sys_msg=True,
),
ModelSettings(
"gpt-4-1106-preview",
"udiff",
weak_model_name="gpt-4o-mini",
use_repo_map=True,
send_undo_reply=True,
lazy=True,
reminder_as_sys_msg=True,
),
ModelSettings(
"gpt-4-vision-preview",
"diff",
weak_model_name="gpt-4o-mini",
use_repo_map=True,
send_undo_reply=True,
accepts_images=True,
reminder_as_sys_msg=True,
),
ModelSettings(
"gpt-4-0314",
"diff",
weak_model_name="gpt-4o-mini",
use_repo_map=True,
send_undo_reply=True,
reminder_as_sys_msg=True,
examples_as_sys_msg=True,
),
ModelSettings(
"gpt-4-0613",
"diff",
weak_model_name="gpt-4o-mini",
use_repo_map=True,
send_undo_reply=True,
reminder_as_sys_msg=True,
),
ModelSettings(
"gpt-4-32k-0613",
"diff",
weak_model_name="gpt-4o-mini",
use_repo_map=True,
send_undo_reply=True,
reminder_as_sys_msg=True,
),
# Claude
ModelSettings(
"claude-3-opus-20240229",
"diff",
weak_model_name="claude-3-haiku-20240307",
use_repo_map=True,
send_undo_reply=True,
),
ModelSettings(
"openrouter/anthropic/claude-3-opus",
"diff",
weak_model_name="openrouter/anthropic/claude-3-haiku",
use_repo_map=True,
send_undo_reply=True,
),
ModelSettings(
"claude-3-sonnet-20240229",
"whole",
weak_model_name="claude-3-haiku-20240307",
),
ModelSettings(
"claude-3-5-sonnet-20240620",
"diff",
weak_model_name="claude-3-haiku-20240307",
use_repo_map=True,
examples_as_sys_msg=True,
accepts_images=True,
max_tokens=8192,
extra_headers={"anthropic-beta": "max-tokens-3-5-sonnet-2024-07-15"},
),
ModelSettings(
"anthropic/claude-3-5-sonnet-20240620",
"diff",
weak_model_name="claude-3-haiku-20240307",
use_repo_map=True,
examples_as_sys_msg=True,
max_tokens=8192,
extra_headers={
"anthropic-beta": "max-tokens-3-5-sonnet-2024-07-15",
"HTTP-Referer": AIDER_SITE_URL,
"X-Title": AIDER_APP_NAME,
},
),
ModelSettings(
"openrouter/anthropic/claude-3.5-sonnet",
"diff",
weak_model_name="openrouter/anthropic/claude-3-haiku-20240307",
use_repo_map=True,
examples_as_sys_msg=True,
accepts_images=True,
max_tokens=8192,
extra_headers={
"anthropic-beta": "max-tokens-3-5-sonnet-2024-07-15",
"HTTP-Referer": "https://aider.chat",
"X-Title": "Aider",
},
),
# Vertex AI Claude models
# Does not yet support 8k token
ModelSettings(
"vertex_ai/claude-3-5-sonnet@20240620",
"diff",
weak_model_name="vertex_ai/claude-3-haiku@20240307",
use_repo_map=True,
examples_as_sys_msg=True,
accepts_images=True,
),
ModelSettings(
"vertex_ai/claude-3-opus@20240229",
"diff",
weak_model_name="vertex_ai/claude-3-haiku@20240307",
use_repo_map=True,
send_undo_reply=True,
),
ModelSettings(
"vertex_ai/claude-3-sonnet@20240229",
"whole",
weak_model_name="vertex_ai/claude-3-haiku@20240307",
),
# Cohere
ModelSettings(
"command-r-plus",
"whole",
weak_model_name="command-r-plus",
use_repo_map=True,
send_undo_reply=True,
),
# Groq llama3
ModelSettings(
"groq/llama3-70b-8192",
"diff",
weak_model_name="groq/llama3-8b-8192",
use_repo_map=False,
send_undo_reply=False,
examples_as_sys_msg=True,
),
# Openrouter llama3
ModelSettings(
"openrouter/meta-llama/llama-3-70b-instruct",
"diff",
weak_model_name="openrouter/meta-llama/llama-3-70b-instruct",
use_repo_map=False,
send_undo_reply=False,
examples_as_sys_msg=True,
),
# Gemini
ModelSettings(
"gemini/gemini-1.5-pro",
"diff-fenced",
use_repo_map=True,
send_undo_reply=True,
),
ModelSettings(
"gemini/gemini-1.5-pro-latest",
"diff-fenced",
use_repo_map=True,
send_undo_reply=True,
),
ModelSettings(
"deepseek/deepseek-chat",
"diff",
use_repo_map=True,
send_undo_reply=True,
examples_as_sys_msg=True,
reminder_as_sys_msg=True,
),
ModelSettings(
"deepseek/deepseek-coder",
"diff",
use_repo_map=True,
send_undo_reply=True,
examples_as_sys_msg=True,
reminder_as_sys_msg=True,
),
ModelSettings(
"openrouter/deepseek/deepseek-coder",
"diff",
use_repo_map=True,
send_undo_reply=True,
examples_as_sys_msg=True,
reminder_as_sys_msg=True,
),
ModelSettings(
"openrouter/openai/gpt-4o",
"diff",
weak_model_name="openrouter/openai/gpt-4o-mini",
use_repo_map=True,
send_undo_reply=True,
accepts_images=True,
lazy=True,
reminder_as_sys_msg=True,
),
]
class Model:
def __init__(self, model, weak_model=None):
# Set defaults from ModelSettings
default_settings = ModelSettings(name="")
for field in fields(ModelSettings):
setattr(self, field.name, getattr(default_settings, field.name))
self.name = model
self.max_chat_history_tokens = 1024
self.weak_model = None
self.info = self.get_model_info(model)
# Are all needed keys/params available?
res = self.validate_environment()
self.missing_keys = res.get("missing_keys")
self.keys_in_environment = res.get("keys_in_environment")
max_input_tokens = self.info.get("max_input_tokens") or 0
if max_input_tokens < 32 * 1024:
self.max_chat_history_tokens = 1024
else:
self.max_chat_history_tokens = 2 * 1024
self.configure_model_settings(model)
if weak_model is False:
self.weak_model_name = None
else:
self.get_weak_model(weak_model)
def get_model_info(self, model):
# Try and do this quickly, without triggering the litellm import
spec = importlib.util.find_spec("litellm")
if spec:
origin = Path(spec.origin)
fname = origin.parent / "model_prices_and_context_window_backup.json"
if fname.exists():
data = json.loads(fname.read_text())
info = data.get(model)
if info:
return info
# Do it the slow way...
try:
return litellm.get_model_info(model)
except Exception:
return dict()
def configure_model_settings(self, model):
for ms in MODEL_SETTINGS:
# direct match, or match "provider/<model>"
if model == ms.name:
for field in fields(ModelSettings):
val = getattr(ms, field.name)
setattr(self, field.name, val)
return # <--
model = model.lower()
if ("llama3" in model or "llama-3" in model) and "70b" in model:
self.edit_format = "diff"
self.use_repo_map = True
self.send_undo_reply = True
self.examples_as_sys_msg = True
return # <--
if "gpt-4-turbo" in model or ("gpt-4-" in model and "-preview" in model):
self.edit_format = "udiff"
self.use_repo_map = True
self.send_undo_reply = True
return # <--
if "gpt-4" in model or "claude-3-opus" in model:
self.edit_format = "diff"
self.use_repo_map = True
self.send_undo_reply = True
return # <--
if "gpt-3.5" in model or "gpt-4" in model:
self.reminder_as_sys_msg = True
if "3.5-sonnet" in model or "3-5-sonnet" in model:
self.edit_format = "diff"
self.use_repo_map = True
self.examples_as_sys_msg = True
# use the defaults
if self.edit_format == "diff":
self.use_repo_map = True
def __str__(self):
return self.name
def get_weak_model(self, provided_weak_model_name):
# If weak_model_name is provided, override the model settings
if provided_weak_model_name:
self.weak_model_name = provided_weak_model_name
if not self.weak_model_name:
self.weak_model = self
return
if self.weak_model_name == self.name:
self.weak_model = self
return
self.weak_model = Model(
self.weak_model_name,
weak_model=False,
)
return self.weak_model
def commit_message_models(self):
return [self.weak_model, self]
def tokenizer(self, text):
return litellm.encode(model=self.name, text=text)
def token_count(self, messages):
if type(messages) is list:
return litellm.token_counter(model=self.name, messages=messages)
if not self.tokenizer:
return
if type(messages) is str:
msgs = messages
else:
msgs = json.dumps(messages)
return len(self.tokenizer(msgs))
def token_count_for_image(self, fname):
"""
Calculate the token cost for an image assuming high detail.
The token cost is determined by the size of the image.
:param fname: The filename of the image.
:return: The token cost for the image.
"""
width, height = self.get_image_size(fname)
# If the image is larger than 2048 in any dimension, scale it down to fit within 2048x2048
max_dimension = max(width, height)
if max_dimension > 2048:
scale_factor = 2048 / max_dimension
width = int(width * scale_factor)
height = int(height * scale_factor)
# Scale the image such that the shortest side is 768 pixels long
min_dimension = min(width, height)
scale_factor = 768 / min_dimension
width = int(width * scale_factor)
height = int(height * scale_factor)
# Calculate the number of 512x512 tiles needed to cover the image
tiles_width = math.ceil(width / 512)
tiles_height = math.ceil(height / 512)
num_tiles = tiles_width * tiles_height
# Each tile costs 170 tokens, and there's an additional fixed cost of 85 tokens
token_cost = num_tiles * 170 + 85
return token_cost
def get_image_size(self, fname):
"""
Retrieve the size of an image.
:param fname: The filename of the image.
:return: A tuple (width, height) representing the image size in pixels.
"""
with Image.open(fname) as img:
return img.size
def fast_validate_environment(self):
"""Fast path for common models. Avoids forcing litellm import."""
model = self.name
if model in OPENAI_MODELS or model.startswith("openai/"):
var = "OPENAI_API_KEY"
elif model in ANTHROPIC_MODELS or model.startswith("anthropic/"):
var = "ANTHROPIC_API_KEY"
else:
return
if os.environ.get(var):
return dict(keys_in_environment=[var], missing_keys=[])
def validate_environment(self):
res = self.fast_validate_environment()
if res:
return res
# https://github.com/BerriAI/litellm/issues/3190
model = self.name
res = litellm.validate_environment(model)
if res["keys_in_environment"]:
return res
if res["missing_keys"]:
return res
provider = self.info.get("litellm_provider", "").lower()
if provider == "cohere_chat":
return validate_variables(["COHERE_API_KEY"])
if provider == "gemini":
return validate_variables(["GEMINI_API_KEY"])
if provider == "groq":
return validate_variables(["GROQ_API_KEY"])
return res
def register_models(model_settings_fnames):
files_loaded = []
for model_settings_fname in model_settings_fnames:
if not os.path.exists(model_settings_fname):
continue
try:
with open(model_settings_fname, "r") as model_settings_file:
model_settings_list = yaml.safe_load(model_settings_file)
for model_settings_dict in model_settings_list:
model_settings = ModelSettings(**model_settings_dict)
existing_model_settings = next(
(ms for ms in MODEL_SETTINGS if ms.name == model_settings.name), None
)
if existing_model_settings:
MODEL_SETTINGS.remove(existing_model_settings)
MODEL_SETTINGS.append(model_settings)
except Exception as e:
raise Exception(f"Error loading model settings from {model_settings_fname}: {e}")
files_loaded.append(model_settings_fname)
return files_loaded
def register_litellm_models(model_fnames):
files_loaded = []
for model_fname in model_fnames:
if not os.path.exists(model_fname):
continue
try:
with open(model_fname, "r") as model_def_file:
model_def = json.load(model_def_file)
litellm.register_model(model_def)
except Exception as e:
raise Exception(f"Error loading model definition from {model_fname}: {e}")
files_loaded.append(model_fname)
return files_loaded
def validate_variables(vars):
missing = []
for var in vars:
if var not in os.environ:
missing.append(var)
if missing:
return dict(keys_in_environment=False, missing_keys=missing)
return dict(keys_in_environment=True, missing_keys=missing)
def sanity_check_models(io, main_model):
sanity_check_model(io, main_model)
if main_model.weak_model and main_model.weak_model is not main_model:
sanity_check_model(io, main_model.weak_model)
def sanity_check_model(io, model):
show = False
if model.missing_keys:
show = True
io.tool_error(f"Model {model}: Missing these environment variables:")
for key in model.missing_keys:
io.tool_error(f"- {key}")
if platform.system() == "Windows" or True:
io.tool_output(
"If you just set these environment variables using `setx` you may need to restart"
" your terminal or command prompt for the changes to take effect."
)
elif not model.keys_in_environment:
show = True
io.tool_output(f"Model {model}: Unknown which environment variables are required.")
if not model.info:
show = True
io.tool_output(
f"Model {model}: Unknown context window size and costs, using sane defaults."
)
possible_matches = fuzzy_match_models(model.name)
if possible_matches:
io.tool_output("Did you mean one of these?")
for match in possible_matches:
io.tool_output(f"- {match}")
if show:
io.tool_output(f"For more info, see: {urls.model_warnings}\n")
def fuzzy_match_models(name):
name = name.lower()
chat_models = set()
for model, attrs in litellm.model_cost.items():
model = model.lower()
if attrs.get("mode") != "chat":
continue
provider = (attrs["litellm_provider"] + "/").lower()
if model.startswith(provider):
fq_model = model
else:
fq_model = provider + model
chat_models.add(fq_model)
chat_models.add(model)
chat_models = sorted(chat_models)
# exactly matching model
# matching_models = [
# (fq,m) for fq,m in chat_models
# if name == fq or name == m
# ]
# if matching_models:
# return matching_models
# Check for model names containing the name
matching_models = [m for m in chat_models if name in m]
if matching_models:
return sorted(set(matching_models))
# Check for slight misspellings
models = set(chat_models)
matching_models = difflib.get_close_matches(name, models, n=3, cutoff=0.8)
return sorted(set(matching_models))
def print_matching_models(io, search):
matches = fuzzy_match_models(search)
if matches:
io.tool_output(f'Models which match "{search}":')
for model in matches:
io.tool_output(f"- {model}")
else:
io.tool_output(f'No models match "{search}".')
def main():
if len(sys.argv) != 2:
print("Usage: python models.py <model_name>")
sys.exit(1)
model_name = sys.argv[1]
matching_models = fuzzy_match_models(model_name)
if matching_models:
print(f"Matching models for '{model_name}':")
for model in matching_models:
print(model)
else:
print(f"No matching models found for '{model_name}'.")
if __name__ == "__main__":
main()
paul-gauthier/aider/blob/main/aider/prompts.py:
# flake8: noqa: E501# COMMIT# Conventional Commits text adapted from:# https://www.conventionalcommits.org/en/v1.0.0/#summarycommit_system="""You are an expert software engineer.Review the provided context and diffs which are about to be committed to a git repo.Review the diffs carefully.Generate a commit message for those changes.The commit message MUST use the imperative tense.The commit message should be structured as follows: <type>: <description>Use these for <type>: fix, feat, build, chore, ci, docs, style, refactor, perf, testReply with JUST the commit message, without quotes, comments, questions, etc!"""# COMMANDSundo_command_reply= (
"I did `git reset --hard HEAD~1` to discard the last edits. Please wait for further"" instructions before attempting that change again. Feel free to ask relevant questions about"" why the changes were reverted."
)
added_files= (
"I added these files to the chat: {fnames}\nLet me know if there are others we should add."
)
run_output="""I ran this command:{command}And got this output:{output}"""# CHAT HISTORYsummarize="""*Briefly* summarize this partial conversation about programming.Include less detail about older parts and more detail about the most recent messages.Start a new paragraph every time the topic changes!This is only part of a longer conversation so *DO NOT* conclude the summary with language like "Finally, ...". Because the conversation continues after the summary.The summary *MUST* include the function names, libraries, packages that are being discussed.The summary *MUST* include the filenames that are being referenced by the assistant inside the ```...``` fenced code blocks!The summaries *MUST NOT* include ```...``` fenced code blocks!Phrase the summary with the USER in first person, telling the ASSISTANT about the conversation.Write *as* the user.The user should refer to the assistant as *you*.Start the summary with "I asked you..."."""summary_prefix="I spoke to you previously about a number of things.\n"
# Credits
Aider uses modified versions of the tags.scm files from these open source
tree-sitter language implementations:
*[https://github.com/tree-sitter/tree-sitter-c](https://github.com/tree-sitter/tree-sitter-c) — licensed under the MIT License.
*[https://github.com/tree-sitter/tree-sitter-c-sharp](https://github.com/tree-sitter/tree-sitter-c-sharp) — licensed under the MIT License.
*[https://github.com/tree-sitter/tree-sitter-cpp](https://github.com/tree-sitter/tree-sitter-cpp) — licensed under the MIT License.
*[https://github.com/Wilfred/tree-sitter-elisp](https://github.com/Wilfred/tree-sitter-elisp) — licensed under the MIT License.
*[https://github.com/elixir-lang/tree-sitter-elixir](https://github.com/elixir-lang/tree-sitter-elixir) — licensed under the Apache License, Version 2.0.
*[https://github.com/elm-tooling/tree-sitter-elm](https://github.com/elm-tooling/tree-sitter-elm) — licensed under the MIT License.
*[https://github.com/tree-sitter/tree-sitter-go](https://github.com/tree-sitter/tree-sitter-go) — licensed under the MIT License.
*[https://github.com/tree-sitter/tree-sitter-java](https://github.com/tree-sitter/tree-sitter-java) — licensed under the MIT License.
*[https://github.com/tree-sitter/tree-sitter-javascript](https://github.com/tree-sitter/tree-sitter-javascript) — licensed under the MIT License.
*[https://github.com/tree-sitter/tree-sitter-ocaml](https://github.com/tree-sitter/tree-sitter-ocaml) — licensed under the MIT License.
*[https://github.com/tree-sitter/tree-sitter-php](https://github.com/tree-sitter/tree-sitter-php) — licensed under the MIT License.
*[https://github.com/tree-sitter/tree-sitter-python](https://github.com/tree-sitter/tree-sitter-python) — licensed under the MIT License.
*[https://github.com/tree-sitter/tree-sitter-ql](https://github.com/tree-sitter/tree-sitter-ql) — licensed under the MIT License.
*[https://github.com/r-lib/tree-sitter-r](https://github.com/r-lib/tree-sitter-r) — licensed under the MIT License.
*[https://github.com/tree-sitter/tree-sitter-ruby](https://github.com/tree-sitter/tree-sitter-ruby) — licensed under the MIT License.
*[https://github.com/tree-sitter/tree-sitter-rust](https://github.com/tree-sitter/tree-sitter-rust) — licensed under the MIT License.
*[https://github.com/tree-sitter/tree-sitter-typescript](https://github.com/tree-sitter/tree-sitter-typescript) — licensed under the MIT License.
---title: Release historyparent: More infonav_order: 999highlight_image: /assets/blame.jpgdescription: Release notes and stats on aider writing its own code.---
{% include blame.md %}
<!--[[[cog# This page is a copy of HISTORY.md, adding the front matter above.text = open("HISTORY.md").read()cog.out(text)]]]--># Release history### Aider v0.50.0- Infinite output for DeepSeek Coder, Mistral models in addition to Anthropic's models.
- New `--deepseek` switch to use DeepSeek Coder.
- DeepSeek Coder uses 8k token output.
- New `--chat-mode <mode>` switch to launch in ask/help/code modes.
- New `/code <message>` command request a code edit while in `ask` mode.
- Web scraper is more robust if page never idles.
- Improved token and cost reporting for infinite output.
- Improvements and bug fixes for `/read` only files.
- Switched from `setup.py` to `pyproject.toml`, by @branchvincent.
- Bug fix to persist files added during `/ask`.
- Bug fix for chat history size in `/tokens`.
- Aider wrote 66% of the code in this release.
### Aider v0.49.1- Bugfix to `/help`.
### Aider v0.49.0- Add read-only files to the chat context with `/read` and `--read`, including from outside the git repo.
-`/diff` now shows diffs of all changes resulting from your request, including lint and test fixes.
- New `/clipboard` command to paste images or text from the clipboard, replaces `/add-clipboard-image`.
- Now shows the markdown scraped when you add a url with `/web`.
- When [scripting aider](https://aider.chat/docs/scripting.html) messages can now contain in-chat `/` commands.
- Aider in docker image now suggests the correct command to update to latest version.
- Improved retries on API errors (was easy to test during Sonnet outage).
- Added `--mini` for `gpt-4o-mini`.
- Bugfix to keep session cost accurate when using `/ask` and `/help`.
- Performance improvements for repo map calculation.
-`/tokens` now shows the active model.
- Enhanced commit message attribution options:
- New `--attribute-commit-message-author` to prefix commit messages with 'aider: ' if aider authored the changes, replaces `--attribute-commit-message`.
- New `--attribute-commit-message-committer` to prefix all commit messages with 'aider: '.
- Aider wrote 61% of the code in this release.
### Aider v0.48.1- Added `openai/gpt-4o-2024-08-06`.
- Worked around litellm bug that removes OpenRouter app headers when using `extra_headers`.
- Improved progress indication during repo map processing.
- Corrected instructions for upgrading the docker container to latest aider version.
- Removed obsolete 16k token limit on commit diffs, use per-model limits.
### Aider v0.48.0- Performance improvements for large/mono repos.
- Added `--subtree-only` to limit aider to current directory subtree.
- Should help with large/mono repo performance.
- New `/add-clipboard-image` to add images to the chat from your clipboard.
- Use `--map-tokens 1024` to use repo map with any model.
- Support for Sonnet's 8k output window.
-[Aider already supported infinite output from Sonnet.](https://aider.chat/2024/07/01/sonnet-not-lazy.html)- Workaround litellm bug for retrying API server errors.
- Upgraded dependencies, to pick up litellm bug fixes.
- Aider wrote 44% of the code in this release.
### Aider v0.47.1- Improvements to conventional commits prompting.
### Aider v0.47.0-[Commit message](https://aider.chat/docs/git.html#commit-messages) improvements:
- Added Conventional Commits guidelines to commit message prompt.
- Added `--commit-prompt` to customize the commit message prompt.
- Added strong model as a fallback for commit messages (and chat summaries).
-[Linting](https://aider.chat/docs/usage/lint-test.html) improvements:
- Ask before fixing lint errors.
- Improved performance of `--lint` on all dirty files in repo.
- Improved lint flow, now doing code edit auto-commit before linting.
- Bugfix to properly handle subprocess encodings (also for `/run`).
- Improved [docker support](https://aider.chat/docs/install/docker.html):
- Resolved permission issues when using `docker run --user xxx`.
- New `paulgauthier/aider-full` docker image, which includes all extras.
- Switching to code and ask mode no longer summarizes the chat history.
- Added graph of aider's contribution to each release.
- Generic auto-completions are provided for `/commands` without a completion override.
- Fixed broken OCaml tags file.
- Bugfix in `/run` add to chat approval logic.
- Aider wrote 58% of the code in this release.
### Aider v0.46.1- Downgraded stray numpy dependency back to 1.26.4.
### Aider v0.46.0- New `/ask <question>` command to ask about your code, without making any edits.
- New `/chat-mode <mode>` command to switch chat modes:
- ask: Ask questions about your code without making any changes.
- code: Ask for changes to your code (using the best edit format).
- help: Get help about using aider (usage, config, troubleshoot).
- Add `file: CONVENTIONS.md` to `.aider.conf.yml` to always load a specific file.
- Or `file: [file1, file2, file3]` to always load multiple files.
- Enhanced token usage and cost reporting. Now works when streaming too.
- Filename auto-complete for `/add` and `/drop` is now case-insensitive.
- Commit message improvements:
- Updated commit message prompt to use imperative tense.
- Fall back to main model if weak model is unable to generate a commit message.
- Stop aider from asking to add the same url to the chat multiple times.
- Updates and fixes to `--no-verify-ssl`:
- Fixed regression that broke it in v0.42.0.
- Disables SSL certificate verification when `/web` scrapes websites.
- Improved error handling and reporting in `/web` scraping functionality
- Fixed syntax error in Elm's tree-sitter scm file (by @cjoach).
- Handle UnicodeEncodeError when streaming text to the terminal.
- Updated dependencies to latest versions.
- Aider wrote 45% of the code in this release.
### Aider v0.45.1- Use 4o-mini as the weak model wherever 3.5-turbo was used.
### Aider v0.45.0- GPT-4o mini scores similar to the original GPT 3.5, using whole edit format.
- Aider is better at offering to add files to the chat on Windows.
- Bugfix corner cases for `/undo` with new files or new repos.
- Now shows last 4 characters of API keys in `--verbose` output.
- Bugfix to precedence of multiple `.env` files.
- Bugfix to gracefully handle HTTP errors when installing pandoc.
- Aider wrote 42% of the code in this release.
### Aider v0.44.0- Default pip install size reduced by 3-12x.
- Added 3 package extras, which aider will offer to install when needed:
-`aider-chat[help]`-`aider-chat[browser]`-`aider-chat[playwright]`- Improved regex for detecting URLs in user chat messages.
- Bugfix to globbing logic when absolute paths are included in `/add`.
- Simplified output of `--models`.
- The `--check-update` switch was renamed to `--just-check-updated`.
- The `--skip-check-update` switch was renamed to `--[no-]check-update`.
- Aider wrote 29% of the code in this release (157/547 lines).
### Aider v0.43.4- Added scipy back to main requirements.txt.
### Aider v0.43.3- Added build-essentials back to main Dockerfile.
### Aider v0.43.2- Moved HuggingFace embeddings deps into [hf-embed] extra.
- Added [dev] extra.
### Aider v0.43.1- Replace the torch requirement with the CPU only version, because the GPU versions are huge.
### Aider v0.43.0- Use `/help <question>` to [ask for help about using aider](https://aider.chat/docs/troubleshooting/support.html), customizing settings, troubleshooting, using LLMs, etc.
- Allow multiple use of `/undo`.
- All config/env/yml/json files now load from home, git root, cwd and named command line switch.
- New `$HOME/.aider/caches` dir for app-wide expendable caches.
- Default `--model-settings-file` is now `.aider.model.settings.yml`.
- Default `--model-metadata-file` is now `.aider.model.metadata.json`.
- Bugfix affecting launch with `--no-git`.
- Aider wrote 9% of the 424 lines edited in this release.
### Aider v0.42.0- Performance release:
- 5X faster launch!
- Faster auto-complete in large git repos (users report ~100X speedup)!
### Aider v0.41.0-[Allow Claude 3.5 Sonnet to stream back >4k tokens!](https://aider.chat/2024/07/01/sonnet-not-lazy.html)- It is the first model capable of writing such large coherent, useful code edits.
- Do large refactors or generate multiple files of new code in one go.
- Aider now uses `claude-3-5-sonnet-20240620` by default if `ANTHROPIC_API_KEY` is set in the environment.
-[Enabled image support](https://aider.chat/docs/usage/images-urls.html) for 3.5 Sonnet and for GPT-4o & 3.5 Sonnet via OpenRouter (by @yamitzky).
- Added `--attribute-commit-message` to prefix aider's commit messages with "aider:".
- Fixed regression in quality of one-line commit messages.
- Automatically retry on Anthropic `overloaded_error`.
- Bumped dependency versions.
### Aider v0.40.6- Fixed `/undo` so it works regardless of `--attribute` settings.
### Aider v0.40.5- Bump versions to pickup latest litellm to fix streaming issue with Gemini
-https://github.com/BerriAI/litellm/issues/4408### Aider v0.40.1- Improved context awareness of repomap.
- Restored proper `--help` functionality.
### Aider v0.40.0- Improved prompting to discourage Sonnet from wasting tokens emitting unchanging code (#705).
- Improved error info for token limit errors.
- Options to suppress adding "(aider)" to the [git author and committer names](https://aider.chat/docs/git.html#commit-attribution).
- Use `--model-settings-file` to customize per-model settings, like use of repo-map (by @caseymcc).
- Improved invocation of flake8 linter for python code.
### Aider v0.39.0- Use `--sonnet` for Claude 3.5 Sonnet, which is the top model on [aider's LLM code editing leaderboard](https://aider.chat/docs/leaderboards/#claude-35-sonnet-takes-the-top-spot).
- All `AIDER_xxx` environment variables can now be set in `.env` (by @jpshack-at-palomar).
- Use `--llm-history-file` to log raw messages sent to the LLM (by @daniel-vainsencher).
- Commit messages are no longer prefixed with "aider:". Instead the git author and committer names have "(aider)" added.
### Aider v0.38.0- Use `--vim` for [vim keybindings](https://aider.chat/docs/usage/commands.html#vi) in the chat.
-[Add LLM metadata](https://aider.chat/docs/llms/warnings.html#specifying-context-window-size-and-token-costs) via `.aider.models.json` file (by @caseymcc).
- More detailed [error messages on token limit errors](https://aider.chat/docs/troubleshooting/token-limits.html).
- Single line commit messages, without the recent chat messages.
- Ensure `--commit --dry-run` does nothing.
- Have playwright wait for idle network to better scrape js sites.
- Documentation updates, moved into website/ subdir.
- Moved tests/ into aider/tests/.
### Aider v0.37.0- Repo map is now optimized based on text of chat history as well as files added to chat.
- Improved prompts when no files have been added to chat to solicit LLM file suggestions.
- Aider will notice if you paste a URL into the chat, and offer to scrape it.
- Performance improvements the repo map, especially in large repos.
- Aider will not offer to add bare filenames like `make` or `run` which may just be words.
- Properly override `GIT_EDITOR` env for commits if it is already set.
- Detect supported audio sample rates for `/voice`.
- Other small bug fixes.
### Aider v0.36.0-[Aider can now lint your code and fix any errors](https://aider.chat/2024/05/22/linting.html).
- Aider automatically lints and fixes after every LLM edit.
- You can manually lint-and-fix files with `/lint` in the chat or `--lint` on the command line.
- Aider includes built in basic linters for all supported tree-sitter languages.
- You can also configure aider to use your preferred linter with `--lint-cmd`.
- Aider has additional support for running tests and fixing problems.
- Configure your testing command with `--test-cmd`.
- Run tests with `/test` or from the command line with `--test`.
- Aider will automatically attempt to fix any test failures.
### Aider v0.35.0- Aider now uses GPT-4o by default.
- GPT-4o tops the [aider LLM code editing leaderboard](https://aider.chat/docs/leaderboards/) at 72.9%, versus 68.4% for Opus.
- GPT-4o takes second on [aider's refactoring leaderboard](https://aider.chat/docs/leaderboards/#code-refactoring-leaderboard) with 62.9%, versus Opus at 72.3%.
- Added `--restore-chat-history` to restore prior chat history on launch, so you can continue the last conversation.
- Improved reflection feedback to LLMs using the diff edit format.
- Improved retries on `httpx` errors.
### Aider v0.34.0- Updated prompting to use more natural phrasing about files, the git repo, etc. Removed reliance on read-write/read-only terminology.
- Refactored prompting to unify some phrasing across edit formats.
- Enhanced the canned assistant responses used in prompts.
- Added explicit model settings for `openrouter/anthropic/claude-3-opus`, `gpt-3.5-turbo`- Added `--show-prompts` debug switch.
- Bugfix: catch and retry on all litellm exceptions.
### Aider v0.33.0- Added native support for [Deepseek models](https://aider.chat/docs/llms.html#deepseek) using `DEEPSEEK_API_KEY` and `deepseek/deepseek-chat`, etc rather than as a generic OpenAI compatible API.
### Aider v0.32.0-[Aider LLM code editing leaderboards](https://aider.chat/docs/leaderboards/) that rank popular models according to their ability to edit code.
- Leaderboards include GPT-3.5/4 Turbo, Opus, Sonnet, Gemini 1.5 Pro, Llama 3, Deepseek Coder & Command-R+.
- Gemini 1.5 Pro now defaults to a new diff-style edit format (diff-fenced), enabling it to work better with larger code bases.
- Support for Deepseek-V2, via more a flexible config of system messages in the diff edit format.
- Improved retry handling on errors from model APIs.
- Benchmark outputs results in YAML, compatible with leaderboard.
### Aider v0.31.0-[Aider is now also AI pair programming in your browser!](https://aider.chat/2024/05/02/browser.html) Use the `--browser` switch to launch an experimental browser based version of aider.
- Switch models during the chat with `/model <name>` and search the list of available models with `/models <query>`.
### Aider v0.30.1- Adding missing `google-generativeai` dependency
### Aider v0.30.0- Added [Gemini 1.5 Pro](https://aider.chat/docs/llms.html#free-models) as a recommended free model.
- Allow repo map for "whole" edit format.
- Added `--models <MODEL-NAME>` to search the available models.
- Added `--no-show-model-warnings` to silence model warnings.
### Aider v0.29.2- Improved [model warnings](https://aider.chat/docs/llms.html#model-warnings) for unknown or unfamiliar models
### Aider v0.29.1- Added better support for groq/llama3-70b-8192
### Aider v0.29.0- Added support for [directly connecting to Anthropic, Cohere, Gemini and many other LLM providers](https://aider.chat/docs/llms.html).
- Added `--weak-model <model-name>` which allows you to specify which model to use for commit messages and chat history summarization.
- New command line switches for working with popular models:
-`--4-turbo-vision`-`--opus`-`--sonnet`-`--anthropic-api-key`- Improved "whole" and "diff" backends to better support [Cohere's free to use Command-R+ model](https://aider.chat/docs/llms.html#cohere).
- Allow `/add` of images from anywhere in the filesystem.
- Fixed crash when operating in a repo in a detached HEAD state.
- Fix: Use the same default model in CLI and python scripting.
### Aider v0.28.0- Added support for new `gpt-4-turbo-2024-04-09` and `gpt-4-turbo` models.
- Benchmarked at 61.7% on Exercism benchmark, comparable to `gpt-4-0613` and worse than the `gpt-4-preview-XXXX` models. See [recent Exercism benchmark results](https://aider.chat/2024/03/08/claude-3.html).
- Benchmarked at 34.1% on the refactoring/laziness benchmark, significantly worse than the `gpt-4-preview-XXXX` models. See [recent refactor bencmark results](https://aider.chat/2024/01/25/benchmarks-0125.html).
- Aider continues to default to `gpt-4-1106-preview` as it performs best on both benchmarks, and significantly better on the refactoring/laziness benchmark.
### Aider v0.27.0- Improved repomap support for typescript, by @ryanfreckleton.
- Bugfix: Only /undo the files which were part of the last commit, don't stomp other dirty files
- Bugfix: Show clear error message when OpenAI API key is not set.
- Bugfix: Catch error for obscure languages without tags.scm file.
### Aider v0.26.1- Fixed bug affecting parsing of git config in some environments.
### Aider v0.26.0- Use GPT-4 Turbo by default.
- Added `-3` and `-4` switches to use GPT 3.5 or GPT-4 (non-Turbo).
- Bug fix to avoid reflecting local git errors back to GPT.
- Improved logic for opening git repo on launch.
### Aider v0.25.0- Issue a warning if user adds too much code to the chat.
-https://aider.chat/docs/faq.html#how-can-i-add-all-the-files-to-the-chat- Vocally refuse to add files to the chat that match `.aiderignore`- Prevents bug where subsequent git commit of those files will fail.
- Added `--openai-organization-id` argument.
- Show the user a FAQ link if edits fail to apply.
- Made past articles part of https://aider.chat/blog/### Aider v0.24.1- Fixed bug with cost computations when --no-steam in effect
### Aider v0.24.0- New `/web <url>` command which scrapes the url, turns it into fairly clean markdown and adds it to the chat.
- Updated all OpenAI model names, pricing info
- Default GPT 3.5 model is now `gpt-3.5-turbo-0125`.
- Bugfix to the `!` alias for `/run`.
### Aider v0.23.0- Added support for `--model gpt-4-0125-preview` and OpenAI's alias `--model gpt-4-turbo-preview`. The `--4turbo` switch remains an alias for `--model gpt-4-1106-preview` at this time.
- New `/test` command that runs a command and adds the output to the chat on non-zero exit status.
- Improved streaming of markdown to the terminal.
- Added `/quit` as alias for `/exit`.
- Added `--skip-check-update` to skip checking for the update on launch.
- Added `--openrouter` as a shortcut for `--openai-api-base https://openrouter.ai/api/v1`- Fixed bug preventing use of env vars `OPENAI_API_BASE, OPENAI_API_TYPE, OPENAI_API_VERSION, OPENAI_API_DEPLOYMENT_ID`.
### Aider v0.22.0- Improvements for unified diff editing format.
- Added ! as an alias for /run.
- Autocomplete for /add and /drop now properly quotes filenames with spaces.
- The /undo command asks GPT not to just retry reverted edit.
### Aider v0.21.1- Bugfix for unified diff editing format.
- Added --4turbo and --4 aliases for --4-turbo.
### Aider v0.21.0- Support for python 3.12.
- Improvements to unified diff editing format.
- New `--check-update` arg to check if updates are available and exit with status code.
### Aider v0.20.0- Add images to the chat to automatically use GPT-4 Vision, by @joshuavial- Bugfixes:
- Improved unicode encoding for `/run` command output, by @ctoth- Prevent false auto-commits on Windows, by @ctoth### Aider v0.19.1- Removed stray debug output.
### Aider v0.19.0-[Significantly reduced "lazy" coding from GPT-4 Turbo due to new unified diff edit format](https://aider.chat/docs/unified-diffs.html)- Score improves from 20% to 61% on new "laziness benchmark".
- Aider now uses unified diffs by default for `gpt-4-1106-preview`.
- New `--4-turbo` command line switch as a shortcut for `--model gpt-4-1106-preview`.
### Aider v0.18.1- Upgraded to new openai python client v1.3.7.
### Aider v0.18.0- Improved prompting for both GPT-4 and GPT-4 Turbo.
- Far fewer edit errors from GPT-4 Turbo (`gpt-4-1106-preview`).
- Significantly better benchmark results from the June GPT-4 (`gpt-4-0613`). Performance leaps from 47%/64% up to 51%/71%.
- Fixed bug where in-chat files were marked as both read-only and ready-write, sometimes confusing GPT.
- Fixed bug to properly handle repos with submodules.
### Aider v0.17.0- Support for OpenAI's new 11/06 models:
- gpt-4-1106-preview with 128k context window
- gpt-3.5-turbo-1106 with 16k context window
-[Benchmarks for OpenAI's new 11/06 models](https://aider.chat/docs/benchmarks-1106.html)- Streamlined [API for scripting aider, added docs](https://aider.chat/docs/faq.html#can-i-script-aider)- Ask for more concise SEARCH/REPLACE blocks. [Benchmarked](https://aider.chat/docs/benchmarks.html) at 63.9%, no regression.
- Improved repo-map support for elisp.
- Fixed crash bug when `/add` used on file matching `.gitignore`- Fixed misc bugs to catch and handle unicode decoding errors.
### Aider v0.16.3- Fixed repo-map support for C#.
### Aider v0.16.2- Fixed docker image.
### Aider v0.16.1- Updated tree-sitter dependencies to streamline the pip install process
### Aider v0.16.0-[Improved repository map using tree-sitter](https://aider.chat/docs/repomap.html)- Switched from "edit block" to "search/replace block", which reduced malformed edit blocks. [Benchmarked](https://aider.chat/docs/benchmarks.html) at 66.2%, no regression.
- Improved handling of malformed edit blocks targeting multiple edits to the same file. [Benchmarked](https://aider.chat/docs/benchmarks.html) at 65.4%, no regression.
- Bugfix to properly handle malformed `/add` wildcards.
### Aider v0.15.0- Added support for `.aiderignore` file, which instructs aider to ignore parts of the git repo.
- New `--commit` cmd line arg, which just commits all pending changes with a sensible commit message generated by gpt-3.5.
- Added universal ctags and multiple architectures to the [aider docker image](https://aider.chat/docs/install/docker.html)-`/run` and `/git` now accept full shell commands, like: `/run (cd subdir; ls)`- Restored missing `--encoding` cmd line switch.
### Aider v0.14.2- Easily [run aider from a docker image](https://aider.chat/docs/install/docker.html)- Fixed bug with chat history summarization.
- Fixed bug if `soundfile` package not available.
### Aider v0.14.1- /add and /drop handle absolute filenames and quoted filenames
- /add checks to be sure files are within the git repo (or root)
- If needed, warn users that in-chat file paths are all relative to the git repo
- Fixed /add bug in when aider launched in repo subdir
- Show models supported by api/key if requested model isn't available
### Aider v0.14.0-[Support for Claude2 and other LLMs via OpenRouter](https://aider.chat/docs/faq.html#accessing-other-llms-with-openrouter) by @joshuavial- Documentation for [running the aider benchmarking suite](https://github.com/paul-gauthier/aider/tree/main/benchmark)- Aider now requires Python >= 3.9
### Aider v0.13.0-[Only git commit dirty files that GPT tries to edit](https://aider.chat/docs/faq.html#how-did-v0130-change-git-usage)- Send chat history as prompt/context for Whisper voice transcription
- Added `--voice-language` switch to constrain `/voice` to transcribe to a specific language
- Late-bind importing `sounddevice`, as it was slowing down aider startup
- Improved --foo/--no-foo switch handling for command line and yml config settings
### Aider v0.12.0-[Voice-to-code](https://aider.chat/docs/usage/voice.html) support, which allows you to code with your voice.
- Fixed bug where /diff was causing crash.
- Improved prompting for gpt-4, refactor of editblock coder.
-[Benchmarked](https://aider.chat/docs/benchmarks.html) at 63.2% for gpt-4/diff, no regression.
### Aider v0.11.1- Added a progress bar when initially creating a repo map.
- Fixed bad commit message when adding new file to empty repo.
- Fixed corner case of pending chat history summarization when dirty committing.
- Fixed corner case of undefined `text` when using `--no-pretty`.
- Fixed /commit bug from repo refactor, added test coverage.
-[Benchmarked](https://aider.chat/docs/benchmarks.html) at 53.4% for gpt-3.5/whole (no regression).
### Aider v0.11.0- Automatically summarize chat history to avoid exhausting context window.
- More detail on dollar costs when running with `--no-stream`- Stronger GPT-3.5 prompt against skipping/eliding code in replies (51.9% [benchmark](https://aider.chat/docs/benchmarks.html), no regression)
- Defend against GPT-3.5 or non-OpenAI models suggesting filenames surrounded by asterisks.
- Refactored GitRepo code out of the Coder class.
### Aider v0.10.1- /add and /drop always use paths relative to the git root
- Encourage GPT to use language like "add files to the chat" to ask users for permission to edit them.
### Aider v0.10.0- Added `/git` command to run git from inside aider chats.
- Use Meta-ENTER (Esc+ENTER in some environments) to enter multiline chat messages.
- Create a `.gitignore` with `.aider*` to prevent users from accidentaly adding aider files to git.
- Check pypi for newer versions and notify user.
- Updated keyboard interrupt logic so that 2 ^C in 2 seconds always forces aider to exit.
- Provide GPT with detailed error if it makes a bad edit block, ask for a retry.
- Force `--no-pretty` if aider detects it is running inside a VSCode terminal.
-[Benchmarked](https://aider.chat/docs/benchmarks.html) at 64.7% for gpt-4/diff (no regression)
### Aider v0.9.0- Support for the OpenAI models in [Azure](https://aider.chat/docs/faq.html#azure)- Added `--show-repo-map`- Improved output when retrying connections to the OpenAI API
- Redacted api key from `--verbose` output
- Bugfix: recognize and add files in subdirectories mentioned by user or GPT
-[Benchmarked](https://aider.chat/docs/benchmarks.html) at 53.8% for gpt-3.5-turbo/whole (no regression)
### Aider v0.8.3- Added `--dark-mode` and `--light-mode` to select colors optimized for terminal background
- Install docs link to [NeoVim plugin](https://github.com/joshuavial/aider.nvim) by @joshuavial- Reorganized the `--help` output
- Bugfix/improvement to whole edit format, may improve coding editing for GPT-3.5
- Bugfix and tests around git filenames with unicode characters
- Bugfix so that aider throws an exception when OpenAI returns InvalidRequest
- Bugfix/improvement to /add and /drop to recurse selected directories
- Bugfix for live diff output when using "whole" edit format
### Aider v0.8.2- Disabled general availability of gpt-4 (it's rolling out, not 100% available yet)
### Aider v0.8.1- Ask to create a git repo if none found, to better track GPT's code changes
- Glob wildcards are now supported in `/add` and `/drop` commands
- Pass `--encoding` into ctags, require it to return `utf-8`- More robust handling of filepaths, to avoid 8.3 windows filenames
- Added [FAQ](https://aider.chat/docs/faq.html)- Marked GPT-4 as generally available
- Bugfix for live diffs of whole coder with missing filenames
- Bugfix for chats with multiple files
- Bugfix in editblock coder prompt
### Aider v0.8.0-[Benchmark comparing code editing in GPT-3.5 and GPT-4](https://aider.chat/docs/benchmarks.html)- Improved Windows support:
- Fixed bugs related to path separators in Windows
- Added a CI step to run all tests on Windows
- Improved handling of Unicode encoding/decoding
- Explicitly read/write text files with utf-8 encoding by default (mainly benefits Windows)
- Added `--encoding` switch to specify another encoding
- Gracefully handle decoding errors
- Added `--code-theme` switch to control the pygments styling of code blocks (by @kwmiebach)
- Better status messages explaining the reason when ctags is disabled
### Aider v0.7.2:- Fixed a bug to allow aider to edit files that contain triple backtick fences.
### Aider v0.7.1:- Fixed a bug in the display of streaming diffs in GPT-3.5 chats
### Aider v0.7.0:- Graceful handling of context window exhaustion, including helpful tips.
- Added `--message` to give GPT that one instruction and then exit after it replies and any edits are performed.
- Added `--no-stream` to disable streaming GPT responses.
- Non-streaming responses include token usage info.
- Enables display of cost info based on OpenAI advertised pricing.
- Coding competence benchmarking tool against suite of programming tasks based on Execism's python repo.
-https://github.com/exercism/python- Major refactor in preparation for supporting new function calls api.
- Initial implementation of a function based code editing backend for 3.5.
- Initial experiments show that using functions makes 3.5 less competent at coding.
- Limit automatic retries when GPT returns a malformed edit response.
### Aider v0.6.2* Support for `gpt-3.5-turbo-16k`, and all OpenAI chat models
* Improved ability to correct when gpt-4 omits leading whitespace in code edits
* Added `--openai-api-base` to support API proxies, etc.
### Aider v0.5.0- Added support for `gpt-3.5-turbo` and `gpt-4-32k`.
- Added `--map-tokens` to set a token budget for the repo map, along with a PageRank based algorithm for prioritizing which files and identifiers to include in the map.
- Added in-chat command `/tokens` to report on context window token usage.
- Added in-chat command `/clear` to clear the conversation history.
<!--[[[end]]]-->
{: .tip }
All API keys can be stored in a
[.env file](/docs/config/dotenv.html).
Only OpenAI and Anthropic keys can be stored in the
[YAML config file](/docs/config/aider_conf.html).
{: .tip }
Use `/help <question>` to
[ask for help about using aider](/docs/troubleshooting/support.html),
customizing settings, troubleshooting, using LLMs, etc.
If you need more help, please check our
[GitHub issues](https://github.com/paul-gauthier/aider/issues)
and file a new issue if your problem isn't discussed.
Or drop into our
[Discord](https://discord.gg/Tv2uQnR88V)
to chat with us.
When reporting problems, it is very helpful if you can provide:
- Aider version
- LLM model you are using
Including the "announcement" lines that
aider prints at startup
is an easy way to share this helpful info.
Aider v0.37.1-dev
Models: gpt-4o with diff edit format, weak model gpt-3.5-turbo
Git repo: .git with 243 files
Repo-map: using 1024 tokens
Model foobar: Unknown context window size and costs, using sane defaults.
If you specify a model that aider has never heard of, you will get
this warning.
This means aider doesn't know the context window size and token costs
for that model.
Aider will use an unlimited context window and assume the model is free,
so this is not usually a significant problem.
See the docs on
[configuring advanced model settings](/docs/config/adv-model-settings.html)
for details on how to remove this warning.
{: .tip }
You can probably ignore the unknown context window size and token costs warning.
## Did you mean?
If aider isn't familiar with the model you've specified,
it will suggest similarly named models.
This helps
in the case where you made a typo or mistake when specifying the model name.
Model gpt-5o: Unknown context window size and costs, using sane defaults.
Did you mean one of these?
gpt-4o
## Missing environment variables
You need to set the listed environment variables.
Otherwise you will get error messages when you start chatting with the model.
Model azure/gpt-4-turbo: Missing these environment variables:
AZURE_API_BASE
AZURE_API_VERSION
AZURE_API_KEY
{: .tip }
On Windows,
if you just set these environment variables using `setx` you may need to restart your terminal or
command prompt for the changes to take effect.
## Unknown which environment variables are required
Model gpt-5: Unknown which environment variables are required.
Aider is unable verify the environment because it doesn't know
which variables are required for the model.
If required variables are missing,
you may get errors when you attempt to chat with the model.
You can look in the [aider's LLM documentation](/docs/llms.html)
or the
[litellm documentation](https://docs.litellm.ai/docs/providers)
to see if the required variables are listed there.
You can send long, multi-line messages in the chat in a few ways:
- Paste a multi-line message directly into the chat.
- Enter `{` alone on the first line to start a multiline message and `}` alone on the last line to end it.
- Use Meta-ENTER to start a new line without sending the message (Esc+ENTER in some environments).
<footerclass="site-footer">
Aider is AI pair programming in your terminal.
Aider is on
<ahref="https://github.com/paul-gauthier/aider">GitHub</a>
and
<ahref="https://discord.gg/Tv2uQnR88V">Discord</a>.
</footer>
{: .tip }
In some environments you may get "aider command not found" errors.
You can try `python -m aider` or
[see here for more info](/docs/troubleshooting/aider-not-found.html).
Aider has special support for providing
OpenAI and Anthropic API keys
via
[command line switches](/docs/config/options.html)
and
[yaml config file](/docs/config/aider_conf.html).
*All other LLM providers* must
have their keys and settings
specified in environment variables.
This can be done in your shell,
or by using a
[.env file](/docs/config/dotenv.html).
{: .tip }
Using a Python
[virtual environment](https://docs.python.org/3/library/venv.html){:target="_blank"}
is recommended.
Or, you could
[use pipx to install aider](/docs/install/pipx.html)
once for your whole system.
<!DOCTYPE html><htmllang="en-US"><metacharset="utf-8"><title>Redirecting…</title><linkrel="canonical" href="{{ page.redirect.to }}"><script>location="{{ page.redirect.to }}"</script><metahttp-equiv="refresh" content="0; url={{ page.redirect.to }}"><h1>Redirecting…</h1><ahref="{{ page.redirect.to }}">Click here if you are not redirected.</a></html>
---title: Building a better repository map with tree sitterexcerpt: Tree-sitter allows aider to build a repo map that better summarizes large code bases.highlight_image: /assets/robot-ast.pngnav_exclude: true---
{% if page.date %}
<pclass="post-date">{{ page.date | date: "%B %d, %Y" }}</p>
{% endif %}
# Building a better repository map with tree sitter
GPT-4 is extremely useful for "self-contained" coding tasks,
like generating or modifying a simple function
that has no dependencies. Tools like GitHub CoPilot serve
these simple coding tasks well.
But making complex changes in a larger, pre-existing codebase
is much more difficult, for both humans and AIs.
To do this successfully, you need to:
1. Find the code that needs to be changed.
2. Understand how that code relates to the rest of the codebase.
3. Make the correct code change to accomplish the task.
GPT-4 is actually great at making the code changes (3),
once you tell it which files need to be changed (1)
and show it how they fit into the rest of the codebase (2).
This article is going to focus on step (2), providing "code context":
- We need to help GPT understand the overall codebase.
- This will help it understand the code it needs to change, which may depend on other parts of the codebase.
- It will also help GPT write new code and modify the existing code in a way
that respects and utilizes existing libraries, modules and abstractions
found elsewhere in the codebase.
- We must convey all of this "code context" to GPT in an
efficient manner that fits within the limited context window.
To address these issues, aider
sends GPT a **concise map of your whole git repository**
that includes
the most important classes and functions along with their types and call signatures.
This **repository map** is now built automatically using
[tree-sitter](https://tree-sitter.github.io/tree-sitter/)
to extract symbol definitions from source files.
Tree-sitter is used by many IDEs, editors and LSP servers to
help humans search and navigate large codebases.
Aider now uses it to help GPT better comprehend, navigate
and edit code in larger repos.
*To code with GPT-4 using the techniques discussed here, just install [aider](https://aider.chat/docs/install.html).*## The problem: code context
GPT-4 is great at "self contained" coding tasks, like writing or
modifying a pure function with no external dependencies.
GPT can easily handle requests like "write a
Fibonacci function" or "rewrite this loop using list
comprehensions", because they require no context beyond the code
being discussed.
Most real code is not pure and self-contained, it is intertwined with
and depends on code from many different files in a repo.
If you ask GPT to "switch all the print statements in class Foo to
use the BarLog logging system", it needs to see and
modify the code in the Foo class, but it also needs to understand
how to use
the project's BarLog
subsystem.
A simple solution is to **send the entire codebase** to GPT along with
each change request. Now GPT has all the context! But this won't work
for even moderately
sized repos, because they won't fit into the context window.
A better approach is to be selective,
and **hand pick which files to send**.
For the example above, you could send the file that
contains the Foo class
and the file that contains the BarLog logging subsystem.
This works pretty well, and is supported by aider -- you
can manually specify which files to "add to the chat" you are having with GPT.
But sending whole files is a bulky way to send code context,
wasting the precious context window.
GPT doesn't need to see the entire implementation of BarLog,
it just needs to understand it well enough to use it.
You may quickly run out of context window by sending
full files of code
just to convey context.
Aider also strives to reduce the manual work involved in
coding with AI.
So in an ideal world, we'd like aider to automatically
identify and provide the needed code context.
## Using a repo map to provide context
Aider sends a **repo map** to GPT along with
each request from the user to make a code change.
The map contains a list of the files in the
repo, along with the key symbols which are defined in each file.
It shows how each of these symbols are defined in the
source code, by including the critical lines of code for each definition.
Here's a
sample of the map of the aider repo, just showing the maps of
[base_coder.py](https://github.com/paul-gauthier/aider/blob/main/aider/coders/base_coder.py)
and
[commands.py](https://github.com/paul-gauthier/aider/blob/main/aider/commands.py)
:
Mapping out the repo like this provides some key benefits:
- GPT can see classes, methods and function signatures from everywhere in the repo. This alone may give it enough context to solve many tasks. For example, it can probably figure out how to use the API exported from a module just based on the details shown in the map.
- If it needs to see more code, GPT can use the map to figure out by itself which files it needs to look at in more detail. GPT will then ask to see these specific files, and aider will automatically add them to the chat context.
## Optimizing the map
Of course, for large repositories even just the repo map might be too large
for GPT's context window.
Aider solves this problem by sending just the **most relevant**
portions of the repo map.
It does this by analyzing the full repo map using
a graph ranking algorithm, computed on a graph
where each source file is a node and edges connect
files which have dependencies.
Aider optimizes the repo map by
selecting the most important parts of the codebase
which will
fit into the token budget assigned by the user
(via the `--map-tokens` switch, which defaults to 1k tokens).
The sample map shown above doesn't contain *every* class, method and function from those
files.
It only includes the most important identifiers,
the ones which are most often referenced by other portions of the code.
These are the key pieces of context that GPT needs to know to understand
the overall codebase.
## Using tree-sitter to make the map
Under the hood, aider uses
[tree sitter](https://tree-sitter.github.io/tree-sitter/)
to build the
map.
It specifically uses the
[py-tree-sitter-languages](https://github.com/grantjenks/py-tree-sitter-languages)
python module,
which provides simple, pip-installable binary wheels for
[most popular programming languages](https://github.com/paul-gauthier/grep-ast/blob/main/grep_ast/parsers.py).
Tree-sitter parses source code into an Abstract Syntax Tree (AST) based
on the syntax of the programming language.
Using the AST, we can identify where functions, classes, variables, types and
other definitions occur in the source code.
We can also identify where else in the code these things are used or referenced.
Aider uses all of these definitions and references to
determine which are the most important identifiers in the repository,
and to produce the repo map that shows just those key
lines from the codebase.
## What about ctags?
The tree-sitter repository map replaces the
[ctags based map](https://aider.chat/docs/ctags.html)
that aider originally used.
Switching from ctags to tree-sitter provides a bunch of benefits:
- The map is richer, showing full function call signatures and other details straight from the source files.
- Thanks to `py-tree-sitter-languages`, we get full support for many programming languages via a python package that's automatically installed as part of the normal `python -m pip install aider-chat`.
- We remove the requirement for users to manually install `universal-ctags` via some external tool or package manager (brew, apt, choco, etc).
- Tree-sitter integration is a key enabler for future work and capabilities for aider.
## Future work
You'll recall that we identified the 3 key steps
required to use GPT
to complete a coding task within a large, pre-existing codebase:
1. Find the code that needs to be changed.
2. Understand how that code relates to the rest of the codebase.
3. Make the correct code change to accomplish the task.
We're now using tree-sitter to help solve the code context problem (2),
but it's also an important foundation
for future work on automatically finding all the code which
will need to be changed (1).
Right now, aider relies on the user to specify which source files
will need to be modified to complete their request.
Users manually "add files to the chat" using aider's `/add` command,
which makes those files available for GPT to modify.
This works well, but a key piece of future work is to harness the
power of GPT and tree-sitter to automatically identify
which parts of the code will need changes.
## Try it out
To code with GPT-4 using the techniques discussed here,
just install [aider](https://aider.chat/docs/install.html).
## Credits
Aider uses
[modified versions of the tags.scm files](https://github.com/paul-gauthier/aider/tree/main/aider/queries)
from these
open source tree-sitter language implementations:
* [https://github.com/tree-sitter/tree-sitter-c](https://github.com/tree-sitter/tree-sitter-c) — licensed under the MIT License.
* [https://github.com/tree-sitter/tree-sitter-c-sharp](https://github.com/tree-sitter/tree-sitter-c-sharp) — licensed under the MIT License.
* [https://github.com/tree-sitter/tree-sitter-cpp](https://github.com/tree-sitter/tree-sitter-cpp) — licensed under the MIT License.
* [https://github.com/Wilfred/tree-sitter-elisp](https://github.com/Wilfred/tree-sitter-elisp) — licensed under the MIT License.
* [https://github.com/elixir-lang/tree-sitter-elixir](https://github.com/elixir-lang/tree-sitter-elixir) — licensed under the Apache License, Version 2.0.
* [https://github.com/elm-tooling/tree-sitter-elm](https://github.com/elm-tooling/tree-sitter-elm) — licensed under the MIT License.
* [https://github.com/tree-sitter/tree-sitter-go](https://github.com/tree-sitter/tree-sitter-go) — licensed under the MIT License.
* [https://github.com/tree-sitter/tree-sitter-java](https://github.com/tree-sitter/tree-sitter-java) — licensed under the MIT License.
* [https://github.com/tree-sitter/tree-sitter-javascript](https://github.com/tree-sitter/tree-sitter-javascript) — licensed under the MIT License.
* [https://github.com/tree-sitter/tree-sitter-ocaml](https://github.com/tree-sitter/tree-sitter-ocaml) — licensed under the MIT License.
* [https://github.com/tree-sitter/tree-sitter-php](https://github.com/tree-sitter/tree-sitter-php) — licensed under the MIT License.
* [https://github.com/tree-sitter/tree-sitter-python](https://github.com/tree-sitter/tree-sitter-python) — licensed under the MIT License.
* [https://github.com/tree-sitter/tree-sitter-ql](https://github.com/tree-sitter/tree-sitter-ql) — licensed under the MIT License.
* [https://github.com/r-lib/tree-sitter-r](https://github.com/r-lib/tree-sitter-r) — licensed under the MIT License.
* [https://github.com/tree-sitter/tree-sitter-ruby](https://github.com/tree-sitter/tree-sitter-ruby) — licensed under the MIT License.
* [https://github.com/tree-sitter/tree-sitter-rust](https://github.com/tree-sitter/tree-sitter-rust) — licensed under the MIT License.
* [https://github.com/tree-sitter/tree-sitter-typescript](https://github.com/tree-sitter/tree-sitter-typescript) — licensed under the MIT License.
---title: Claude 3 beats GPT-4 on Aider's code editing benchmarkexcerpt: Claude 3 Opus outperforms all of OpenAI's models on Aider's code editing benchmark, making it the best available model for pair programming with AI.highlight_image: /assets/2024-03-07-claude-3.jpgnav_exclude: true---
{% if page.date %}
<pclass="post-date">{{ page.date | date: "%B %d, %Y" }}</p>
{% endif %}
# Claude 3 beats GPT-4 on Aider's code editing benchmark[](https://aider.chat/assets/2024-03-07-claude-3.svg)[Anthropic just released their new Claude 3 models](https://www.anthropic.com/news/claude-3-family)
with evals showing better performance on coding tasks.
With that in mind, I've been benchmarking the new models
using Aider's code editing benchmark suite.
Claude 3 Opus outperforms all of OpenAI's models,
making it the best available model for pair programming with AI.
To use Claude 3 Opus with aider:
## Aider's code editing benchmark
[Aider](https://github.com/paul-gauthier/aider)
is an open source command line chat tool that lets you
pair program with AI on code in your local git repo.
Aider relies on a
[code editing benchmark](https://aider.chat/docs/benchmarks.html)
to quantitatively evaluate how well
an LLM can make changes to existing code.
The benchmark uses aider to try and complete
[133 Exercism Python coding exercises](https://github.com/exercism/python).
For each exercise,
Exercism provides a starting python file with stubs for the needed functions,
a natural language description of the problem to solve
and a test suite to evaluate whether the coder has correctly solved the problem.
The LLM gets two tries to solve each problem:
1. On the first try, it gets the initial stub code and the English description of the coding task. If the tests all pass, we are done.
2. If any tests failed, aider sends the LLM the failing test output and gives it a second try to complete the task.
## Benchmark results
### Claude 3 Opus
- The new `claude-3-opus-20240229` model got the highest score ever on this benchmark, completing 68.4% of the tasks with two tries.
- Its single-try performance was comparable to the latest GPT-4 Turbo model `gpt-4-0125-preview`, at 54.1%.
- While Opus got the highest score, it was only a few points higher than the GPT-4 Turbo results. Given the extra costs of Opus and the slower response times, it remains to be seen which is the most practical model for daily coding use.
### Claude 3 Sonnet
- The new `claude-3-sonnet-20240229` model performed similarly to OpenAI's GPT-3.5 Turbo models with an overall score of 54.9% and a first-try score of 43.6%.
## Code editing
It's highly desirable to have the LLM send back code edits as
some form of diffs, rather than having it send back an updated copy of the
entire source code.
Weaker models like GPT-3.5 are unable to use diffs, and are stuck sending back
updated copies of entire source files.
Aider uses more efficient
[search/replace blocks](https://aider.chat/2023/07/02/benchmarks.html#diff)
with the original GPT-4
and
[unified diffs](https://aider.chat/2023/12/21/unified-diffs.html#unified-diff-editing-format)
with the newer GPT-4 Turbo models.
Claude 3 Opus works best with the search/replace blocks, allowing it to send back
code changes efficiently.
Unfortunately, the Sonnet model was only able to work reliably with whole files,
which limits it to editing smaller source files and uses more tokens, money and time.
## Other observations
There are a few other things worth noting:
- Claude 3 Opus and Sonnet are both slower and more expensive than OpenAI's models. You can get almost the same coding skill faster and cheaper with OpenAI's models.
- Claude 3 has a 2X larger context window than the latest GPT-4 Turbo, which may be an advantage when working with larger code bases.
- The Claude models refused to perform a number of coding tasks and returned the error "Output blocked by content filtering policy". They refused to code up the [beer song](https://exercism.org/tracks/python/exercises/beer-song) program, which makes some sort of superficial sense. But they also refused to work in some larger open source code bases, for unclear reasons.
- The Claude APIs seem somewhat unstable, returning HTTP 5xx errors of various sorts. Aider automatically recovers from these errors with exponential backoff retries, but it's a sign that Anthropic made be struggling under surging demand.
---title: GPT-4 Turbo with Vision is a step backwards for codingexcerpt: OpenAI's GPT-4 Turbo with Vision model scores worse on aider's code editing benchmarks than all the previous GPT-4 models. In particular, it seems much more prone to "lazy coding" than the existing GPT-4 Turbo "preview" models.highlight_image: /assets/2024-04-09-gpt-4-turbo-laziness.jpgnav_exclude: true---
{% if page.date %}
<pclass="post-date">{{ page.date | date: "%B %d, %Y" }}</p>
{% endif %}
# GPT-4 Turbo with Vision is a step backwards for coding[OpenAI just released GPT-4 Turbo with Vision](https://twitter.com/OpenAIDevs/status/1777769463258988634)
and it performs worse on aider's coding benchmark suites than all the previous GPT-4 models.
In particular, it seems much more prone to "lazy coding" than the
existing GPT-4 Turbo "preview" models.
## Code editing skill[](https://aider.chat/assets/2024-04-09-gpt-4-turbo.svg)
Aider relies on a
[code editing benchmark](https://aider.chat/docs/benchmarks.html#the-benchmark)
to quantitatively evaluate how well
an LLM can make changes to existing code.
The benchmark uses aider to try and complete
[133 Exercism Python coding exercises](https://github.com/exercism/python).
For each exercise, the LLM gets two tries to solve each problem:
1. On the first try, it gets initial stub code and the English description of the coding task. If the tests all pass, we are done.
2. If any tests failed, aider sends the LLM the failing test output and gives it a second try to complete the task.
**GPT-4 Turbo with Vision
scores only 62% on this benchmark,
the lowest score of any of the existing GPT-4 models.**
The other models scored 63-66%, so this represents only a small
regression, and is likely statistically insignificant when compared
against `gpt-4-0613`.
## Lazy coding[](https://aider.chat/assets/2024-04-09-gpt-4-turbo-laziness.svg)
The GPT-4 Turbo "preview" models have been widely criticized for being "lazy"
when coding.
They often omit needed code
and instead leave comments with homework assignments like "implement method here".
def some_complex_method(foo, bar):
# ... implement method here ...
Aider uses a ["laziness" benchmark suite](https://github.com/paul-gauthier/refactor-benchmark)
which is designed to both provoke and quantify lazy coding.
It consists of
89 python refactoring tasks
which tend to make GPT-4 Turbo code in that lazy manner.
**The new GPT-4 Turbo with Vision model scores only 34% on aider's
refactoring benchmark, making it the laziest coder of all the GPT-4 Turbo models
by a significant margin.**
# Conclusions
Aider has full support for the new GPT-4 Turbo with Vision
model, which you can access using the switch `--model gpt-4-turbo-2024-04-09`.
But aider will continue to use `gpt-4-1106-preview` by default,
as it is by far the strongest coder of the GPT-4 models.
---title: Aider in your browserexcerpt: Aider has an experimental browser UI, allowing you to collaborate with LLMs on code in your local git repo.highlight_image: /assets/browser.jpg---
{% if page.date %}
<pclass="post-date">{{ page.date | date: "%B %d, %Y" }}</p>
{% endif %}
# Aider in your browser
<divclass="video-container">
<videocontrolsloopposter="/assets/browser.jpg">
<source src="/assets/aider-browser-social.mp4" type="video/mp4"><a href="/assets/aider-browser-social.mp4">Aider browser UI demo video</a>
</video>
</div>
<style>
.video-container {
position: relative;
padding-bottom: 101.89%; /* 1080 / 1060 = 1.0189 */height: 0;
overflow: hidden;
}
.video-containervideo {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
</style>
Use aider's new experimental browser UI to collaborate with LLMs
to edit code in your local git repo.
Aider will directly edit the code in your local source files,
and [git commit the changes](https://aider.chat/docs/git.html)
with sensible commit messages.
You can start a new project or work with an existing git repo.
Aider works well with GPT 3.5, GPT-4, GPT-4 Turbo with Vision,
and Claude 3 Opus.
It also supports [connecting to almost any LLM](https://aider.chat/docs/llms.html).
Use the `--browser` switch to launch the browser version of aider:
---title: Drawing graphs with aider, GPT-4o and matplotlibexcerpt: Use GPT-4o to draw graphs with matplotlib, including adjusting styles and making visual changes. You get the graph, but you also get the code in your repo.highlight_image: /assets/models-over-time.pngnav_exclude: true---
{% if page.date %}
<pclass="post-date">{{ page.date | date: "%B %d, %Y" }}</p>
{% endif %}
# Drawing graphs with aider, GPT-4o and matplotlib
I recently wanted to draw a graph showing how LLM code editing skill has been
changing over time as new models have been released by OpenAI, Anthropic and others.
I have all the
[data in a yaml file](https://github.com/paul-gauthier/aider/blob/main/website/_data/edit_leaderboard.yml) that is used to render
[aider's LLM leaderboards](https://aider.chat/docs/leaderboards/).
Below is the aider chat transcript, which shows:
- I launch aider with the yaml file, a file with other plots I've done recently (so GPT can crib the style) and an empty file called `over_time.py`.
- Then I ask GPT to draw the scatterplot I want.
- I run the resulting script and share the error output with GPT so it can fix a small bug.
- I ask it to color the points for GPT-4 and GPT-3.5 family models differently, to better see trends within those model families.
- I add a PNG of the graph to the chat, so GPT can see the current graph and understand why I want it to move the point labels so they don't overlap the points.
- I work through a series of other small style changes, like changing fonts and the graph border.
In the end I have the graph, but I also have the python code in my repo.
So I can update this graph easily whenever I add new entries to the yaml data file.
## Aider chat transcript
<divclass="chat-transcript"markdown="1">
> Aider v0.35.1-dev > Models: gpt-4o with diff edit format, weak model gpt-3.5-turbo > Added _data/edit_leaderboard.yml to the chat. > Added benchmark/over_time.py to the chat. > Added benchmark/plots.py to the chat. #### in over_time.py, draw a graph for each of the yaml entries with a `released` date. plot date on x, `pass_rate_2` on y and label with the `model` name. do a scatter plot. use colors/styles similar to the other graphs.
To draw a scatter plot for each of the YAML entries with a `released` date, we need to:
1. Read the YAML file.
2. Extract the `released` date and `pass_rate_2` for each entry.
3. Plot the data using matplotlib.
Here are the changes:
benchmark/over_time.py
```python<<<<<<<SEARCH=======import matplotlib.pyplot as plt
import yaml
from datetime import datetime
defplot_over_time(yaml_file):
withopen(yaml_file, 'r') asfile:
data = yaml.safe_load(file)
dates = []
pass_rates = []
models = []
for entry in data:
if'released'in entry and'pass_rate_2'in entry:
dates.append(datetime.strptime(entry['released'], '%Y-%m-%d'))
pass_rates.append(entry['pass_rate_2'])
models.append(entry['model'])
plt.figure(figsize=(10, 6))
plt.scatter(dates, pass_rates, c='blue', alpha=0.5)
for i, model inenumerate(models):
plt.annotate(model, (dates[i], pass_rates[i]), fontsize=8, alpha=0.75)
plt.xlabel('Release Date')
plt.ylabel('Pass Rate 2')
plt.title('Model Performance Over Time')
plt.grid(True)
plt.tight_layout()
plt.show()
# Example usage
plot_over_time('_data/edit_leaderboard.yml')
>>>>>>>REPLACE
Applied edit to benchmark/over_time.py
Commit 49ac9ca aider: Added scatter plot functionality for YAML entries with a released date and pass_rate_2.
/run python benchmark/over_time.py
Traceback (most recent call last):
File "/Users/gauthier/Projects/aider/benchmark/over_time.py", line 33, in
plot_over_time('_data/edit_leaderboard.yml')
File "/Users/gauthier/Projects/aider/benchmark/over_time.py", line 15, in plot_over_time
dates.append(datetime.strptime(entry['released'], '%Y-%m-%d'))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: strptime() argument 1 must be str, not datetime.date
Add the output to the chat? y
Traceback (most recent call last):
File "/Users/gauthier/Projects/aider/benchmark/over_time.py", line 33, in
plot_over_time('_data/edit_leaderboard.yml')
File "/Users/gauthier/Projects/aider/benchmark/over_time.py", line 15, in plot_over_time
dates.append(datetime.strptime(entry['released'], '%Y-%m-%d'))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: strptime() argument 1 must be str, not datetime.date
The error indicates that the released field in the YAML file is already a datetime.date object, so we don't need to parse it with datetime.strptime. We can directly use it in the plot.
Applied edit to benchmark/over_time.py
Commit af2f4b7 aider: Use the released field directly in the plot instead of parsing it with datetime.strptime.
color the "gpt-4" models differently
To color the "gpt-4" models differently, we need to modify the plotting code in benchmark/over_time.py to check for "gpt-4" in the model name and assign a different color.
This change will color the points red if the model name contains "gpt-4", otherwise, it will color them blue.
Applied edit to benchmark/over_time.py
Commit 0d11357 aider: Color the "gpt-4" models differently.
color the gpt-3.5 models a new color
To color the "gpt-3.5" models a new color, we need to modify the plotting code in benchmark/over_time.py to check for "gpt-3.5" in the model name and assign a different color.
Committing benchmark/over_time.py before applying edits.
Commit 49eb72c Updated image file format from SVG to PNG and added imgcat library for displaying the plot.
Applied edit to benchmark/over_time.py
Commit 75fa061 aider: Adjust the position of labels to prevent overlap with dots.
make the dots bigger
To make the dots bigger, we can adjust the s parameter in the scatter function, which controls the size of the dots.
Applied edit to benchmark/over_time.py
Commit 77ba518 aider: Made the border of the graph thinner and lighter by adjusting the spines properties of the axes.
paul-gauthier/aider/blob/main/aider/website/_posts/2024-05-22-draft.md:
```md
---
title: A draft post.
excerpt: With a draft summary.
highlight_image: /assets/linting.jpg
draft: true
nav_exclude: true
---
{% if page.date %}
<p class="post-date">{{ page.date | date: "%B %d, %Y" }}</p>
{% endif %}
# A draft post
Content TBD.
---title: Linting code for LLMs with tree-sitterexcerpt: Aider now lints code after every LLM edit and automatically fixes errors, using tree-sitter and AST-aware code context.highlight_image: /assets/linting.jpgnav_exclude: true---
{% if page.date %}
<pclass="post-date">{{ page.date | date: "%B %d, %Y" }}</p>
{% endif %}
[](https://aider.chat/assets/linting.jpg)# Linting code for LLMs with tree-sitter
Aider now lints your code after every LLM edit, and offers to automatically fix
any linting errors.
You can also use aider's lint-and-fix functionality on your source files any time
you like, to speedily resolve issues with code written by humans.
Aider shows linting errors to the LLM in a novel format,
using tree-sitter
to help display relevant code context for each
error.
This increases the ability of the LLM to understand the problem and
make the correct changes to resolve it.
Aider ships with basic linters built with tree-sitter that support
[most popular programming languages](https://github.com/paul-gauthier/grep-ast/blob/main/grep_ast/parsers.py).
These built in linters will detect syntax errors and other fatal problems with the code.
You can also configure aider to use your preferred linters.
This allows aider to check for a larger class of problems, keep the code style
aligned with the rest of your team, etc.
## Linting and fixing your code
Aider now lints each source file after it applies the edits
suggested by an LLM.
If problems are found, aider will ask if you'd like it to
attempt to fix the errors.
If so, aider will send the LLM a report of the lint errors
and request changes to fix them. This process may iterate a few times
as the LLM works to fully resolve all the issues.
You can also lint and fix files any time, on demand from within the aider chat or via the
command line:
- The in-chat `/lint` command will lint and fix all the files which have
been added to the chat by default. Or you can name any files
in your git repo as arguments.
- From the command line, you can run `aider --lint` to lint and fix
all the dirty files in the repo.
Or you can specify specific filenames on the command line.
## An LLM-friendly lint report
Most linting tools produce terse and cryptic output,
which is one reason many engineers appreciate IDEs that highlight
linting errors.
LLM's don't have the luxury of using an IDE, so aider sends
the linting errors in an LLM friendly format.
Here's an example of raw output of the `flake8` python linter:
app.py:23:36: F821 undefined name 'num'
app.py:41:16: F541 f-string is missing placeholders
This sort of output depends on the user to reference line numbers to find and fix
each reported error.
LLMs are quite bad at working with source code line numbers, often
making off-by-one errors and other mistakes even when provided with
a fully numbered code listing.
Aider augments the raw linter by
displaying and
highlighting the lines that have errors within their
containing functions, methods, classes.
To do this, aider uses tree-sitter to obtain the code's AST and analyzes it
in light of the linting errors.
LLMs are more effective at editing code that's provided
with context like this.
app.py:23:36: F821 undefined name 'num'
app.py:41:16: F541 f-string is missing placeholders
app.py:
...⋮...
6│class LongNum:
7│ def init(self, num):
8│ """
9│ Initialize the number.
10│ """
...⋮...
19│ def str(self):
20│ """
21│ Render the number as a string.
22│ """
23█ return str(num)
24│
25│
26│@app.route('/subtract/int:x/int:y')
...⋮...
38│@app.route('/divide/int:x/int:y')
39│def divide(x, y):
40│ if y == 0:
41█ return f"Error: Cannot divide by zero"
42│ else:
43│ result = x / y
44│ return str(result)
45│
...⋮...
## Basic linters for most popular languages
Aider comes batteries-included with built in linters for
[most popular programming languages](https://aider.chat/docs/languages.html).
This provides wide support for linting without requiring
users to manually install a linter and configure it to work with aider.
Aider's built in language-agnostic linter uses tree-sitter to parse
the AST of each file.
When tree-sitter encounters a syntax error or other fatal issue
parsing a source file, it inserts an AST node with type `ERROR`.
Aider simply uses these `ERROR` nodes to identify all the lines
with syntax or other types of fatal error, and displays
them in the LLM friendly format described above.
## Configuring your preferred linters
You can optionally configure aider to use
your preferred linters with the `--lint-cmd` switch.
To lint javascript with jslint
aider --lint-cmd javascript:jslint
To lint python with flake8 using some specific args:
---title: How aider scored SOTA 26.3% on SWE Bench Liteexcerpt: Aider achieved this result mainly through its existing features that focus on static code analysis, reliable LLM code editing, and pragmatic UX for AI pair programming.highlight_image: /assets/swe_bench_lite.jpgnav_exclude: true---
{% if page.date %}
<pclass="post-date">{{ page.date | date: "%B %d, %Y" }}</p>
{% endif %}
# How aider scored SOTA 26.3% on SWE Bench Lite[Aider scored 26.3%](https://github.com/swe-bench/experiments/pull/7)
on the
[SWE Bench Lite benchmark](https://www.swebench.com),
achieving a state-of-the-art result.
The previous top leaderboard entry was 20.3%
from Amazon Q Developer Agent.
See also [aider's SOTA result on the main SWE Bench](https://aider.chat/2024/06/02/main-swe-bench.html).
[](https://aider.chat/assets/swe_bench_lite.svg)**All of aider's results reported here are pass@1 results,
obtained without using the SWE Bench `hints_text`.**
All results in the above chart are unhinted pass@1 results.
Please see the [references](#references)
for details on the data presented in this chart.
It was corrected on 5/30/24 to reflect apples-to-apples comparisons,
using pass@1 results from AutoCodeRover
and results from OpenDevin that don't use hints.
The [official SWE Bench Lite leaderboard](https://www.swebench.com)
only accepts pass@1 results that do not use hints.
## Interactive, not agentic
Aider achieved this result mainly through its existing features that focus on static code analysis, reliable LLM code editing, and pragmatic UX for AI pair programming.
Aider intentionally has quite limited and narrow "agentic behavior"
to avoid long delays, high token costs
and the need for users to repeatedly code review incorrect solutions.
It's also worth noting that aider currently does not use
RAG, vector search, tools or give the LLM access to search the web
or unilaterally execute code.
Aider is first and foremost an interactive tool for engineers to get real work done in
real code bases using a chat interface.
Aider provides a pair programming UX where users can ask for a change
and see the edits performed in real-time.
Aider can also offer additional help like fixing lint or test errors,
but the user is always in full interactive control.
This lets them quickly steer misunderstandings back on course and
avoid wasting time and token costs.
## Benchmark methodology
For the benchmark,
aider was launched in each problem's git repository
with the problem statement
submitted as the opening chat message from "the user."
After that aider runs as normal, with the following modifications:
- Aider's suggestions were always accepted without user approval.
- A simple harness was used to retry the SWE Bench problem if aider produced code that wasn't *plausibly correct*.
Plausibly correct means that aider reported that it had successfully edited the repo
without causing syntax errors or breaking any *pre-existing* tests.
- If the solution isn't plausible, the harness launches aider to try again from scratch,
alternating between using aider with GPT-4o and Opus.
- If no plausible solution is found after six tries, the harness picks the solution
with the fewest edit/lint/test problems.
It's important to be clear that
*aider and the benchmark harness
only had access to the pre-existing tests in each problem's repo*.
The held out "acceptance tests" were *only* used
after benchmarking to compute statistics on which problems aider
correctly resolved.
The [full harness to run aider on SWE Bench Lite is available on GitHub](https://github.com/paul-gauthier/aider-swe-bench).
The benchmarking process was similar to how a developer might use aider to
resolve a GitHub issue:
- They could launch aider in their repo with the command below, which
tells aider they want to accept every suggestion
and to use pytest to run tests.
-`aider --yes --test-cmd pytest`- They could start the chat by pasting in the URL or text of a GitHub issue.
Aider will pull in the URL's content and then try and solve the issue.
- If aider doesn't produce code that lints and tests clean, the user might decide to revert the changes and try again, maybe using aider with a different LLM this time.
[Aider is tightly integrated with git](https://aider.chat/docs/git.html),
so it's always easy to revert AI changes that don't pan out.
Outside a benchmark setting, it's probably
unwise or at least highly inefficient
to let *any* AI agent run unsupervised on your code base.
The reason aider is intended to be used interactively
is so that the user can participate and direct aider's work and approve suggestions.
This way the user can offer immediate feedback or corrections if their initial
instructions turn out to be ambiguous,
or if the AI starts going down a wrong path.
## Aider with GPT-4o alone was SOTA
Running the benchmark harness
only using aider with GPT-4o to find plausible solutions
achieved a score of 25.0%.
This was itself matching the state-of-the-art, before being surpassed by the main
result being reported here
that used aider with both GPT-4o & Opus.
As noted below, a single attempt using Aider with GPT-4o tied
the current top entry on the leaderboard.
## Aider with GPT-4o & Opus
The benchmark harness alternated between running aider with GPT-4o and Opus.
The harness proceeded in a fixed order, always starting with GPT-4o and
then alternating with Opus until a plausible solution was found for each
problem.
The table below breaks down the plausible solutions that
were found for the 300 problems.
It also provides details on the 79 that were ultimately
verified as correctly resolving their issue.
Some noteworthy observations:
-*Just the first attempt* of Aider with GPT-4o resolved 20.3% of the problems, which ties the Amazon Q Developer Agent currently atop the official leaderboard.
- Including the second attempt, Aider with GPT-4o and Opus scored 23.6% on the benchmark.
These first two attempts obtained ~75% of all plausible and ~90% of all resolved solutions.
- A long tail of solutions continued to be found using both models including one correctly resolved solution on the final, sixth attempt of that problem.
| Attempt | Agent |Number of<br>plausible<br>solutions|Percent of<br>plausible<br>solutions| Number of<br/>correctly<br>resolved<br>solutions | Percent of<br>correctly<br>resolved<br>solutions | Score on<br>SWE Bench<br>Lite ||:--------:|------------|---------:|---------:|----:|---:|--:|| 1 | Aider with GPT-4o | 208 | 69.3% | 61 | 77.2% | 20.3% || 2 | Aider with Opus | 49 | 16.3% | 10 | 12.7% | 3.3% || 3 | Aider with GPT-4o | 20 | 6.7% | 3 | 3.8% | 1.0% || 4 | Aider with Opus | 9 | 3.0% | 2 | 2.5% | 0.7% || 5 | Aider with GPT-4o | 11 | 3.7% | 2 | 2.5% | 0.7% || 6 | Aider with Opus | 3 | 1.0% | 1 | 1.3% | 0.3% ||**Total**||**300**|**100%**|**79**|**100%**|**26.3%**|
If we break down the solutions solely by model,
we can see that aider with GPT-4o outperforms Opus.
This isn't a fair and direct comparison, because GPT-4o always took the first
turn and therefore got first crack at all the "easiest" problems.
Aider with Opus only ever saw problems that GPT-4o failed to
find plausible solutions for on its first try.
Aider with GPT-4o was producing higher quality plausible solutions,
with a greater chance of going on to be accepted as resolving the issue.
Again, this is biased by the turn ordering.
But other anecdotal evidence from earlier runs of the benchmark
also supports the observation that aider with GPT-4o is significantly stronger than Opus
for this benchmark.
| Agent | Number of<br>plausible<br>solutions | Number of<br>correctly<br>resolved<br>solutions | Percent of<br>plausible<br>which<br>correctly<br>resolved<br>||------------|---------:|---------:|---:|| Aider with GPT-4o | 239 | 66 |27.6% || Aider with Opus | 61 | 13 |21.3% ||**Total**|**300**|**79**|**26.3%**|## Repository map, not RAG
The crucial first step in solving a SWE Bench problem is figuring out
which parts of the repo are relevant and which files need to be edited.
Most coding agents use some combination of RAG, vector search
and providing the LLM with
tools to interactively explore the code base.
Aider instead uses a
[repository map](https://aider.chat/2023/10/22/repomap.html)
to help the LLM understand the
layout, code structure, and content of a git repo.
The repo map is created through static analysis of the code's
abstract syntax tree and call graph
to provide a compact and powerful summary of the entire code base.
The map is constantly
tailored to show
repo context that is relevant to the current state of the chat conversation.
This is done by performing a graph optimization on the code's call graph.
When the user asks for a change to their code, the LLM can use the repo map
to decide which files to edit.
The LLM simply returns a normal text response explaining which files
it needs to edit and why.
Aider notices when the LLM mentions filenames from the repo,
and asks the user if they should be added to the chat.
Adding a file to the chat allows the LLM to see the full contents
of the file and edit it.
<divclass="chat-transcript"markdown="1">
#### Please add a new /factorial/N endpoint.
To add a new /factorial/N endpoint, the most likely file that needs to be edited is app.py.
Please add app.py to the chat so I can proceed with the changes.
> app.py > Add these files to the chat? yes
</div>
This is a convenient and natural workflow for interactive chat,
and it worked well for the SWE Bench problems.
Aider successfully identified the correct file to edit
in 70.3% of the benchmark tasks.
We can determine which file needs to be edited using the "gold" patch
which is associated with each SWE Bench task.
This patch was created by a human developer
to solve the issue, and therefore reveals a file which can
be edited to solve the problem.
Of course aider is not able to see or use the gold patch
or the file names it contains in any way.
This information was only used to compute
statistics outside the benchmarking process.
## Reliable code editing
Once files have been selected for editing,
the next step is of course to edit the source code to fix the problem.
Aider goes to great lengths to ensure that LLMs can not just write code,
but reliably *edit* code.
Aider has a collection of prompting strategies and code editing backends which have
been honed through
[extensive benchmarking](https://aider.chat/docs/leaderboards/).
These foundational capabilities help ensure that aider can
properly integrate code from LLMs into an existing code base and source files.
The repository map helps here too, making sure that the LLM
can see relevant classes, functions and variables from the entire repo.
This helps ensure that the project's existing APIs and conventions are
respected and utilized when new code is added.
Regardless, there are still cases where aider may be unable to cleanly
complete the edits specified by the LLM.
This is usually because the LLM has failed to conform to the editing
instructions in its system prompt.
When aider completes, it returns an editing outcome that indicates
whether it was able to successfully apply all edits.
The benchmark harness uses this editing status as
one criteria to determine if aider has
created a plausible solution.
## Linting and fixing
Another key criteria for a plausible solution is that it passes basic
linting, which means that the code has no syntax
or other fatal errors.
[Aider lints code](https://aider.chat/2024/05/22/linting.html)
after every LLM edit and offers to automatically fix
any problems.
Aider ships with built-in linters based on tree-sitter
which work with most popular programming languages.
Aider shows linting errors to the LLM in a novel format,
using the abstract syntax tree to display relevant code context for each
error.
This context helps LLMs understand the problem and
make the correct changes to resolve it.
<divclass="chat-transcript"markdown="1">
app.py:23:36: F821 undefined name 'num'
app.py:
...⋮...
6│class LongNum:
...⋮...
19│ def expound(self, threshold):
20│ number = self.basis
21│ while number < threshold:
22│ number *= self.factor
23█ return num
24│
25│
...⋮...
> Attempt to fix lint errors? yes
</div>
In the benchmark, these linting suggestions are always accepted.
At completion,
aider reports a linting outcome that
indicates if it was able to produce
code without any outstanding linting errors.
The benchmark harness uses this status as
one of the criteria to determine if aider has
created a plausible solution.
## Testing and fixing
The final crtieria for a plausible solution is that
all tests must be passing.
Aider can be configured with the command to run tests for a repo,
and will automatically attempt to fix any test failures.
A user working on a python project might configure testing
by launching aider like this:
aider --test-cmd pytest
For the benchmark, aider is configured with a test command that will run the
tests that already exist in each problem's repository.
SWE Bench problems are based on repositories from large open
source projects with extensive existing test suites.
This means that
testing will fail if aider has broken any of these
pre-existing tests or if any new
tests that it created aren't passing.
As with editing and linting, aider reports a testing outcome
that indicates if it completed with any outstanding failing tests.
The benchmark harness uses this status when deciding if aider
has produced a plausible solution.
To be clear, *aider cannot run or even see the held out "acceptance tests"* that
are used to judge if a proposed solution correctly
resolves the problem.
Those tests are only run outside of aider and the benchmark harness,
to compute the final benchmark statistics.
## Finding a plausible solution
Each time aider executes, it reports
the outcome of the editing, linting, and testing
steps.
Each of these steps may complete successfully or
return a status that indicates that there were outstanding
problems that remain unresolved.
The benchmark harness uses these outcomes to determine if
aider has produced a plausible
solution to the current SWE Bench task.
A plausible solution is one where aider
returns saying that it
edited the repo with no outstanding
edit, lint, or test errors.
In this case, aider's changes are recorded
as the SWE Bench `model_patch` to be evaluated later with the
acceptance tests.
If the solution is not plausible, another
instance of aider is launched again from scratch on the same problem.
The harness alternates launching aider with GPT-4o and Opus to solve the problem,
and gives each model three attempts -- for a total of six attempts.
As soon as a plausible solution is found, it is accepted and the
harness moves on to the next SWE Bench instance.
It's worth noting that repositories may have lint or test errors
present before aider even starts to edit them.
Whether unresolved errors were caused by aider or were pre-existing,
there will be instances where
no plausible solution is
found after six tries.
If all six attempts fail to produce a plausible solution,
then the "best" solution available is selected as the
`model_patch`.
Which of the non-plausible solutions to use is determined
by ignoring the testing outcome
and prioritizing solutions in the following order:
- Pick a solution where editing and linting were completed successfully.
- Pick a solution where editing was at least partially successful and linting succeeded.
- Pick a solution where editing was successful.
- Pick a solution where editing was at least partially successful.
## Computing the benchmark score
The benchmark harness produced a plausible solution for each of the 300
SWE Bench Lite instances and saved it as the `model_patch`.
A separate evaluation script was used to
test each of these solutions with the full test suite,
including the held out acceptance tests.
For this final acceptance testing, any edits that aider made to tests
are discarded.
This ensures that the correct,
unmodified test suite is used for acceptance testing.
The evaluation script compares the test results
with results from testing
the "gold" patch that was developed by a human to correctly solve the issue.
If they match, the candidate solution has correctly resolved the issue.
These acceptance tests are only ever run outside of aider
and the benchmark harness, and only to compute the number of
correctly resolved instances.
They are never run, used, or even visible during aider's attempts to solve the problems.
Aider correctly resolved 79 out of 300 SWE Bench Lite instances, or 26.3%.
## Acknowledgments
Much thanks to the team behind the
[SWE Bench](https://www.swebench.com)
family of AI coding benchmarks.
Also thanks to Albert Örwall who has
[dockerized the SWE Bench evaluation scripts](https://github.com/aorwall/SWE-bench-docker)
making it faster, easier, and more reliable to run the acceptance tests.
## References
All of aider's results reported here are pass@1 results,
obtained without using the SWE Bench `hints_text`.
The "aider agent" internally makes multiple "attempts" at solving the problem,
but it picks and returns one single candidate solution.
Only that one candidate solution is evaluated with the acceptance tests
and contributes to the benchmark score.
Thus it is a pass@1 result.
This is contrast to a pass@N result for N>1, where N attempts are made
and all N solutions are evaluated by the acceptance tests.
If *any* of the N solution pass, that counts as a pass@N success.
Below are the references for the other pass@1 unhinted SWE-Bench results
displayed in the graph at the beginning of this article.
- [20.3% Amazon Q Developer Agent (v20240430-dev)](https://www.swebench.com)
- [19.0% AutoCodeRover](https://www.swebench.com/)
- [18.0% SWE-Agent + GPT-4](https://www.swebench.com)
- [16.7% OpenDevin](https://github.com/OpenDevin/OpenDevin/issues/2149)
- [11.7% SWE-Agent + Opus](https://www.swebench.com)
Note, the graph was corrected on 5/30/24 as follows.
The graph now contains AutoCodeRover's average pass@1 results.
Previously it displayed pass@3 results, which are
not comparable
to the pass@1 results for aider being reported here.
The [AutoCodeRover GitHub page](https://github.com/nus-apr/auto-code-rover)
features pass@3 results
without being clearly labeled.
The graph now contains the best OpenDevin results obtained without using
the SWE Bench `hints_text` to provide hints to the agent.
The previous graph contained their hinted result,
which is not comparable
to the unhinted aider results being reported here.
[OpenDevin reported hinted results](https://x.com/gneubig/status/1791498953709752405)
without noting that hints were used.
---title: Aider has written 7% of its own codeexcerpt: Aider has written 7% of its own code, via 600+ commits that inserted 4.8K and deleted 1.5K lines of code.highlight_image: /assets/self-assembly.jpgnav_exclude: true---
{% if page.date %}
<pclass="post-date">{{ page.date | date: "%B %d, %Y" }}</p>
{% endif %}
# Aider has written 7% of its own code[](https://aider.chat/assets/self-assembly.jpg)
The
[aider git repo](https://github.com/paul-gauthier/aider)
currently contains about 4K commits and 14K lines of code.
Aider made 15% of the commits, inserting 4.8K and deleting 1.5K lines of code.
About 7% of the code now in the repo is attributable to an aider commit
using `git blame`.
This number is probably a significant undercount, because periodic reformatting
by `black` is likely obscuring aider's authorship of many lines.
Here's the breakdown of the code aider wrote in the current code base
according to `git blame`.
| File | Lines | Percent ||---|---:|---:||aider/args.py| 6 of 449 | 1.3% ||aider/coders/base_coder.py| 37 of 1354 | 2.7% ||aider/coders/editblock_coder.py| 14 of 507 | 2.8% ||aider/coders/editblock_func_coder.py| 6 of 141 | 4.3% ||aider/coders/udiff_coder.py| 2 of 421 | 0.5% ||aider/coders/wholefile_coder.py| 5 of 146 | 3.4% ||aider/coders/wholefile_func_coder.py| 4 of 134 | 3.0% ||aider/commands.py| 67 of 703 | 9.5% ||aider/diffs.py| 15 of 129 | 11.6% ||aider/gui.py| 2 of 533 | 0.4% ||aider/history.py| 19 of 124 | 15.3% ||aider/io.py| 55 of 368 | 14.9% ||aider/linter.py| 30 of 240 | 12.5% ||aider/main.py| 30 of 466 | 6.4% ||aider/mdstream.py| 3 of 122 | 2.5% ||aider/models.py| 22 of 549 | 4.0% ||aider/repo.py| 19 of 266 | 7.1% ||aider/repomap.py| 17 of 518 | 3.3% ||aider/scrape.py| 12 of 199 | 6.0% ||aider/versioncheck.py| 10 of 37 | 27.0% ||aider/voice.py| 9 of 104 | 8.7% ||benchmark/benchmark.py| 33 of 730 | 4.5% ||benchmark/over_time.py| 32 of 60 | 53.3% ||benchmark/swe_bench_lite.py| 40 of 71 | 56.3% ||scripts/blame.py| 55 of 212 | 25.9% ||scripts/versionbump.py| 96 of 123 | 78.0% ||setup.py| 11 of 47 | 23.4% ||tests/test_coder.py| 48 of 612 | 7.8% ||tests/test_commands.py| 135 of 588 | 23.0% ||tests/test_editblock.py| 23 of 403 | 5.7% ||tests/test_io.py| 30 of 65 | 46.2% ||tests/test_main.py| 13 of 239 | 5.4% ||tests/test_models.py| 6 of 28 | 21.4% ||tests/test_repo.py| 2 of 296 | 0.7% ||tests/test_repomap.py| 70 of 217 | 32.3% ||tests/test_udiff.py| 7 of 119 | 5.9% ||tests/test_wholefile.py| 37 of 321 | 11.5% ||**Total**|**1022 of 14219**| 7.2% |
---title: Aider is SOTA for both SWE Bench and SWE Bench Liteexcerpt: Aider sets SOTA for the main SWE Bench, after recently setting SOTA for the Lite version.highlight_image: /assets/swe_bench.jpgnav_exclude: true---
{% if page.date %}
<pclass="post-date">{{ page.date | date: "%B %d, %Y" }}</p>
{% endif %}
# Aider is SOTA for both SWE Bench and SWE Bench Lite
Aider scored 18.9%
on the main
[SWE Bench benchmark](https://www.swebench.com),
achieving a state-of-the-art result.
The current top leaderboard entry is 13.8%
from Amazon Q Developer Agent.
The best result reported elsewhere seems to be
[13.9% from Devin](https://www.cognition.ai/post/swe-bench-technical-report).
This result on the main SWE Bench builds on
[aider's recent SOTA result on the easier SWE Bench Lite](https://aider.chat/2024/05/22/swe-bench-lite.html).
[](https://aider.chat/assets/swe_bench.svg)**All of aider's results reported here are pass@1 results,
obtained without using the SWE Bench `hints_text`.**
Aider was benchmarked on the same
[570 randomly selected SWE Bench problems](https://github.com/CognitionAI/devin-swebench-results/tree/main/output_diffs)
that were used in the
[Devin evaluation](https://www.cognition.ai/post/swe-bench-technical-report).
See the [references](#references)
for more details on the data presented in this chart.
## Interactive, not agentic
Aider achieved this result mainly through its existing features that focus on static
code analysis, reliable LLM code editing, and pragmatic UX for automatically
fixing linting and testing errors.
Aider intentionally has quite limited and narrow "agentic behavior"
to avoid long delays, high token costs
and the need for users to repeatedly code review incorrect solutions.
It's also worth noting that aider currently does not use
RAG, vector search, tools or give the LLM access to search the web
or unilaterally execute code.
Aider is first and foremost an interactive tool for engineers to get real work done in
real code bases using a chat interface.
Aider provides a pair programming UX where users can ask for a change
and see code edits performed in real-time.
Aider can also offer additional help like fixing lint or test errors,
but the user is always in full interactive control.
This allows them to quickly steer misunderstandings back on course and
avoid wasting time and token costs.
## Benchmark methodology
Benchmarking was conducted as follows:
- Aider with GPT-4o was launched in each problem's git repository
with the problem statement
submitted as the opening chat message from "the user".
- After that aider ran as normal, except all of aider's
suggestions were always accepted without user approval.
- A [simple harness](https://github.com/paul-gauthier/aider-swe-bench#the-aider-agent) was used to retry the SWE Bench problem if aider produced code that wasn't *plausibly correct*.
Plausibly correct means that aider reported that it had successfully edited the repo
without causing syntax errors or breaking any *pre-existing* tests.
- If the solution from aider with GPT-4o wasn't plausible, the harness launched aider to try again from scratch using Claude 3 Opus.
- If no plausible solution was found after those two tries, the harness picked the "most plausible" solution with the fewest edit/lint/test problems.
It's important to be clear that
*aider and the benchmark harness
only had access to the pre-existing tests in each problem's repo*.
The held out "acceptance tests" were *only* used
after benchmarking to compute statistics on which problems aider
correctly resolved.
This is the same approach
that was used for
[aider's recent SOTA result on SWE Bench Lite](https://aider.chat/2024/05/22/swe-bench-lite.html).
For the Lite benchmark,
aider alternated between GPT-4o and Opus for up to six total attempts.
To manage the cost of running the main SWE Bench benchmark,
aider was limited to two total attempts:
one with GPT-4o and one with Opus.
For a detailed discussion of the benchmark
methodology, see the
[article about aider's SWE Bench Lite results](https://aider.chat/2024/05/22/swe-bench-lite.html).
Also, the
[aider SWE Bench repository on GitHub](https://github.com/paul-gauthier/aider-swe-bench)
contains the harness and statistics code used for the benchmarks.
The benchmarking process was similar to how a developer might use aider to
resolve a GitHub issue:
- They could launch aider in their repo with the command below, which
tells aider they want to accept every suggestion
and to use pytest to run tests.
-`aider --yes --test-cmd pytest`- They could start the chat by pasting in the URL or text of a GitHub issue.
Aider will pull in the URL's content and then try and resolve the issue.
- If aider doesn't produce code that lints and tests clean, the user might decide to
[use git to revert the changes](https://aider.chat/docs/git.html),
and try again with `aider --opus`.
## Aider with GPT-4o alone was SOTA
Using aider with GPT-4o to make a single attempt at resolving each problem
achieved a score of 17.0%.
This was itself a state-of-the-art result, before being surpassed by the main
result being reported here
that used aider with both GPT-4o & Opus.
## Aider with GPT-4o & Opus
The benchmark harness started by using aider with GPT-4o to try
and resolve each problem.
For problems where this didn't produce a plausible solution,
the harness tried again using aider with Opus.
So at most, two attempts were made for each problem.
The table below breaks down the proposed solutions that
were found from each attempt at the 570 problems.
A proposed solution is either:
- A plausible solution where
aider reported no outstanding errors from editing, linting and testing.
- Or, the "most plausible" solution generated by either attempt, with the
[fewest outstanding editing, linting or testing errors](https://aider.chat/2024/05/22/swe-bench-lite.html#finding-a-plausible-solution).
The table also provides details on the 108 solutions that were ultimately
verified as correctly resolving their issue.
| Attempt | Agent |Number of<br>proposed<br>solutions|Percent of<br>proposed<br>solutions| Number of<br/>correctly<br>resolved<br>solutions | Percent of<br>correctly<br>resolved<br>solutions | Score on<br>SWE Bench<br>Lite ||:--------:|------------|---------:|---------:|----:|---:|--:|| 1 | Aider with GPT-4o | 419 | 73.5% | 87 | 80.6% | 15.3% || 2 | Aider with Opus | 151 | 26.5% | 21 | 19.4% | 3.7% ||**Total**||**570**|**100%**|**108**|**100%**|**18.9%**|## Non-plausible but correct solutions?
A solution doesn't actually have to be plausible in order to correctly resolve the issue.
Recall that plausible is simply defined as aider
reporting that it successfully completed all file edits,
repaired and resolved any linting errors
and resolved any test failures.
But there are many reasons why aider might fail to do those things
and yet still produce a solution that will pass
acceptance testing:
- There may have been pre-existing failing tests in the repo,
before aider even started working on the SWE Bench problem.
Aider may not have resolved such issues, and yet they may not be
relevant to the acceptance testing.
The SWE Bench acceptance testing just confirms that tests pass or fail
in the same pattern as the "gold patch" developed by a human to resolve the
problem.
Some tests may fail during acceptance testing,
and that's ok as long as they failed for the gold
patch too.
- There may have been pre-existing linting problems in the repo.
If lingering linting issues affected code paths that are not well tested,
they may not impact acceptance testing.
- Aider may have reported file editing errors because it thought the LLM
specified edits that it wasn't able to successfully apply.
This can only happen when the LLM specified edits in
a way that doesn't comply with the editing instructions in the system prompt.
Given that the LLM isn't complying with the system prompt,
it may have become confused and
asked for redundant or otherwise irrelevant edits.
Such outstanding edit errors might not be fatal for acceptance testing.
- Etc.
Keeping all this in mind, we can understand why
GPT-4o accounts for 15.3% of the benchmark score in the table above,
but benchmarking with just one attempt of aider with GPT-4o scored 17.0%.
When an Opus attempt is allowed after GPT-4o,
it may propose some *incorrect* solutions which
are "more plausible" than some of GPT-4o's non-plausible solutions.
These more plausible, incorrect solutions can
eclipse some of
the earlier non-plausible correct solutions that GPT-4o generated.
This is why GPT-4o's score in the table
showing the combined GPT-4o & Opus results (15.3%)
is lower than the result from just one try using aider with GPT-4o (17.0%).
For these reasons, adding additional attempts is not guaranteed to monotonically
increase the number of resolved problems.
New solutions may resolve some new problems but they may also
eclipse and discard some of the previous non-plausible correct solutions.
Luckily, the net effect of additional attempts
usually increases or at least maintains the
number of resolved solutions.
This was the case for all the attempts made in both this main SWE Bench result and the
earlier Lite result.
## Computing the benchmark score
The benchmark harness produced one proposed solution for each of
the 570 SWE Bench problems.
A separate evaluation script was used to
test each of these solutions with the full test suite,
including the held out acceptance tests.
For this final acceptance testing, any edits that aider made to tests
were discarded.
This ensured that the correct,
unmodified test suite was used for acceptance testing.
The evaluation script compared each proposed solution's test results
with results from testing
the "gold" patch that was developed by a human to correctly resolve the issue.
If they matched, the proposed solution correctly resolved the issue.
These acceptance tests were only ever run outside of aider
and the benchmark harness, and only to compute statistics about the
correctly resolved instances.
They were never run, used, or even visible during aider's attempts to resolve the problems.
Aider correctly resolved 108 out of 570 SWE Bench instances that were benchmarked,
or 18.9%.
## Acknowledgments
Much thanks to the team behind the
[SWE Bench](https://www.swebench.com)
family of AI coding benchmarks.
Also thanks to Albert Örwall who has
[dockerized the SWE Bench evaluation scripts](https://github.com/aorwall/SWE-bench-docker)
making it faster, easier, and more reliable to run the acceptance tests.
## References
All of aider's results reported here are pass@1 results,
obtained without using the SWE Bench `hints_text`.
The "aider agent" internally makes multiple "attempts" at solving the problem,
but it picks and returns one single candidate solution.
Only that one candidate solution is evaluated with the acceptance tests
and contributes to the benchmark score.
Thus it is a pass@1 result.
This is contrast to a pass@N result for N>1, where N attempts are made
and all N solutions are evaluated by the acceptance tests.
If *any* of the N solution pass, that counts as a pass@N success.
Below are the references for the other pass@1 unhinted SWE-Bench results
displayed in the graph at the beginning of this article.
-[13.9% Devin, benchmarked on 570 instances.](https://www.cognition.ai/post/swe-bench-technical-report)-[13.8% Amazon Q Developer Agent, benchmarked on 2,294 instances.](https://www.swebench.com)-[12.5% SWE- Agent + GPT-4, benchmarked on 2,294 instances.](https://www.swebench.com)-[10.6% AutoCode Rover, benchmarked on 2,294 instances.](https://arxiv.org/pdf/2404.05427v2)-[10.5% SWE- Agent + Opus, benchmarked on 2,294 instances.](https://www.swebench.com)
The graph contains average pass@1 results for AutoCodeRover.
The [AutoCodeRover GitHub page](https://github.com/nus-apr/auto-code-rover)
features their pass@3 results
without being clearly labeled.
Table 2 of their
[paper](https://arxiv.org/pdf/2404.05427v2)
reports an `ACR-avg` result of 10.59% which is an average pass@1 result.
---title: Sonnet is the opposite of lazyexcerpt: Claude 3.5 Sonnet can easily write more good code than fits in one 4k token API response.highlight_image: /assets/sonnet-not-lazy.jpgnav_exclude: true---[](https://aider.chat/assets/sonnet-not-lazy.jpg)
{% if page.date %}
<pclass="post-date">{{ page.date | date: "%B %d, %Y" }}</p>
{% endif %}
# Sonnet is the opposite of lazy
Claude 3.5 Sonnet represents a step change
in AI coding.
It is incredibly industrious, diligent and hard working.
Unexpectedly,
this presented a challenge:
Sonnet
was often writing so much code that
it was hitting the 4k output token limit,
truncating its coding in mid-stream.
Aider now works
around this 4k limit and allows Sonnet to produce
as much code as it wants.
The result is surprisingly powerful.
Sonnet's score on
[aider's refactoring benchmark](https://aider.chat/docs/leaderboards/#code-refactoring-leaderboard)
jumped from 55.1% up to 64.0%.
This moved Sonnet into second place, ahead of GPT-4o and
behind only Opus.
Users who tested Sonnet with a preview of
[aider's latest release](https://aider.chat/HISTORY.html#aider-v0410)
were thrilled:
-*Works like a charm. It is a monster. It refactors files of any size like it is nothing. The continue trick with Sonnet is truly the holy grail. Aider beats [other tools] hands down. I'm going to cancel both subscriptions.* -- [Emasoft](https://github.com/paul-gauthier/aider/issues/705#issuecomment-2200338971)-*Thanks heaps for this feature - it's a real game changer. I can be more ambitious when asking Claude for larger features.* -- [cngarrison](https://github.com/paul-gauthier/aider/issues/705#issuecomment-2196026656)-*Fantastic...! It's such an improvement not being constrained by output token length issues. [I refactored] a single JavaScript file into seven smaller files using a single Aider request.* -- [John Galt](https://discord.com/channels/1131200896827654144/1253492379336441907/1256250487934554143)## Hitting the 4k token output limit
All LLMs have various token limits, the most familiar being their
context window size.
But they also have a limit on how many tokens they can output
in response to a single request.
Sonnet and the majority of other
models are limited to returning 4k tokens.
Sonnet's amazing work ethic caused it to
regularly hit this 4k output token
limit for a few reasons:
1. Sonnet is capable of outputting a very large amount of correct,
complete new code in one response.
2. Similarly, Sonnet can specify long sequences of edits in one go,
like changing a majority of lines while refactoring a large file.
3. Sonnet tends to quote large chunks of a
file when performing a SEARCH & REPLACE edits.
Beyond token limits, this is very wasteful.
## Good problems
Problems (1) and (2) are "good problems"
in the sense that Sonnet is
able to write more high quality code than any other model!
We just don't want it to be interrupted prematurely
by the 4k output limit.
Aider now allows Sonnet to return code in multiple 4k token
responses.
Aider seamlessly combines them so that Sonnet can return arbitrarily
long responses.
This gets all the upsides of Sonnet's prolific coding skills,
without being constrained by the 4k output token limit.
## Wasting tokens
Problem (3) is more complicated, as Sonnet isn't just
being stopped early -- it's actually wasting a lot
of tokens, time and money.
Faced with a few small changes spread far apart in
a source file,
Sonnet would often prefer to do one giant SEARCH/REPLACE
operation of almost the entire file.
It would be far faster and less expensive to instead
do a few surgical edits.
Aider now prompts Sonnet to discourage these long-winded
SEARCH/REPLACE operations
and promotes much more concise edits.
## Aider with Sonnet[The latest release of aider](https://aider.chat/HISTORY.html#aider-v0410)
has specialized support for Claude 3.5 Sonnet:
- Aider allows Sonnet to produce as much code as it wants,
by automatically and seamlessly spreading the response
out over a sequence of 4k token API responses.
- Aider carefully prompts Sonnet to be concise when proposing
code edits.
This reduces Sonnet's tendency to waste time, tokens and money
returning large chunks of unchanging code.
- Aider now uses Claude 3.5 Sonnet by default if the `ANTHROPIC_API_KEY` is set in the environment.
See
[aider's install instructions](https://aider.chat/docs/install.html)
for more details, but
you can get started quickly with aider and Sonnet like this:
---title: Coding with Llama 3.1, new DeepSeek Coder & Mistral Largeexcerpt: Summary of code editing skill for the new models, with Sonnet and GPT-3.5 for scale.highlight_image: /assets/2024-07-new-models.jpgnav_exclude: true---
{% if page.date %}
<pclass="post-date">{{ page.date | date: "%B %d, %Y" }}</p>
{% endif %}
# Coding with Llama 3.1, new DeepSeek Coder & Mistral Large
Five noteworthy models have been released in the last few days,
with a wide range of code editing capabilities.
Here are their results from
[aider's code editing leaderboard](https://aider.chat/docs/leaderboards/)
with Claude 3.5 Sonnet and the best GPT-3.5 model
included for scale.
-**77% claude-3.5-sonnet**- 73% DeepSeek Coder V2 0724
- 66% llama-3.1-405b-instruct
- 60% Mistral Large 2 (2407)
- 59% llama-3.1-70b-instruct
-**58% gpt-3.5-turbo-0301**- 38% llama-3.1-8b-instruct
You can code with all of these models using aider like this:
See the
[installation instructions](https://aider.chat/docs/install.html)
and other
[documentation](https://aider.chat/docs/usage.html)
for more details.
## DeepSeek Coder V2 0724
DeepSeek Coder V2 0724 was by far the biggest surprise
and strongest code editing model, coming in 2nd on the leaderboard.
It can
efficiently edit code with SEARCH/REPLACE, unlike
the prior DeepSeek Coder version.
This unlocks the ability to edit large files.
This new Coder version got 73% on the benchmark,
very
close to Sonnet's 77% but 20-50X less expensive!
## LLama 3.1
Meta released the
Llama 3.1 family of models,
which have performed well on many evals.
The flagship Llama 3.1 405B instruct only
secured #7 on aider's leaderboard,
well behind frontier models like
Claude 3.5 Sonnet & GPT-4o.
The 405B model can use SEARCH/REPLACE to efficiently
edit code, but with a decrease in the benchmark score.
When using this "diff" editing format, its score dropped
from 66% to 64%.
The smaller 70B model was competitive with GPT-3.5, while
the 8B model lags far behind.
Both seem unable to reliably use SEARCH/REPLACE to edit files.
This limits them to editing smaller files that can
fit into their output token limit.
## Mistral Large 2 (2407)
Mistral Large 2 (2407) scored only 60% on aider's code editing
benchmark.
This puts it just ahead of the best GPT-3.5 model.
It
doesn't seem able to reliably use SEARCH/REPLACE to efficiently edit
code,
which limits its use to small source files.
---title: The January GPT-4 Turbo is lazier than the last versionexcerpt: The new `gpt-4-0125-preview` model is quantiatively lazier at coding than previous GPT-4 versions, according to a new "laziness" benchmark.highlight_image: /assets/benchmarks-0125.jpgnav_exclude: true---
{% if page.date %}
<pclass="post-date">{{ page.date | date: "%B %d, %Y" }}</p>
{% endif %}
# The January GPT-4 Turbo is lazier than the last version[](https://aider.chat/assets/benchmarks-0125.svg)[OpenAI just released a new version of GPT-4 Turbo](https://openai.com/blog/new-embedding-models-and-api-updates).
This new model is intended to reduce the "laziness" that has been widely observed with the previous `gpt-4-1106-preview` model:
> Today, we are releasing an updated GPT-4 Turbo preview model, gpt-4-0125-preview. This model completes tasks like code generation more thoroughly than the previous preview model and is intended to reduce cases of “laziness” where the model doesn’t complete a task.
With that in mind, I've been benchmarking the new model using
aider's existing
[lazy coding benchmark](https://aider.chat/docs/unified-diffs.html).
## Benchmark results
Overall,
the new `gpt-4-0125-preview` model seems lazier
than the November `gpt-4-1106-preview` model:
- It gets worse benchmark scores when using the [unified diffs](https://aider.chat/docs/unified-diffs.html) code editing format.
- Using aider's older SEARCH/REPLACE block editing format, the new January model outperforms the older November model. But it still performs worse than both models using unified diffs.
## Related reports
This is one in a series of reports
that use the aider benchmarking suite to assess and compare the code
editing capabilities of OpenAI's GPT models.
You can review the other reports
for additional information:
-[GPT code editing benchmarks](https://aider.chat/docs/benchmarks.html) evaluates the March and June versions of GPT-3.5 and GPT-4.
-[Code editing benchmarks for OpenAI's "1106" models](https://aider.chat/docs/benchmarks-1106.html).
-[Aider's lazy coding benchmark](https://aider.chat/docs/unified-diffs.html).
---title: Code editing benchmarks for OpenAI's "1106" modelsexcerpt: A quantitative comparison of the code editing capabilities of the new GPT-3.5 and GPT-4 versions that were released in Nov 2023.highlight_image: /assets/benchmarks-1106.jpgnav_exclude: true---
{% if page.date %}
<pclass="post-date">{{ page.date | date: "%B %d, %Y" }}</p>
{% endif %}
# Code editing benchmarks for OpenAI's "1106" models[](https://aider.chat/assets/benchmarks-1106.svg)[](https://aider.chat/assets/benchmarks-speed-1106.svg)[OpenAI just released new versions of GPT-3.5 and GPT-4](https://openai.com/blog/new-models-and-developer-products-announced-at-devday),
and there's a lot
of interest about their ability to code compared to the previous versions.
With that in mind, I've been benchmarking the new models.
[Aider](https://github.com/paul-gauthier/aider)
is an open source command line chat tool that lets you work with GPT to edit
code in your local git repo.
To do this, aider needs to be able to reliably recognize when GPT wants to edit
your source code,
determine which files it wants to modify
and accurately apply the changes it's trying to make.
Doing a good job on this "code editing" task requires a good LLM, good prompting and
a good tool driving the interactions with the LLM.
Aider relies on a
[code editing benchmark](https://aider.chat/docs/benchmarks.html)
to quantitatively evaluate
performance
whenever one of these things changes.
For example,
whenever I change aider's prompting or the backend which drives LLM conversations,
I run the benchmark to make sure these changes produce improvements (not regressions).
The benchmark uses aider to try and complete
[133 Exercism Python coding exercises](https://github.com/exercism/python).
For each exercise, Exercism provides a starting python file with stubs for the needed functions,
a natural language description of the problem to solve
and a test suite to evaluate whether the coder has correctly solved the problem.
The benchmark gives aider two tries to complete the task:
1. On the first try, aider gives GPT the stub code file to edit and the natural language instructions that describe the problem. This reflects how you code with aider. You add your source code files to the chat and ask for changes, which are automatically applied.
2. If the test suite fails after the first try, aider gives GPT the test error output and asks it to fix the code. Aider supports this sort of interaction using a command like `/run pytest` to run and share pytest results in the chat with GPT. You can `/run` whatever tests/linters/etc make sense for your language/framework/situation.
## Benchmark results### gpt-4-1106-preview
For now, I have only benchmarked the GPT-4 models using the `diff` edit method.
This is the edit format that aider uses by default with gpt-4.
- The new `gpt-4-1106-preview` model seems **2-2.5X faster** than the June GPT-4 model.
-**It seems better at producing correct code on the first try**. It gets
53% of the coding exercises correct, without needing to see errors from the test suite. Previous models only get 46-47% of the exercises correct on the first try.
- The new model seems to perform similar
(~65%) to the old models (63-64%) after their second chance to correct bugs by reviewing test suite error output.
### gpt-3.5-turbo-1106
I benchmarked the GPT-3.5 models with both the `whole` and `diff` edit format.
None of the gpt-3.5 models seem able to effectively use the `diff` edit format, including the newest November (1106) model.
The comments below only focus on comparing the `whole` edit format results:
- The new `gpt-3.5-turbo-1106` model is completing the benchmark **3-4X faster** than the earlier GPT-3.5 models.
- The success rate after the first try of 42% is comparable to the previous June (0613) model. The new November and previous June models are both worse than the original March (0301) model's 50% result on the first try.
- The new model's 56% success rate after the second try seems comparable to the original March model, and somewhat better than the June model's 50% score.
## Related reports
This is one in a series of reports
that use the aider benchmarking suite to assess and compare the code
editing capabilities of OpenAI's GPT models.
You can review the other reports
for additional information:
-[GPT code editing benchmarks](https://aider.chat/docs/benchmarks.html) evaluates the March and June versions of GPT-3.5 and GPT-4.
-[Code editing speed benchmarks for OpenAI's "1106" models](https://aider.chat/2023/11/06/benchmarks-speed-1106.html) compares the performance of the new GPT models.
## Updates
Last updated 11/14/23.
OpenAI has relaxed rate limits so these results are no longer considered preliminary.
---title: Speed benchmarks of GPT-4 Turbo and gpt-3.5-turbo-1106excerpt: This report provides a detailed comparison of the speed of GPT-4 Turbo and gpt-3.5-turbo-1106 models based on the aider benchmarking suite.canonical_url: https://aider.chat/2023/11/06/benchmarks-speed-1106.htmlhighlight_image: /assets/benchmarks-speed-1106.jpgnav_exclude: true---
{% if page.date %}
<pclass="post-date">{{ page.date | date: "%B %d, %Y" }}</p>
{% endif %}
# Speed benchmarks of GPT-4 Turbo and gpt-3.5-turbo-1106
<pclass="post-date">{{ page.date | date: "%b %-d, %Y" }}</p>
[](https://aider.chat/assets/benchmarks-speed-1106.svg)[OpenAI just released new versions of GPT-3.5 and GPT-4](https://openai.com/blog/new-models-and-developer-products-announced-at-devday),
and there's a lot
of interest about their capabilities and performance.
With that in mind, I've been benchmarking the new models.
[Aider](https://github.com/paul-gauthier/aider)
is an open source command line chat tool that lets you work with GPT to edit
code in your local git repo.
Aider relies on a
[code editing benchmark](https://aider.chat/docs/benchmarks.html)
to quantitatively evaluate
performance.
This is the latest in a series of reports
that use the aider benchmarking suite to assess and compare the code
editing capabilities of OpenAI's GPT models. You can review previous
reports to get more background on aider's benchmark suite:
-[GPT code editing benchmarks](https://aider.chat/docs/benchmarks.html) evaluates the March and June versions of GPT-3.5 and GPT-4.
-[Code editing skill benchmarks for OpenAI's "1106" models](https://aider.chat/docs/benchmarks-1106.html) compares the olders models to the November (1106) models.
## Speed
This report compares the **speed** of the various GPT models.
Aider's benchmark measures the response time of the OpenAI chat completion
endpoint each time it asks GPT to solve a programming exercise in the benchmark
suite. These results measure only the time spent waiting for OpenAI to
respond to the prompt.
So they are measuring
how fast these models can
generate responses which primarily consist of source code.
Some observations:
-**GPT-3.5 got 6-11x faster.** The `gpt-3.5-turbo-1106` model is 6-11x faster than the June (0613) version which has been the default `gpt-3.5-turbo` model.
-**GPT-4 Turbo is 2-2.5x faster.** The new `gpt-4-1106-preview` model is 2-2.5x faster than the June (0613) version which has been the default `gpt-4` model.
- The old March (0301) version of GPT-3.5 is actually faster than the June (0613) version. This was a surprising discovery.
## Updates
Last updated 11/14/23.
OpenAI has relaxed rate limits so these results are no longer considered preliminary.
---title: GPT code editing benchmarksexcerpt: Benchmarking GPT-3.5 and GPT-4 code editing skill using a new code editing benchmark suite based on the Exercism python exercises.highlight_image: /assets/benchmarks.jpgnav_exclude: true---
{% if page.date %}
<pclass="post-date">{{ page.date | date: "%B %d, %Y" }}</p>
{% endif %}
# GPT code editing benchmarks[](https://aider.chat/assets/benchmarks.svg)
Aider is an open source command line chat tool that lets you work with GPT to edit
code in your local git repo.
To do this, aider needs to be able to reliably recognize when GPT wants to edit local files,
determine which files it wants to modify and what changes to save.
Such automated
code editing hinges on using the system prompt
to tell GPT how to structure code edits in its responses.
Aider currently asks GPT to use simple text based "edit formats", but
[OpenAI's new function calling
API](https://openai.com/blog/function-calling-and-other-api-updates)
looks like a promising way to create more structured edit formats.
After implementing a couple of function based edit formats,
I wanted
to measure the potential benefits
of switching aider to use them by default.
With this in mind, I developed a
benchmark based on the [Exercism
python](https://github.com/exercism/python) coding exercises.
This
benchmark evaluates how effectively aider and GPT can translate a
natural language coding request into executable code saved into
files that pass unit tests.
It provides an end-to-end evaluation of not just
GPT's coding ability, but also its capacity to *edit existing code*
and *format those code edits* so that aider can save the
edits to the local source files.
I ran the benchmark
on all the ChatGPT models (except `gpt-4-32k`), using a variety of edit formats.
The results were interesting:
-**Plain text edit formats worked best.** Asking GPT to return an updated copy of the whole file in a standard markdown fenced code block proved to be the most reliable and effective edit format across all GPT-3.5 and GPT-4 models. The results for this `whole` edit format are shown in solid blue in the graph.
-**Function calls performed worse.** Using the new functions API for edits performed worse than the above whole file method, for all the models. GPT-3.5 especially produced inferior code and frequently mangled this output format. This was surprising, as the functions API was introduced to enhance the reliability of structured outputs. The results for these `...-func` edit methods are shown as patterned bars in the graph (both green and blue).
-**The new June GPT-3.5 models did a bit worse than the old June model.** The performance of the new June (`0613`) versions of GPT-3.5 appears to be a bit worse than the February (`0301`) version. This is visible if you look at the "first attempt" markers on the first three solid blue bars and also by comparing the first three solid green `diff` bars.
-**GPT-4 does better than GPT-3.5,** as expected.
The quantitative benchmark results agree with my intuitions
about prompting GPT for complex tasks like coding. It's beneficial to
minimize the "cognitive overhead" of formatting the response, allowing
GPT to concentrate on the coding task at hand.
As a thought experiment, imagine a slack conversation with a junior developer where
you ask them to write the code to add some new feature to your app.
They're going to type the response back to you by hand in the chat.
Should they type out the
code and wrap it in a normal markdown code block?
Or should they type up a properly escaped and
syntactically correct json data structure
that contains the text of the new code?
Using more complex output formats with GPT seems to cause two issues:
- It makes GPT write worse code. Keeping the output format simple seems to allow GPT to devote more attention to the actual coding task.
- It reduces GPT's adherence to the output format, making it more challenging for tools like aider to accurately identify and apply the edits GPT is attempting to make.
I was expecting to start using function call based edits in aider for both GPT-3.5 and GPT-4.
But given these benchmark results, I won't be adopting the functions API
at this time.
I will certainly plan to benchmark functions again with future versions of the models.
More details on the benchmark, edit formats and results are discussed below.
## The benchmark
The benchmark uses
[133 practice exercises from the Exercism python repository](https://github.com/exercism/python/tree/main/exercises/practice).
These
exercises were designed to help individuals learn Python and hone
their coding skills.
Each exercise includes:
-[Instructions](https://github.com/exercism/python/blob/main/exercises/practice/anagram/.docs/instructions.md), provided in markdown files.
-[Stub python code](https://github.com/exercism/python/blob/main/exercises/practice/anagram/anagram.py) in an *implementation file*, specifying the functions or classes that need to be implemented.
-[Unit tests](https://github.com/exercism/python/blob/main/exercises/practice/anagram/anagram_test.py) in a separate python file.
The goal is for GPT to read the instructions, implement the provided function/class skeletons
and pass all the unit tests. The benchmark measures what percentage of
the 133 exercises are completed successfully, causing all the associated unit tests to pass.
To start each exercise, aider sends GPT
the initial contents of the implementation file,
the Exercism instructions
and a final instruction:
Use the above instructions to modify the supplied files:
Keep and implement the existing function or class stubs, they will be called from unit tests.
Only use standard python libraries, don't suggest installing any packages.
Aider updates the implementation file based on GPT's reply and runs
the unit tests. If all tests pass, the exercise is considered
complete. If some tests fail, aider sends GPT a second message with
the test error output. It only sends the first 50 lines of test errors
to try and avoid exceeding the context window of the smaller models. Aider
also includes this final instruction:
See the testing errors above.
The tests are correct.
Fix the code in to resolve the errors.
Requiring GPT to fix its first implementation in response to test failures
is another way in which this benchmark stresses code editing skill.
This second chance is also important because it
gives GPT the opportunity to adjust if the
instructions were imprecise with respect to the
specific requirements of the unit tests.
Many of the exercises have multiple paragraphs of instructions,
and most human coders would likely fail some tests on their
first try.
The bars in the graph show the percent of exercises that were completed by
each model and edit format combination. The full bar height represents
the final outcome following both coding attempts.
Each bar also has a horizontal mark that shows
the intermediate performance after the first coding attempt,
without the benefit of the second try that includes the test error output.
It's worth noting that GPT never gets to see the source code of the
unit tests during the benchmark. It only sees the error output from
failed tests. Of course, all of this code was probably part of its
original training data!
In summary, passing an exercise means GPT was able to:
- Write the required code (possibly after reviewing test error output),
- Correctly package all of the code edits into the edit format so that aider can process and save it to the implementation file.
Conversely, failing an exercise only requires a breakdown in one of
those steps. In practice, GPT fails at different steps in different
exercises. Sometimes it simply writes the wrong code. Other times, it
fails to format the code edits in a way that conforms to the edit
format, resulting in the code not being saved correctly.
It's worth keeping in mind that changing the edit format often affects
both aspects of GPT's performance.
Complex edit formats often lead GPT to write worse code *and* make it less
successful at formatting the edits correctly.
## Edit formats
I benchmarked 4 different edit formats, described below.
Each description includes a sample response that GPT might provide to a user who
requests:
"Change the print from hello to goodbye."
### whole
The
[whole](https://github.com/paul-gauthier/aider/blob/main/aider/coders/wholefile_prompts.py)
format asks GPT to return an updated copy of the entire file, including any changes.
The file should be
formatted with normal markdown triple-backtick fences, inlined with the rest of its response text.
This format is very similar to how ChatGPT returns code snippets during normal chats, except with the addition of a filename right before the opening triple-backticks.
Here is the updated copy of your file demo.py:
demo.py
defmain():
print("goodbye")
### diff
The [diff](https://github.com/paul-gauthier/aider/blob/main/aider/coders/editblock_prompts.py)
format also asks GPT to return edits as part of the normal response text,
in a simple diff format.
Each edit is a fenced code block that
specifies the filename and a chunk of ORIGINAL and UPDATED code.
GPT provides some original lines from the file and then a new updated set of lines.
### whole-func
The [whole-func](https://github.com/paul-gauthier/aider/blob/main/aider/coders/wholefile_func_coder.py)
format requests updated copies of whole files to be returned using the function call API.
```
{
"explanation": "Changed hello to goodbye.",
"files": [
{
"path": "demo.py",
"content": "def main():\n print(\"goodbye\")\n"
}
}
```
### diff-func
The
[diff-func](https://github.com/paul-gauthier/aider/blob/main/aider/coders/editblock_func_coder.py)
format requests a list of
original/updated style edits to be returned using the function call API.
```
{
"explanation": "Changed hello to goodbye.",
"edits": [
{
"path": "demo.py",
"original_lines": [
" print(\"hello\")"
],
"updated_lines": [
" print(\"goodbye\")"
],
}
]
}
```
## GPT-3.5's performance
### The `0613` models seem worse?
The GPT-3.5 benchmark results have me fairly convinced that the new
`gpt-3.5-turbo-0613` and `gpt-3.5-16k-0613` models
are a bit worse at code editing than
the older `gpt-3.5-turbo-0301` model.
This is visible in the "first attempt"
portion of each result, before GPT gets a second chance to edit the code.
Look at the horizontal white line in the middle of the first three blue bars.
Performance with the `whole` edit format was 46% for the
February model and only 39% for the June models.
But also note how much the solid green `diff` bars
degrade between the February and June GPT-3.5 models.
They drop from 30% down to about 19%.
I saw other signs of this degraded performance
in earlier versions of the
benchmark as well.
### Pathological use of `diff`
When GPT-3.5 is able to correctly generate the `diff` edit format,
it often uses it in a pathological manner. It places the *entire*
original source file in the ORIGINAL block and the entire updated file
in the UPDATED block. This is strictly worse than just using the
`whole` edit format, as GPT is sending two full copies of the file.
### Hallucinated function calls
When GPT-3.5 uses the functions API
it is prone to ignoring the JSON Schema that specifies valid functions.
It often returns a completely novel and semantically
invalid `function_call` fragment with `"name": "python"`.
The `arguments` attribute is supposed to be a set of key/value pairs
with the arguments to the function specified in the `name` field.
Instead, GPT-3.5 frequently just stuffs an entire python
file into that field.
```
"function_call": {
"name": "python",
"arguments": "def main():\n print(\"hello\")\n"
},
```
It seems like it might be getting confused by fine-tuning that was
done for the ChatGPT code interpreter plugin?
## Randomness
The benchmark attempts to be deterministic, always sending identical
requests for each exercise on repeated runs.
As part of this effort,
when sending test error output to GPT,
it removes the wall-clock timing information that
is normally included by the `unittest` module.
The benchmark harness also logs SHA hashes of
all the OpenAI API requests and replies.
This makes it possible to
detect randomness or nondeterminism
in the benchmarking process.
It turns out that the OpenAI chat APIs are not deterministic, even at
`temperature=0`. The same identical request will produce multiple
distinct responses, usually less than 5-10 variations. This suggests
that OpenAI may be load balancing their API across a number of
slightly different instances of the model?
For certain exercises, some of these variable responses pass the unit tests while
other variants do not. Results for exercises like this, which are
"on the bubble",
are therefore a bit random, depending on which variant OpenAI returns.
Given that, it would be ideal to run all 133 exercises many times for each
model/edit-format combination and report an average performance.
This would average away the effect of the API variance.
It would also significantly increase the cost of this sort of benchmarking.
So I didn't do that.
Benchmarking against 133 exercises already provides some robustness, since
we are measuring the performance across many exercises.
But to get a sense of how much the API variance impacts the benchmark outcomes,
I ran all 133 exercises 10 times each
against `gpt-3.5-turbo-0613` with the `whole` edit format.
You'll see one set of error bars in the graph, which show
the range of results from those 10 runs.
The OpenAI API randomness doesn't seem to
cause a large variance in the overall benchmark results.
## Conclusions
Based on these benchmark results, aider will continue to use
the `whole` edit format for GPT-3.5, and `diff` for GPT-4.
GPT-4 gets comparable results with the `whole` and `diff` edit formats,
but using `whole` significantly increases costs and latency compared to `diff`.
The latency of streaming back the entire updated copy of each edited file
is a real challenge with the `whole` format.
The GPT-3.5 models are quite responsive, and can
stream back entire files at reasonable speed.
Aider displays a progress bar and
live diffs of the files as they stream in,
which helps pass the time.
The GPT-4 models are much slower, and waiting for even small files
to be completely "retyped" on each request is probably unacceptable.
```
paul-gauthier/aider/blob/main/aider/website/docs/config.md:
```md
---
nav_order: 55
has_children: true
description: Information on all of aider's settings and how to use them.
---
# Configuration
Aider has many options which can be set with
command line switches.
Most options can also be set in an `.aider.conf.yml` file
which can be placed in your home directory or at the root of
your git repo.
Or by setting environment variables like `AIDER_xxx`
either in your shell or a `.env` file.
Here are 4 equivalent ways of setting an option.
With a command line switch:
```
$ aider --dark-mode
```
Using a `.aider.conf.yml` file:
```yaml
dark-mode: true
```
By setting an environgment variable:
```
export AIDER_DARK_MODE=true
```
Using an `.env` file:
```
AIDER_DARK_MODE=true
```
{% include env-keys-tip.md %}
```
paul-gauthier/aider/blob/main/aider/website/docs/config/adv-model-settings.md:
```md
---
parent: Configuration
nav_order: 950
description: Configuring advanced settings for LLMs.
---
# Advanced model settings
## Context window size and token costs
In most cases, you can safely ignore aider's warning about unknown context
window size and model costs.
But, you can register context window limits and costs for models that aren't known
to aider. Create a `.aider.model.metadata.json` file in one of these locations:
- Your home directory.
- The root if your git repo.
- The current directory where you launch aider.
- Or specify a specific file with the `--model-metadata-file <filename>` switch.
If the files above exist, they will be loaded in that order.
Files loaded last will take priority.
The json file should be a dictionary with an entry for each model, as follows:
```
{
"deepseek-chat": {
"max_tokens": 4096,
"max_input_tokens": 32000,
"max_output_tokens": 4096,
"input_cost_per_token": 0.00000014,
"output_cost_per_token": 0.00000028,
"litellm_provider": "deepseek",
"mode": "chat"
}
}
```
See
[litellm's model_prices_and_context_window.json file](https://github.com/BerriAI/litellm/blob/main/model_prices_and_context_window.json) for more examples.
## Model settings
Aider has a number of settings that control how it works with
different models.
These model settings are pre-configured for most popular models.
But it can sometimes be helpful to override them or add settings for
a model that aider doesn't know about.
To do that,
create a `.aider.model.settings.yml` file in one of these locations:
- Your home directory.
- The root if your git repo.
- The current directory where you launch aider.
- Or specify a specific file with the `--model-settings-file <filename>` switch.
If the files above exist, they will be loaded in that order.
Files loaded last will take priority.
The yaml file should be a a list of dictionary objects for each model, as follows:
```
- name: "gpt-3.5-turbo"
edit_format: "whole"
weak_model_name: "gpt-3.5-turbo"
use_repo_map: false
send_undo_reply: false
accepts_images: false
lazy: false
reminder_as_sys_msg: true
examples_as_sys_msg: false
- name: "gpt-4-turbo-2024-04-09"
edit_format: "udiff"
weak_model_name: "gpt-3.5-turbo"
use_repo_map: true
send_undo_reply: true
accepts_images: true
lazy: true
reminder_as_sys_msg: true
examples_as_sys_msg: false
```
```
paul-gauthier/aider/blob/main/aider/website/docs/config/aider_conf.md:
```md
---
parent: Configuration
nav_order: 15
description: How to configure aider with a yaml config file.
---
# YAML config file
Most of aider's options can be set in an `.aider.conf.yml` file.
Aider will look for a this file in these locations and
load whichever is found first.
- As specified with the `--config <filename>` parameter.
- The current directory.
- The root of your git repo.
- Your home directory.
## Storing LLM keys
{% include special-keys.md %}
{% include env-keys-tip.md %}
## Sample YAML config file
Below is a sample of the YAML config file, which you
can also
[download from GitHub](https://github.com/paul-gauthier/aider/blob/main/aider/website/assets/sample.aider.conf.yml).
<!--[[[cog
from aider.args import get_sample_yaml
from pathlib import Path
text=get_sample_yaml()
Path("aider/website/assets/sample.aider.conf.yml").write_text(text)
cog.outl("```")
cog.out(text)
cog.outl("```")
]]]-->
```
##########################################################
# Sample .aider.conf.yml
# This file lists *all* the valid configuration entries.
# Place in your home dir, or at the root of your git repo.
##########################################################
# Note: You can only put OpenAI and Anthropic API keys in the yaml
# config file. Keys for all APIs can be stored in a .env file
# https://aider.chat/docs/config/dotenv.html
##########
# options:
## show this help message and exit
#help:
#######
# Main:
## Specify the OpenAI API key
#openai-api-key:
## Specify the Anthropic API key
#anthropic-api-key:
## Specify the model to use for the main chat
#model:
## Use claude-3-opus-20240229 model for the main chat
#opus: false
## Use claude-3-5-sonnet-20240620 model for the main chat
#sonnet: false
## Use gpt-4-0613 model for the main chat
#4: false
## Use gpt-4o model for the main chat
#4o: false
## Use gpt-4o-mini model for the main chat
#mini: false
## Use gpt-4-1106-preview model for the main chat
#4-turbo: false
## Use gpt-3.5-turbo model for the main chat
#35turbo: false
## Use deepseek/deepseek-coder model for the main chat
#deepseek: false
#################
# Model Settings:
## List known models which match the (partial) MODEL name
#models:
## Specify the api base url
#openai-api-base:
## Specify the api_type
#openai-api-type:
## Specify the api_version
#openai-api-version:
## Specify the deployment_id
#openai-api-deployment-id:
## Specify the OpenAI organization ID
#openai-organization-id:
## Specify a file with aider model settings for unknown models
#model-settings-file: .aider.model.settings.yml
## Specify a file with context window and costs for unknown models
#model-metadata-file: .aider.model.metadata.json
## Verify the SSL cert when connecting to models (default: True)
#verify-ssl: true
## Specify what edit format the LLM should use (default depends on model)
#edit-format:
## Specify the model to use for commit messages and chat history summarization (default depends on --model)
#weak-model:
## Only work with models that have meta-data available (default: True)
#show-model-warnings: true
## Max number of tokens to use for repo map, use 0 to disable (default: 1024)
#map-tokens:
## Maximum number of tokens to use for chat history. If not specified, uses the model's max_chat_history_tokens.
#max-chat-history-tokens:
## Specify the .env file to load (default: .env in git root)
#env-file: .env
################
# History Files:
## Specify the chat input history file (default: .aider.input.history)
#input-history-file: .aider.input.history
## Specify the chat history file (default: .aider.chat.history.md)
#chat-history-file: .aider.chat.history.md
## Restore the previous chat history messages (default: False)
#restore-chat-history: false
## Log the conversation with the LLM to this file (for example, .aider.llm.history)
#llm-history-file:
##################
# Output Settings:
## Use colors suitable for a dark terminal background (default: False)
#dark-mode: false
## Use colors suitable for a light terminal background (default: False)
#light-mode: false
## Enable/disable pretty, colorized output (default: True)
#pretty: true
## Enable/disable streaming responses (default: True)
#stream: true
## Set the color for user input (default: #00cc00)
#user-input-color: #00cc00
## Set the color for tool output (default: None)
#tool-output-color:
## Set the color for tool error messages (default: red)
#tool-error-color: #FF2222
## Set the color for assistant output (default: #0088ff)
#assistant-output-color: #0088ff
## Set the markdown code theme (default: default, other options include monokai, solarized-dark, solarized-light)
#code-theme: default
## Show diffs when committing changes (default: False)
#show-diffs: false
###############
# Git Settings:
## Enable/disable looking for a git repo (default: True)
#git: true
## Enable/disable adding .aider* to .gitignore (default: True)
#gitignore: true
## Specify the aider ignore file (default: .aiderignore in git root)
#aiderignore: .aiderignore
## Only consider files in the current subtree of the git repository
#subtree-only: false
## Enable/disable auto commit of LLM changes (default: True)
#auto-commits: true
## Enable/disable commits when repo is found dirty (default: True)
#dirty-commits: true
## Attribute aider code changes in the git author name (default: True)
#attribute-author: true
## Attribute aider commits in the git committer name (default: True)
#attribute-committer: true
## Prefix commit messages with 'aider: ' if aider authored the changes (default: False)
#attribute-commit-message-author: false
## Prefix all commit messages with 'aider: ' (default: False)
#attribute-commit-message-committer: false
## Commit all pending changes with a suitable commit message, then exit
#commit: false
## Specify a custom prompt for generating commit messages
#commit-prompt:
## Perform a dry run without modifying files (default: False)
#dry-run: false
########################
# Fixing and committing:
## Lint and fix provided files, or dirty files if none provided
#lint: false
## Specify lint commands to run for different languages, eg: "python: flake8 --select=..." (can be used multiple times)
#lint-cmd:
## Enable/disable automatic linting after changes (default: True)
#auto-lint: true
## Specify command to run tests
#test-cmd:
## Enable/disable automatic testing after changes (default: False)
#auto-test: false
## Run tests and fix problems found
#test: false
#################
# Other Settings:
## specify a file to edit (can be used multiple times)
#file:
## specify a read-only file (can be used multiple times)
#read:
## Use VI editing mode in the terminal (default: False)
#vim: false
## Specify the language for voice using ISO 639-1 code (default: auto)
#voice-language: en
## Show the version number and exit
#version:
## Check for updates and return status in the exit code
#just-check-update: false
## Check for new aider versions on launch
#check-update: true
## Apply the changes from the given file instead of running the chat (debug)
#apply:
## Always say yes to every confirmation
#yes: false
## Enable verbose output
#verbose: false
## Print the repo map and exit (debug)
#show-repo-map: false
## Print the system prompts and exit (debug)
#show-prompts: false
## Do all startup activities then exit before accepting user input (debug)
#exit: false
## Specify a single message to send the LLM, process reply then exit (disables chat mode)
#message:
## Specify a file containing the message to send the LLM, process reply, then exit (disables chat mode)
#message-file:
## Specify the encoding for input and output (default: utf-8)
#encoding: utf-8
## Specify the config file (default: search for .aider.conf.yml in git root, cwd or home directory)
#config:
## Run aider in your browser
#gui: false
```
<!--[[[end]]]-->
```
paul-gauthier/aider/blob/main/aider/website/docs/config/dotenv.md:
```md
---
parent: Configuration
nav_order: 900
description: Using a .env file to store LLM API keys for aider.
---
# Config with .env
You can use a `.env` file to store API keys and other settings for the
models you use with aider.
You can also set many general aider options
in the `.env` file.
Aider will look for a `.env` file in these locations:
- Your home directory.
- The root of your git repo.
- The current directory.
- As specified with the `--env-file <filename>` parameter.
If the files above exist, they will be loaded in that order. Files loaded last will take priority.
## Storing LLM keys
{% include special-keys.md %}
## Sample .env file
Below is a sample `.env` file, which you
can also
[download from GitHub](https://github.com/paul-gauthier/aider/blob/main/aider/website/assets/sample.env).
<!--[[[cog
from aider.args import get_sample_dotenv
from pathlib import Path
text=get_sample_dotenv()
Path("aider/website/assets/sample.env").write_text(text)
cog.outl("```")
cog.out(text)
cog.outl("```")
]]]-->
```
##########################################################
# Sample aider .env file.
# Place at the root of your git repo.
# Or use `aider --env <fname>` to specify.
##########################################################
#################
# LLM parameters:
#
# Include xxx_API_KEY parameters and other params needed for your LLMs.
# See https://aider.chat/docs/llms.html for details.
## OpenAI
#OPENAI_API_KEY=
## Anthropic
#ANTHROPIC_API_KEY=
##...
#######
# Main:
## Specify the OpenAI API key
#OPENAI_API_KEY=
## Specify the Anthropic API key
#ANTHROPIC_API_KEY=
## Specify the model to use for the main chat
#AIDER_MODEL=
## Use claude-3-opus-20240229 model for the main chat
#AIDER_OPUS=
## Use claude-3-5-sonnet-20240620 model for the main chat
#AIDER_SONNET=
## Use gpt-4-0613 model for the main chat
#AIDER_4=
## Use gpt-4o model for the main chat
#AIDER_4O=
## Use gpt-4o-mini model for the main chat
#AIDER_MINI=
## Use gpt-4-1106-preview model for the main chat
#AIDER_4_TURBO=
## Use gpt-3.5-turbo model for the main chat
#AIDER_35TURBO=
## Use deepseek/deepseek-coder model for the main chat
#AIDER_DEEPSEEK=
#################
# Model Settings:
## List known models which match the (partial) MODEL name
#AIDER_MODELS=
## Specify the api base url
#OPENAI_API_BASE=
## Specify the api_type
#OPENAI_API_TYPE=
## Specify the api_version
#OPENAI_API_VERSION=
## Specify the deployment_id
#OPENAI_API_DEPLOYMENT_ID=
## Specify the OpenAI organization ID
#OPENAI_ORGANIZATION_ID=
## Specify a file with aider model settings for unknown models
#AIDER_MODEL_SETTINGS_FILE=.aider.model.settings.yml
## Specify a file with context window and costs for unknown models
#AIDER_MODEL_METADATA_FILE=.aider.model.metadata.json
## Verify the SSL cert when connecting to models (default: True)
#AIDER_VERIFY_SSL=true
## Specify what edit format the LLM should use (default depends on model)
#AIDER_EDIT_FORMAT=
## Specify the model to use for commit messages and chat history summarization (default depends on --model)
#AIDER_WEAK_MODEL=
## Only work with models that have meta-data available (default: True)
#AIDER_SHOW_MODEL_WARNINGS=true
## Max number of tokens to use for repo map, use 0 to disable (default: 1024)
#AIDER_MAP_TOKENS=
## Maximum number of tokens to use for chat history. If not specified, uses the model's max_chat_history_tokens.
#AIDER_MAX_CHAT_HISTORY_TOKENS=
## Specify the .env file to load (default: .env in git root)
#AIDER_ENV_FILE=.env
################
# History Files:
## Specify the chat input history file (default: .aider.input.history)
#AIDER_INPUT_HISTORY_FILE=.aider.input.history
## Specify the chat history file (default: .aider.chat.history.md)
#AIDER_CHAT_HISTORY_FILE=.aider.chat.history.md
## Restore the previous chat history messages (default: False)
#AIDER_RESTORE_CHAT_HISTORY=false
## Log the conversation with the LLM to this file (for example, .aider.llm.history)
#AIDER_LLM_HISTORY_FILE=
##################
# Output Settings:
## Use colors suitable for a dark terminal background (default: False)
#AIDER_DARK_MODE=false
## Use colors suitable for a light terminal background (default: False)
#AIDER_LIGHT_MODE=false
## Enable/disable pretty, colorized output (default: True)
#AIDER_PRETTY=true
## Enable/disable streaming responses (default: True)
#AIDER_STREAM=true
## Set the color for user input (default: #00cc00)
#AIDER_USER_INPUT_COLOR=#00cc00
## Set the color for tool output (default: None)
#AIDER_TOOL_OUTPUT_COLOR=
## Set the color for tool error messages (default: red)
#AIDER_TOOL_ERROR_COLOR=#FF2222
## Set the color for assistant output (default: #0088ff)
#AIDER_ASSISTANT_OUTPUT_COLOR=#0088ff
## Set the markdown code theme (default: default, other options include monokai, solarized-dark, solarized-light)
#AIDER_CODE_THEME=default
## Show diffs when committing changes (default: False)
#AIDER_SHOW_DIFFS=false
###############
# Git Settings:
## Enable/disable looking for a git repo (default: True)
#AIDER_GIT=true
## Enable/disable adding .aider* to .gitignore (default: True)
#AIDER_GITIGNORE=true
## Specify the aider ignore file (default: .aiderignore in git root)
#AIDER_AIDERIGNORE=.aiderignore
## Only consider files in the current subtree of the git repository
#AIDER_SUBTREE_ONLY=false
## Enable/disable auto commit of LLM changes (default: True)
#AIDER_AUTO_COMMITS=true
## Enable/disable commits when repo is found dirty (default: True)
#AIDER_DIRTY_COMMITS=true
## Attribute aider code changes in the git author name (default: True)
#AIDER_ATTRIBUTE_AUTHOR=true
## Attribute aider commits in the git committer name (default: True)
#AIDER_ATTRIBUTE_COMMITTER=true
## Prefix commit messages with 'aider: ' if aider authored the changes (default: False)
#AIDER_ATTRIBUTE_COMMIT_MESSAGE_AUTHOR=false
## Prefix all commit messages with 'aider: ' (default: False)
#AIDER_ATTRIBUTE_COMMIT_MESSAGE_COMMITTER=false
## Commit all pending changes with a suitable commit message, then exit
#AIDER_COMMIT=false
## Specify a custom prompt for generating commit messages
#AIDER_COMMIT_PROMPT=
## Perform a dry run without modifying files (default: False)
#AIDER_DRY_RUN=false
########################
# Fixing and committing:
## Lint and fix provided files, or dirty files if none provided
#AIDER_LINT=false
## Specify lint commands to run for different languages, eg: "python: flake8 --select=..." (can be used multiple times)
#AIDER_LINT_CMD=
## Enable/disable automatic linting after changes (default: True)
#AIDER_AUTO_LINT=true
## Specify command to run tests
#AIDER_TEST_CMD=
## Enable/disable automatic testing after changes (default: False)
#AIDER_AUTO_TEST=false
## Run tests and fix problems found
#AIDER_TEST=false
#################
# Other Settings:
## specify a file to edit (can be used multiple times)
#AIDER_FILE=
## specify a read-only file (can be used multiple times)
#AIDER_READ=
## Use VI editing mode in the terminal (default: False)
#AIDER_VIM=false
## Specify the language for voice using ISO 639-1 code (default: auto)
#AIDER_VOICE_LANGUAGE=en
## Check for updates and return status in the exit code
#AIDER_JUST_CHECK_UPDATE=false
## Check for new aider versions on launch
#AIDER_CHECK_UPDATE=true
## Apply the changes from the given file instead of running the chat (debug)
#AIDER_APPLY=
## Always say yes to every confirmation
#AIDER_YES=
## Enable verbose output
#AIDER_VERBOSE=false
## Print the repo map and exit (debug)
#AIDER_SHOW_REPO_MAP=false
## Print the system prompts and exit (debug)
#AIDER_SHOW_PROMPTS=false
## Do all startup activities then exit before accepting user input (debug)
#AIDER_EXIT=false
## Specify a single message to send the LLM, process reply then exit (disables chat mode)
#AIDER_MESSAGE=
## Specify a file containing the message to send the LLM, process reply, then exit (disables chat mode)
#AIDER_MESSAGE_FILE=
## Specify the encoding for input and output (default: utf-8)
#AIDER_ENCODING=utf-8
## Run aider in your browser
#AIDER_GUI=false
```
<!--[[[end]]]-->
```
paul-gauthier/aider/blob/main/aider/website/docs/config/options.md:
```md
---
parent: Configuration
nav_order: 10
description: Details about all of aider's settings.
---
# Options reference
{: .no_toc }
You can use `aider --help` to see all the available options,
or review them below.
- TOC
{:toc}
## LLM keys
{: .no_toc }
{% include special-keys.md %}
## Usage summary
<!--[[[cog
from aider.args import get_md_help
cog.out(get_md_help())
]]]-->
```
usage: aider [-h] [--openai-api-key] [--anthropic-api-key] [--model]
[--opus] [--sonnet] [--4] [--4o] [--mini] [--4-turbo]
[--35turbo] [--deepseek] [--models] [--openai-api-base]
[--openai-api-type] [--openai-api-version]
[--openai-api-deployment-id] [--openai-organization-id]
[--model-settings-file] [--model-metadata-file]
[--verify-ssl | --no-verify-ssl] [--edit-format]
[--weak-model]
[--show-model-warnings | --no-show-model-warnings]
[--map-tokens] [--max-chat-history-tokens] [--env-file]
[--input-history-file] [--chat-history-file]
[--restore-chat-history | --no-restore-chat-history]
[--llm-history-file] [--dark-mode] [--light-mode]
[--pretty | --no-pretty] [--stream | --no-stream]
[--user-input-color] [--tool-output-color]
[--tool-error-color] [--assistant-output-color]
[--code-theme] [--show-diffs] [--git | --no-git]
[--gitignore | --no-gitignore] [--aiderignore]
[--subtree-only] [--auto-commits | --no-auto-commits]
[--dirty-commits | --no-dirty-commits]
[--attribute-author | --no-attribute-author]
[--attribute-committer | --no-attribute-committer]
[--attribute-commit-message-author | --no-attribute-commit-message-author]
[--attribute-commit-message-committer | --no-attribute-commit-message-committer]
[--commit] [--commit-prompt] [--dry-run | --no-dry-run]
[--lint] [--lint-cmd] [--auto-lint | --no-auto-lint]
[--test-cmd] [--auto-test | --no-auto-test] [--test]
[--file] [--read] [--vim] [--voice-language]
[--version] [--just-check-update]
[--check-update | --no-check-update] [--apply] [--yes]
[-v] [--show-repo-map] [--show-prompts] [--exit]
[--message] [--message-file] [--encoding] [-c] [--gui]
```
## options:
### `--help`
show this help message and exit
Aliases:
- `-h`
- `--help`
## Main:
### `--openai-api-key OPENAI_API_KEY`
Specify the OpenAI API key
Environment variable: `OPENAI_API_KEY`
### `--anthropic-api-key ANTHROPIC_API_KEY`
Specify the Anthropic API key
Environment variable: `ANTHROPIC_API_KEY`
### `--model MODEL`
Specify the model to use for the main chat
Environment variable: `AIDER_MODEL`
### `--opus`
Use claude-3-opus-20240229 model for the main chat
Environment variable: `AIDER_OPUS`
### `--sonnet`
Use claude-3-5-sonnet-20240620 model for the main chat
Environment variable: `AIDER_SONNET`
### `--4`
Use gpt-4-0613 model for the main chat
Environment variable: `AIDER_4`
Aliases:
- `--4`
- `-4`
### `--4o`
Use gpt-4o model for the main chat
Environment variable: `AIDER_4O`
### `--mini`
Use gpt-4o-mini model for the main chat
Environment variable: `AIDER_MINI`
### `--4-turbo`
Use gpt-4-1106-preview model for the main chat
Environment variable: `AIDER_4_TURBO`
### `--35turbo`
Use gpt-3.5-turbo model for the main chat
Environment variable: `AIDER_35TURBO`
Aliases:
- `--35turbo`
- `--35-turbo`
- `--3`
- `-3`
### `--deepseek`
Use deepseek/deepseek-coder model for the main chat
Environment variable: `AIDER_DEEPSEEK`
## Model Settings:
### `--models MODEL`
List known models which match the (partial) MODEL name
Environment variable: `AIDER_MODELS`
### `--openai-api-base OPENAI_API_BASE`
Specify the api base url
Environment variable: `OPENAI_API_BASE`
### `--openai-api-type OPENAI_API_TYPE`
Specify the api_type
Environment variable: `OPENAI_API_TYPE`
### `--openai-api-version OPENAI_API_VERSION`
Specify the api_version
Environment variable: `OPENAI_API_VERSION`
### `--openai-api-deployment-id OPENAI_API_DEPLOYMENT_ID`
Specify the deployment_id
Environment variable: `OPENAI_API_DEPLOYMENT_ID`
### `--openai-organization-id OPENAI_ORGANIZATION_ID`
Specify the OpenAI organization ID
Environment variable: `OPENAI_ORGANIZATION_ID`
### `--model-settings-file MODEL_SETTINGS_FILE`
Specify a file with aider model settings for unknown models
Default: .aider.model.settings.yml
Environment variable: `AIDER_MODEL_SETTINGS_FILE`
### `--model-metadata-file MODEL_METADATA_FILE`
Specify a file with context window and costs for unknown models
Default: .aider.model.metadata.json
Environment variable: `AIDER_MODEL_METADATA_FILE`
### `--verify-ssl`
Verify the SSL cert when connecting to models (default: True)
Default: True
Environment variable: `AIDER_VERIFY_SSL`
Aliases:
- `--verify-ssl`
- `--no-verify-ssl`
### `--edit-format EDIT_FORMAT`
Specify what edit format the LLM should use (default depends on model)
Environment variable: `AIDER_EDIT_FORMAT`
Aliases:
- `--edit-format EDIT_FORMAT`
- `--chat-mode EDIT_FORMAT`
### `--weak-model WEAK_MODEL`
Specify the model to use for commit messages and chat history summarization (default depends on --model)
Environment variable: `AIDER_WEAK_MODEL`
### `--show-model-warnings`
Only work with models that have meta-data available (default: True)
Default: True
Environment variable: `AIDER_SHOW_MODEL_WARNINGS`
Aliases:
- `--show-model-warnings`
- `--no-show-model-warnings`
### `--map-tokens VALUE`
Max number of tokens to use for repo map, use 0 to disable (default: 1024)
Environment variable: `AIDER_MAP_TOKENS`
### `--max-chat-history-tokens VALUE`
Maximum number of tokens to use for chat history. If not specified, uses the model's max_chat_history_tokens.
Environment variable: `AIDER_MAX_CHAT_HISTORY_TOKENS`
### `--env-file ENV_FILE`
Specify the .env file to load (default: .env in git root)
Default: .env
Environment variable: `AIDER_ENV_FILE`
## History Files:
### `--input-history-file INPUT_HISTORY_FILE`
Specify the chat input history file (default: .aider.input.history)
Default: .aider.input.history
Environment variable: `AIDER_INPUT_HISTORY_FILE`
### `--chat-history-file CHAT_HISTORY_FILE`
Specify the chat history file (default: .aider.chat.history.md)
Default: .aider.chat.history.md
Environment variable: `AIDER_CHAT_HISTORY_FILE`
### `--restore-chat-history`
Restore the previous chat history messages (default: False)
Default: False
Environment variable: `AIDER_RESTORE_CHAT_HISTORY`
Aliases:
- `--restore-chat-history`
- `--no-restore-chat-history`
### `--llm-history-file LLM_HISTORY_FILE`
Log the conversation with the LLM to this file (for example, .aider.llm.history)
Environment variable: `AIDER_LLM_HISTORY_FILE`
## Output Settings:
### `--dark-mode`
Use colors suitable for a dark terminal background (default: False)
Default: False
Environment variable: `AIDER_DARK_MODE`
### `--light-mode`
Use colors suitable for a light terminal background (default: False)
Default: False
Environment variable: `AIDER_LIGHT_MODE`
### `--pretty`
Enable/disable pretty, colorized output (default: True)
Default: True
Environment variable: `AIDER_PRETTY`
Aliases:
- `--pretty`
- `--no-pretty`
### `--stream`
Enable/disable streaming responses (default: True)
Default: True
Environment variable: `AIDER_STREAM`
Aliases:
- `--stream`
- `--no-stream`
### `--user-input-color VALUE`
Set the color for user input (default: #00cc00)
Default: #00cc00
Environment variable: `AIDER_USER_INPUT_COLOR`
### `--tool-output-color VALUE`
Set the color for tool output (default: None)
Environment variable: `AIDER_TOOL_OUTPUT_COLOR`
### `--tool-error-color VALUE`
Set the color for tool error messages (default: red)
Default: #FF2222
Environment variable: `AIDER_TOOL_ERROR_COLOR`
### `--assistant-output-color VALUE`
Set the color for assistant output (default: #0088ff)
Default: #0088ff
Environment variable: `AIDER_ASSISTANT_OUTPUT_COLOR`
### `--code-theme VALUE`
Set the markdown code theme (default: default, other options include monokai, solarized-dark, solarized-light)
Default: default
Environment variable: `AIDER_CODE_THEME`
### `--show-diffs`
Show diffs when committing changes (default: False)
Default: False
Environment variable: `AIDER_SHOW_DIFFS`
## Git Settings:
### `--git`
Enable/disable looking for a git repo (default: True)
Default: True
Environment variable: `AIDER_GIT`
Aliases:
- `--git`
- `--no-git`
### `--gitignore`
Enable/disable adding .aider* to .gitignore (default: True)
Default: True
Environment variable: `AIDER_GITIGNORE`
Aliases:
- `--gitignore`
- `--no-gitignore`
### `--aiderignore AIDERIGNORE`
Specify the aider ignore file (default: .aiderignore in git root)
Default: .aiderignore
Environment variable: `AIDER_AIDERIGNORE`
### `--subtree-only`
Only consider files in the current subtree of the git repository
Default: False
Environment variable: `AIDER_SUBTREE_ONLY`
### `--auto-commits`
Enable/disable auto commit of LLM changes (default: True)
Default: True
Environment variable: `AIDER_AUTO_COMMITS`
Aliases:
- `--auto-commits`
- `--no-auto-commits`
### `--dirty-commits`
Enable/disable commits when repo is found dirty (default: True)
Default: True
Environment variable: `AIDER_DIRTY_COMMITS`
Aliases:
- `--dirty-commits`
- `--no-dirty-commits`
### `--attribute-author`
Attribute aider code changes in the git author name (default: True)
Default: True
Environment variable: `AIDER_ATTRIBUTE_AUTHOR`
Aliases:
- `--attribute-author`
- `--no-attribute-author`
### `--attribute-committer`
Attribute aider commits in the git committer name (default: True)
Default: True
Environment variable: `AIDER_ATTRIBUTE_COMMITTER`
Aliases:
- `--attribute-committer`
- `--no-attribute-committer`
### `--attribute-commit-message-author`
Prefix commit messages with 'aider: ' if aider authored the changes (default: False)
Default: False
Environment variable: `AIDER_ATTRIBUTE_COMMIT_MESSAGE_AUTHOR`
Aliases:
- `--attribute-commit-message-author`
- `--no-attribute-commit-message-author`
### `--attribute-commit-message-committer`
Prefix all commit messages with 'aider: ' (default: False)
Default: False
Environment variable: `AIDER_ATTRIBUTE_COMMIT_MESSAGE_COMMITTER`
Aliases:
- `--attribute-commit-message-committer`
- `--no-attribute-commit-message-committer`
### `--commit`
Commit all pending changes with a suitable commit message, then exit
Default: False
Environment variable: `AIDER_COMMIT`
### `--commit-prompt PROMPT`
Specify a custom prompt for generating commit messages
Environment variable: `AIDER_COMMIT_PROMPT`
### `--dry-run`
Perform a dry run without modifying files (default: False)
Default: False
Environment variable: `AIDER_DRY_RUN`
Aliases:
- `--dry-run`
- `--no-dry-run`
## Fixing and committing:
### `--lint`
Lint and fix provided files, or dirty files if none provided
Default: False
Environment variable: `AIDER_LINT`
### `--lint-cmd`
Specify lint commands to run for different languages, eg: "python: flake8 --select=..." (can be used multiple times)
Default: []
Environment variable: `AIDER_LINT_CMD`
### `--auto-lint`
Enable/disable automatic linting after changes (default: True)
Default: True
Environment variable: `AIDER_AUTO_LINT`
Aliases:
- `--auto-lint`
- `--no-auto-lint`
### `--test-cmd VALUE`
Specify command to run tests
Default: []
Environment variable: `AIDER_TEST_CMD`
### `--auto-test`
Enable/disable automatic testing after changes (default: False)
Default: False
Environment variable: `AIDER_AUTO_TEST`
Aliases:
- `--auto-test`
- `--no-auto-test`
### `--test`
Run tests and fix problems found
Default: False
Environment variable: `AIDER_TEST`
## Other Settings:
### `--file FILE`
specify a file to edit (can be used multiple times)
Environment variable: `AIDER_FILE`
### `--read FILE`
specify a read-only file (can be used multiple times)
Environment variable: `AIDER_READ`
### `--vim`
Use VI editing mode in the terminal (default: False)
Default: False
Environment variable: `AIDER_VIM`
### `--voice-language VOICE_LANGUAGE`
Specify the language for voice using ISO 639-1 code (default: auto)
Default: en
Environment variable: `AIDER_VOICE_LANGUAGE`
### `--version`
Show the version number and exit
### `--just-check-update`
Check for updates and return status in the exit code
Default: False
Environment variable: `AIDER_JUST_CHECK_UPDATE`
### `--check-update`
Check for new aider versions on launch
Default: True
Environment variable: `AIDER_CHECK_UPDATE`
Aliases:
- `--check-update`
- `--no-check-update`
### `--apply FILE`
Apply the changes from the given file instead of running the chat (debug)
Environment variable: `AIDER_APPLY`
### `--yes`
Always say yes to every confirmation
Environment variable: `AIDER_YES`
### `--verbose`
Enable verbose output
Default: False
Environment variable: `AIDER_VERBOSE`
Aliases:
- `-v`
- `--verbose`
### `--show-repo-map`
Print the repo map and exit (debug)
Default: False
Environment variable: `AIDER_SHOW_REPO_MAP`
### `--show-prompts`
Print the system prompts and exit (debug)
Default: False
Environment variable: `AIDER_SHOW_PROMPTS`
### `--exit`
Do all startup activities then exit before accepting user input (debug)
Default: False
Environment variable: `AIDER_EXIT`
### `--message COMMAND`
Specify a single message to send the LLM, process reply then exit (disables chat mode)
Environment variable: `AIDER_MESSAGE`
Aliases:
- `--message COMMAND`
- `--msg COMMAND`
- `-m COMMAND`
### `--message-file MESSAGE_FILE`
Specify a file containing the message to send the LLM, process reply, then exit (disables chat mode)
Environment variable: `AIDER_MESSAGE_FILE`
Aliases:
- `--message-file MESSAGE_FILE`
- `-f MESSAGE_FILE`
### `--encoding VALUE`
Specify the encoding for input and output (default: utf-8)
Default: utf-8
Environment variable: `AIDER_ENCODING`
### `--config CONFIG_FILE`
Specify the config file (default: search for .aider.conf.yml in git root, cwd or home directory)
Aliases:
- `-c CONFIG_FILE`
- `--config CONFIG_FILE`
### `--gui`
Run aider in your browser
Default: False
Environment variable: `AIDER_GUI`
Aliases:
- `--gui`
- `--browser`
<!--[[[end]]]-->
```
paul-gauthier/aider/blob/main/aider/website/docs/ctags.md:
```md
---
title: Improving GPT-4's codebase understanding with ctags
excerpt: Using ctags to build a "repository map" to increase GPT-4's ability to understand a large code base.
highlight_image: /assets/robot-flowchart.png
nav_exclude: true
---
{% if page.date %}
<p class="post-date">{{ page.date | date: "%B %d, %Y" }}</p>
{% endif %}
# Improving GPT-4's codebase understanding with ctags

## Updated
Aider no longer uses ctags to build a repo map.
Please see the newer article about
[using tree-sitter to build a better repo map](https://aider.chat/docs/repomap.html).
-------
GPT-4 is extremely useful for "self-contained" coding tasks,
like generating brand new code or modifying a pure function
that has no dependencies.
But it's difficult to use GPT-4 to modify or extend
a large, complex pre-existing codebase.
To modify such code, GPT needs to understand the dependencies and APIs
which interconnect its subsystems.
Somehow we need to provide this "code context" to GPT
when we ask it to accomplish a coding task. Specifically, we need to:
- Help GPT understand the overall codebase, so that it
can decifer the meaning of code with complex dependencies and generate
new code that respects and utilizes existing abstractions.
- Convey all of this "code context" to GPT in an
efficient manner that fits within the 8k-token context window.
To address these issues, `aider` now
sends GPT a **concise map of your whole git repository**
that includes
all declared variables and functions with call signatures.
This *repo map* is built automatically using `ctags`, which
extracts symbol definitions from source files. Historically,
ctags were generated and indexed by IDEs and editors to
help humans search and navigate large codebases.
Instead, we're going to use ctags to help GPT better comprehend, navigate
and edit code in larger repos.
To get a sense of how effective this can be, this
[chat transcript](https://aider.chat/examples/add-test.html)
shows GPT-4 creating a black box test case, **without being given
access to the source code of the function being tested or any of the
other code in the repo.**
Using only the meta-data in the repo map, GPT is able to figure out how to
call the method to be tested, as well as how to instantiate multiple
class objects that are required to prepare for the test.
To code with GPT-4 using the techniques discussed here:
- Install [aider](https://aider.chat/docs/install.html).
- Install universal ctags.
- Run `aider` inside your repo, and it should say "Repo-map: universal-ctags using 1024 tokens".
## The problem: code context
GPT-4 is great at "self contained" coding tasks, like writing or
modifying a pure function with no external dependencies.
GPT can easily handle requests like "write a
Fibonacci function" or "rewrite the loop using list
comprehensions", because they require no context beyond the code
being discussed.
Most real code is not pure and self-contained, it is intertwined with
and depends on code from many different files in a repo.
If you ask GPT to "switch all the print statements in class Foo to
use the BarLog logging system", it needs to see the code in the Foo class
with the prints, and it also needs to understand the project's BarLog
subsystem.
A simple solution is to **send the entire codebase** to GPT along with
each change request. Now GPT has all the context! But this won't work
for even moderately
sized repos, because they won't fit into the 8k-token context window.
A better approach is to be selective,
and **hand pick which files to send**.
For the example above, you could send the file that
contains the Foo class
and the file that contains the BarLog logging subsystem.
This works pretty well, and is supported by `aider` -- you
can manually specify which files to "add to the chat" you are having with GPT.
But it's not ideal to have to manually identify the right
set of files to add to the chat.
And sending whole files is a bulky way to send code context,
wasting the precious 8k context window.
GPT doesn't need to see the entire implementation of BarLog,
it just needs to understand it well enough to use it.
You may quickly run out of context window if you
send many files worth of code just to convey context.
## Using a repo map to provide context
The latest version of `aider` sends a **repo map** to GPT along with
each change request. The map contains a list of all the files in the
repo, along with the symbols which are defined in each file. Callables
like functions and methods also include their signatures.
Here's a
sample of the map of the aider repo, just showing the maps of
[main.py](https://github.com/paul-gauthier/aider/blob/main/aider/main.py)
and
[io.py](https://github.com/paul-gauthier/aider/blob/main/aider/io.py)
:
```
aider/
...
main.py:
function
main (args=None, input=None, output=None)
variable
status
...
io.py:
class
FileContentCompleter
InputOutput
FileContentCompleter
member
__init__ (self, fnames, commands)
get_completions (self, document, complete_event)
InputOutput
member
__init__ (self, pretty, yes, input_history_file=None, chat_history_file=None, input=None, output=None)
ai_output (self, content)
append_chat_history (self, text, linebreak=False, blockquote=False)
confirm_ask (self, question, default="y")
get_input (self, fnames, commands)
prompt_ask (self, question, default=None)
tool (self, *messages, log_only=False)
tool_error (self, message)
...
```
Mapping out the repo like this provides some benefits:
- GPT can see variables, classes, methods and function signatures from everywhere in the repo. This alone may give it enough context to solve many tasks. For example, it can probably figure out how to use the API exported from a module just based on the details shown in the map.
- If it needs to see more code, GPT can use the map to figure out by itself which files it needs to look at. GPT will then ask to see these specific files, and `aider` will automatically add them to the chat context (with user approval).
Of course, for large repositories even just the map might be too large
for the context window. However, this mapping approach opens up the
ability to collaborate with GPT-4 on larger codebases than previous
methods. It also reduces the need to manually curate which files to
add to the chat context, empowering GPT to autonomously identify
relevant files for the task at hand.
## Using ctags to make the map
Under the hood, `aider` uses
[universal ctags](https://github.com/universal-ctags/ctags)
to build the
map. Universal ctags can scan source code written in many
languages, and extract data about all the symbols defined in each
file.
Historically, ctags were generated and indexed by IDEs or code editors
to make it easier for a human to search and navigate a
codebase, find the implementation of functions, etc.
Instead, we're going to use ctags to help GPT navigate and understand the codebase.
Here is the type of output you get when you run ctags on source code. Specifically,
this is the
`ctags --fields=+S --output-format=json` output for the `main.py` file mapped above:
```json
{
"_type": "tag",
"name": "main",
"path": "aider/main.py",
"pattern": "/^def main(args=None, input=None, output=None):$/",
"kind": "function",
"signature": "(args=None, input=None, output=None)"
}
{
"_type": "tag",
"name": "status",
"path": "aider/main.py",
"pattern": "/^ status = main()$/",
"kind": "variable"
}
```
The repo map is built using this type of `ctags` data,
but formatted into the space
efficient hierarchical tree format shown earlier.
This is a format that GPT can easily understand
and which conveys the map data using a
minimal number of tokens.
## Example chat transcript
This
[chat transcript](https://aider.chat/examples/add-test.html)
shows GPT-4 creating a black box test case, **without being given
access to the source code of the function being tested or any of the
other code in the repo.** Instead, GPT is operating solely off
the repo map.
Using only the meta-data in the map, GPT is able to figure out how to call the method to be tested, as well as how to instantiate multiple class objects that are required to prepare for the test.
GPT makes one reasonable mistake writing the first version of the test, but is
able to quickly fix the issue after being shown the `pytest` error output.
## Future work
Just as "send the whole codebase to GPT with every request"
is not an efficient solution to this problem,
there are probably better approaches than
"send the whole repo map with every request".
Sending an appropriate subset of the repo map would help `aider` work
better with even larger repositories which have large maps.
Some possible approaches to reducing the amount of map data are:
- Distill the global map, to prioritize important symbols and discard "internal" or otherwise less globally relevant identifiers. Possibly enlist `gpt-3.5-turbo` to perform this distillation in a flexible and language agnostic way.
- Provide a mechanism for GPT to start with a distilled subset of the global map, and let it ask to see more detail about subtrees or keywords that it feels are relevant to the current coding task.
- Attempt to analyize the natural language coding task given by the user and predict which subset of the repo map is relevant. Possibly by analysis of prior coding chats within the specific repo. Work on certain files or types of features may require certain somewhat predictable context from elsewhere in the repo. Vector and keyword search against the chat history, repo map or codebase may help here.
One key goal is to prefer solutions which are language agnostic or
which can be easily deployed against most popular code languages.
The `ctags` solution has this benefit, since it comes pre-built
with support for most popular languages.
I suspect that Language Server Protocol might be an even
better tool than `ctags` for this problem.
But it is more cumbersome to deploy for a broad
array of languages.
Users would need to stand up an LSP server for their
specific language(s) of interest.
## Try it out
To use this experimental repo map feature:
- Install [aider](https://aider.chat/docs/install.html).
- Install ctags.
- Run `aider` inside your repo, and it should say "Repo-map: universal-ctags using 1024 tokens".
```
paul-gauthier/aider/blob/main/aider/website/docs/faq.md:
```md
---
nav_order: 90
description: Frequently asked questions about aider.
---
# FAQ
{: .no_toc }
- TOC
{:toc}
{% include help-tip.md %}
## How can I add ALL the files to the chat?
People regularly ask about how to add **many or all of their repo's files** to the chat.
This is probably not a good idea and will likely do more harm than good.
The best approach is think about which files need to be changed to accomplish
the task you are working on. Just add those files to the chat.
Usually when people want to add "all the files" it's because they think it
will give the LLM helpful context about the overall code base.
Aider will automatically give the LLM a bunch of additional context about
the rest of your git repo.
It does this by analyzing your entire codebase in light of the
current chat to build a compact
[repository map](https://aider.chat/2023/10/22/repomap.html).
Adding a bunch of files that are mostly irrelevant to the
task at hand will often distract or confuse the LLM.
The LLM will give worse coding results, and sometimese even fail to correctly edit files.
Addings extra files will also increase the token costs on your OpenAI invoice.
Again, it's usually best to just add the files to the chat that will need to be modified.
If you still wish to add lots of files to the chat, you can:
- Use a wildcard when you launch aider: `aider src/*.py`
- Use a wildcard with the in-chat `/add` command: `/add src/*.py`
- Give the `/add` command a directory name and it will recurisvely add every file under that dir: `/add src`
## Can I use aider in a large (mono) repo?
Aider will work in any size repo, but is not optimized for quick
performance and response time in very large repos.
There are some things you can do to improve performance.
Change into a sub directory of your repo that contains the
code you want to work on and use the `--subtree-only` switch.
This will tell aider to ignore the repo outside of the
directory you start in.
You can also create a `.aiderignore` file to tell aider
to ignore parts of the repo that aren't relevant to your task.
This file conforms to `.gitignore` syntax and conventions.
You can use `--aiderignore <filename>` to name a specific file
to use for ignore patterns.
You might have a few of these handy for when you want to work on
frontend, backend, etc portions of your repo.
## How can I run aider locally from source code?
To run the project locally, follow these steps:
```
# Clone the repository:
git clone [email protected]:paul-gauthier/aider.git
# Navigate to the project directory:
cd aider
# It's recommended to make a virtual environment
# Install the dependencies listed in the `requirements.txt` file:
python -m pip install -e .
# Run the local version of Aider:
python -m aider
```
## Can I change the system prompts that aider uses?
Aider is set up to support different system prompts and edit formats
in a modular way. If you look in the `aider/coders` subdirectory, you'll
see there's a base coder with base prompts, and then there are
a number of
different specific coder implementations.
If you're thinking about experimenting with system prompts
this document about
[benchmarking GPT-3.5 and GPT-4 on code editing](https://aider.chat/docs/benchmarks.html)
might be useful background.
While it's not well documented how to add new coder subsystems, you may be able
to modify an existing implementation or use it as a template to add another.
To get started, try looking at and modifying these files.
The wholefile coder is currently used by GPT-3.5 by default. You can manually select it with `--edit-format whole`.
- wholefile_coder.py
- wholefile_prompts.py
The editblock coder is currently used by GPT-4o by default. You can manually select it with `--edit-format diff`.
- editblock_coder.py
- editblock_prompts.py
The universal diff coder is currently used by GPT-4 Turbo by default. You can manually select it with `--edit-format udiff`.
- udiff_coder.py
- udiff_prompts.py
When experimenting with coder backends, it helps to run aider with `--verbose --no-pretty` so you can see
all the raw information being sent to/from the LLM in the conversation.
You can also refer to the
[instructions for installing a development version of aider](https://aider.chat/docs/install/optional.html#install-the-development-version-of-aider).
```
paul-gauthier/aider/blob/main/aider/website/docs/git.md:
```md
---
parent: More info
nav_order: 800
description: Aider is tightly integrated with git.
---
# Git integration
Aider works best with code that is part of a git repo.
Aider is tightly integrated with git, which makes it easy to:
- Use the `/undo` command to instantly undo any AI changes that you don't like.
- Go back in the git history to review the changes that aider made to your code
- Manage a series of aider's changes on a git branch
Aider uses git in these ways:
- It asks to create a git repo if you launch it in a directory without one.
- Whenever aider edits a file, it commits those changes with a descriptive commit message. This makes it easy to undo or review aider's changes.
- Aider takes special care before editing files that already have uncommitted changes (dirty files). Aider will first commit any preexisting changes with a descriptive commit message.
This keeps your edits separate from aider's edits, and makes sure you never lose your work if aider makes an inappropriate change.
## In-chat commands
Aider also allows you to use in-chat commands to `/diff` or `/undo` the last change.
To do more complex management of your git history, you cat use raw `git` commands,
either by using `/git` within the chat, or with standard git tools outside of aider.
## Disabling git integration
While it is not recommended, you can disable aider's use of git in a few ways:
- `--no-auto-commits` will stop aider from git committing each of its changes.
- `--no-dirty-commits` will stop aider from committing dirty files before applying its edits.
- `--no-git` will completely stop aider from using git on your files. You should ensure you are keeping sensible backups of the files you are working with.
## Commit messages
By default, aider creates commit messages which follow
[Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/).
You can customize the
[commit prompt](https://github.com/paul-gauthier/aider/blob/main/aider/prompts.py#L5)
with the `--commit-prompt` option.
You can place that on the command line, or
[configure it via a config file or environment variables](https://aider.chat/docs/config.html).
## Commit attribution
Aider marks commits that it either authored or committed.
- If aider authored the changes in a commit, they will have "(aider)" appended to the git author and git committer name metadata.
- If aider simply committed changes (found in dirty files), the commit will have "(aider)" appended to the git committer name metadata.
You can use `--no-attribute-author` and `--no-attribute-committer` to disable
modification of the git author and committer name fields.
Additionally, you can use the following options to prefix commit messages:
- `--attribute-commit-message-author`: Prefix commit messages with 'aider: ' if aider authored the changes.
- `--attribute-commit-message-committer`: Prefix all commit messages with 'aider: ', regardless of whether aider authored the changes or not.
Both of these options are disabled by default, but can be useful for easily identifying changes made by aider.
```
paul-gauthier/aider/blob/main/aider/website/docs/install.md:
```md
---
title: Installation
has_children: true
nav_order: 20
description: How to install and get started pair programming with aider.
---
# Quick start
{% include get-started.md %}
Or see the
[full installation instructions](/docs/install/install.html)
for more details,
or the
[usage instructions](https://aider.chat/docs/usage.html) to start coding with aider.
{% include python-m-aider.md %}
<div class="video-container">
<video controls poster="/assets/install.jpg">
<source src="/assets/install.mp4" type="video/mp4">
<a href="/assets/install.mp4">Installing aider</a>
</video>
</div>
<style>
.video-container {
position: relative;
padding-bottom: 76.2711864407%;
height: 0;
overflow: hidden;
}
.video-container video {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
</style>
```
paul-gauthier/aider/blob/main/aider/website/docs/install/codespaces.md:
```md
---
title: GitHub Codespaces
parent: Installation
nav_order: 900
---
# GitHub Codespaces
You can use aider in GitHub Codespaces via the built-in Terminal pane.
See below for an example,
but you can see the
[main install instructions](/docs/install.html)
for all the details.
<div class="video-container">
<video controls poster="/assets/codespaces.jpg">
<source src="/assets/codespaces.mp4" type="video/mp4">
<a href="/assets/codespaces.mp4">Install aider in GitHub Codespaces</a>
</video>
</div>
<style>
.video-container {
position: relative;
padding-bottom: 101.89%; /* 1080 / 1060 = 1.0189 */
height: 0;
overflow: hidden;
}
.video-container video {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
</style>
```
paul-gauthier/aider/blob/main/aider/website/docs/install/docker.md:
```md
---
parent: Installation
nav_order: 100
---
# Aider with docker
Aider is available as 2 docker images:
- `paulgauthier/aider` installs the aider core, a smaller image that's good to get started quickly.
- `paulgauthier/aider-full` installs aider will all the optional extras.
The full image has support for features like interactive help, the
browser GUI and support for using Playwright to scrape web pages. The
core image can still use these features, but they will need to be
installed the first time you access them. Since containers are
ephemeral, the extras will need to be reinstalled the next time you
launch the aider core container.
### Aider core
```
docker pull paulgauthier/aider
docker run -it --user $(id -u):$(id -g) --volume $(pwd):/app paulgauthier/aider --openai-api-key $OPENAI_API_KEY [...other aider args...]
```
### Full version
```
docker pull paulgauthier/aider-full
docker run -it --user $(id -u):$(id -g) --volume $(pwd):/app paulgauthier/aider-full --openai-api-key $OPENAI_API_KEY [...other aider args...]
```
## How to use it
You should run the above commands from the root of your git repo,
since the `--volume` arg maps your current directory into the
docker container.
Given that, you need to be in the root of your git repo for aider to be able to
see the repo and all its files.
You should be sure your that
git repo config contains your user name and email, since the
docker container won't have your global git config.
Run these commands while in your git repo, before
you do the `docker run` command:
```
git config user.email "[email protected]"
git config user.name "Your Name"
```
## Limitations
- When you use the in-chat `/run` command, it will be running shell commands *inside the docker container*. So those commands won't be running in your local environment, which may make it tricky to `/run` tests, etc for your project.
- The `/voice` command won't work unless you can figure out how to give the docker container access to your host audio device. The container has libportaudio2 installed, so it should work if you can do that.
```
paul-gauthier/aider/blob/main/aider/website/docs/install/install.md:
```md
---
parent: Installation
nav_order: 10
---
# Installing aider
{: .no_toc }
- TOC
{:toc}
## Install git
Make sure you have git installed.
Here are
[instructions for installing git in various environments](https://github.com/git-guides/install-git).
## Get your API key
To work with OpenAI's models like GPT-4o or GPT-3.5 you need a paid
[OpenAI API key](https://help.openai.com/en/articles/4936850-where-do-i-find-my-secret-api-key).
Note that this is different than being a "ChatGPT Plus" subscriber.
To work with Anthropic's models like Claude 3.5 Sonnet you need a paid
[Anthropic API key](https://docs.anthropic.com/claude/reference/getting-started-with-the-api).
{% include venv-pipx.md %}
## Mac/Linux install
```
# Install aider
python -m pip install aider-chat
# To work with GPT-4o:
$ aider --4o --openai-api-key sk-xxx...
# To work with Claude 3.5 Sonnet:
$ aider --sonnet --anthropic-api-key sk-xxx...
```
## Windows install
```
# Install aider
python -m pip install aider-chat
# To work with GPT-4o:
$ aider --4o --openai-api-key sk-xxx...
# To work with Claude 3.5 Sonnet:
$ aider --sonnet --anthropic-api-key sk-xxx...
```
{% include python-m-aider.md %}
## Working with other LLMs
{% include works-best.md %}
## You are done!
There are some [optional install steps](/docs/install/optional.html) you could consider.
See the [usage instructions](https://aider.chat/docs/usage.html) to start coding with aider.
```
paul-gauthier/aider/blob/main/aider/website/docs/install/optional.md:
```md
---
parent: Installation
nav_order: 20
---
# Optional steps
{: .no_toc }
The steps below are completely optional.
- TOC
{:toc}
## Store your api keys
You can [store your api keys in a .env file](/docs/config/dotenv.html)
and they will be loaded automatically whenever you run aider.
## Enable Playwright
Aider supports adding web pages to the chat with the `/web <url>` command.
When you add a url to the chat, aider fetches the page and scrapes its
content.
By default, aider uses the `httpx` library to scrape web pages, but this only
works on a subset of web pages.
Some sites explicitly block requests from tools like httpx.
Others rely heavily on javascript to render the page content,
which isn't possible using only httpx.
Aider works best with all web pages if you install
Playwright's chromium browser and its dependencies:
```
playwright install --with-deps chromium
```
See the
[Playwright for Python documentation](https://playwright.dev/python/docs/browsers#install-system-dependencies)
for additional information.
## Enable voice coding
Aider supports
[coding with your voice](https://aider.chat/docs/usage/voice.html)
using the in-chat `/voice` command.
Aider uses the [PortAudio](http://www.portaudio.com) library to
capture audio.
Installing PortAudio is completely optional, but can usually be accomplished like this:
- For Windows, there is no need to install PortAudio.
- For Mac, do `brew install portaudio`
- For Linux, do `sudo apt-get install libportaudio2`
## Add aider to your editor
Other projects have integrated aider into some IDE/editors.
It's not clear if they are tracking the latest
versions of aider,
so it may be best to just run the latest
aider in a terminal alongside your editor.
### NeoVim
[joshuavial](https://github.com/joshuavial) provided a NeoVim plugin for aider:
[https://github.com/joshuavial/aider.nvim](https://github.com/joshuavial/aider.nvim)
### VS Code
joshuavial also confirmed that aider works inside a VS Code terminal window.
Aider detects if it is running inside VSCode and turns off pretty/color output,
since the VSCode terminal doesn't seem to support it well.
[MattFlower](https://github.com/MattFlower) provided a VSCode plugin for aider:
[https://marketplace.visualstudio.com/items?itemName=MattFlower.aider](https://marketplace.visualstudio.com/items?itemName=MattFlower.aider)
### Other editors
If you are interested in creating an aider plugin for your favorite editor,
please let me know by opening a
[GitHub issue](https://github.com/paul-gauthier/aider/issues).
## Install the development version of aider
If you want the very latest development version of aider
you can install directly from GitHub:
```
python -m pip install --upgrade git+https://github.com/paul-gauthier/aider.git
```
If you've git cloned the aider repository already, you can install "live" from your local copy. This is mostly useful if you are developing aider and want your current modifications to take effect immediately.
```
python -m pip install -e .
```
```
paul-gauthier/aider/blob/main/aider/website/docs/install/pipx.md:
```md
---
parent: Installation
nav_order: 100
---
# Install with pipx
If you are using aider to work on a python project, sometimes your project will require
specific versions of python packages which conflict with the versions that aider
requires.
If this happens, the `python -m pip install` command may return errors like these:
```
aider-chat 0.23.0 requires somepackage==X.Y.Z, but you have somepackage U.W.V which is incompatible.
```
You can avoid this problem by installing aider using `pipx`,
which will install it globally on your system
within its own python environment.
This way you can use aider to work on any python project,
even if that project has conflicting dependencies.
Install [pipx](https://pipx.pypa.io/stable/) then just do:
```
pipx install aider-chat
```
```
paul-gauthier/aider/blob/main/aider/website/docs/languages.md:
```md
---
parent: More info
nav_order: 900
description: Aider supports pretty much all popular coding languages.
---
# Supported languages
Aider should work well with most popular coding languages.
This is because top LLMs are fluent in most mainstream languages,
and familiar with popular libraries, packages and frameworks.
Aider has specific support for linting many languages.
By default, aider runs the built in linter any time a file is edited.
If it finds syntax errors, aider will offer to fix them for you.
This helps catch small code issues and quickly fix them.
Aider also does code analysis to help
the LLM navigate larger code bases by producing
a [repository map](https://aider.chat/docs/repomap.html).
Aider can currently produce repository maps for many popular
mainstream languages, listed below.
<!--[[[cog
from aider.repomap import get_supported_languages_md
cog.out(get_supported_languages_md())
]]]-->
| Language | File extension | Repo map | Linter |
|:--------:|:--------------:|:--------:|:------:|
| bash | .bash | | ✓ |
| c | .c | ✓ | ✓ |
| c_sharp | .cs | ✓ | ✓ |
| commonlisp | .cl | | ✓ |
| cpp | .cc | ✓ | ✓ |
| cpp | .cpp | ✓ | ✓ |
| css | .css | | ✓ |
| dockerfile | .dockerfile | | ✓ |
| dot | .dot | | ✓ |
| elisp | .el | ✓ | ✓ |
| elixir | .ex | ✓ | ✓ |
| elm | .elm | ✓ | ✓ |
| embedded_template | .et | | ✓ |
| erlang | .erl | | ✓ |
| go | .go | ✓ | ✓ |
| gomod | .gomod | | ✓ |
| hack | .hack | | ✓ |
| haskell | .hs | | ✓ |
| hcl | .hcl | | ✓ |
| html | .html | | ✓ |
| java | .java | ✓ | ✓ |
| javascript | .js | ✓ | ✓ |
| javascript | .mjs | ✓ | ✓ |
| jsdoc | .jsdoc | | ✓ |
| json | .json | | ✓ |
| julia | .jl | | ✓ |
| kotlin | .kt | | ✓ |
| lua | .lua | | ✓ |
| make | .mk | | ✓ |
| objc | .m | | ✓ |
| ocaml | .ml | ✓ | ✓ |
| perl | .pl | | ✓ |
| php | .php | ✓ | ✓ |
| python | .py | ✓ | ✓ |
| ql | .ql | ✓ | ✓ |
| r | .R | | ✓ |
| r | .r | | ✓ |
| regex | .regex | | ✓ |
| rst | .rst | | ✓ |
| ruby | .rb | ✓ | ✓ |
| rust | .rs | ✓ | ✓ |
| scala | .scala | | ✓ |
| sql | .sql | | ✓ |
| sqlite | .sqlite | | ✓ |
| toml | .toml | | ✓ |
| tsq | .tsq | | ✓ |
| typescript | .ts | ✓ | ✓ |
| typescript | .tsx | ✓ | ✓ |
| yaml | .yaml | | ✓ |
<!--[[[end]]]-->
## How to add support for another language
Aider should work quite well for other languages, even those
without repo map or linter support.
You should really try coding with aider before
assuming it needs better support for your language.
That said, if aider already has support for linting your language,
then it should be possible to add repo map support.
To build a repo map, aider needs the `tags.scm` file
from the given language's tree-sitter grammar.
If you can find and share that file in a
[GitHub issue](https://github.com/paul-gauthier/aider/issues),
then it may be possible to add repo map support.
If aider doesn't support linting, it will be complicated to
add linting and repo map support.
That is because aider relies on
[py-tree-sitter-languages](https://github.com/grantjenks/py-tree-sitter-languages)
to provide pre-packaged versions of tree-sitter
parsers for many languages.
Aider needs to be easy for users to install in many environments,
and it is probably too complex to add dependencies on
additional individual tree-sitter parsers.
```
paul-gauthier/aider/blob/main/aider/website/docs/leaderboards/index.md:
```md
---
highlight_image: /assets/leaderboard.jpg
nav_order: 950
description: Quantitative benchmarks of LLM code editing skill.
---
# Aider LLM Leaderboards
{: .no_toc }
Aider works best with LLMs which are good at *editing* code, not just good at writing
code.
To evaluate an LLM's editing skill, aider uses a pair of benchmarks that
assess a model's ability to consistently follow the system prompt
to successfully edit code.
The leaderboards below report the results from a number of popular LLMs.
While [aider can connect to almost any LLM](/docs/llms.html),
it works best with models that score well on the benchmarks.
See the following sections for benchmark
results and additional information:
- TOC
{:toc}
## Code editing leaderboard
[Aider's code editing benchmark](/docs/benchmarks.html#the-benchmark) asks the LLM to edit python source files to complete 133 small coding exercises
from Exercism.
This measures the LLM's coding ability, and whether it can
write new code that integrates into existing code.
The model also has to successfully apply all its changes to the source file without human intervention.
<table style="width: 100%; max-width: 800px; margin: auto; border-collapse: collapse; box-shadow: 0 2px 4px rgba(0,0,0,0.1); font-size: 14px;">
<thead style="background-color: #f2f2f2;">
<tr>
<th style="padding: 8px; text-align: left;">Model</th>
<th style="padding: 8px; text-align: center;">Percent completed correctly</th>
<th style="padding: 8px; text-align: center;">Percent using correct edit format</th>
<th style="padding: 8px; text-align: left;">Command</th>
<th style="padding: 8px; text-align: center;">Edit format</th>
</tr>
</thead>
<tbody>
{% assign edit_sorted = site.data.edit_leaderboard | sort: 'pass_rate_2' | reverse %}
{% for row in edit_sorted %}
<tr style="border-bottom: 1px solid #ddd;">
<td style="padding: 8px;">{{ row.model }}</td>
<td style="padding: 8px; text-align: center;">{{ row.pass_rate_2 }}%</td>
<td style="padding: 8px; text-align: center;">{{ row.percent_cases_well_formed }}%</td>
<td style="padding: 8px;"><code>{{ row.command }}</code></td>
<td style="padding: 8px; text-align: center;">{{ row.edit_format }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<canvas id="editChart" width="800" height="450" style="margin-top: 20px"></canvas>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function () {
var ctx = document.getElementById('editChart').getContext('2d');
var leaderboardData = {
labels: [],
datasets: [{
label: 'Percent completed correctly',
data: [],
backgroundColor: 'rgba(54, 162, 235, 0.2)',
borderColor: 'rgba(54, 162, 235, 1)',
borderWidth: 1
}]
};
var allData = [];
{% for row in edit_sorted %}
allData.push({
model: '{{ row.model }}',
pass_rate_2: {{ row.pass_rate_2 }},
percent_cases_well_formed: {{ row.percent_cases_well_formed }}
});
{% endfor %}
function updateChart() {
var selectedRows = document.querySelectorAll('tr.selected');
var showAll = selectedRows.length === 0;
leaderboardData.labels = [];
leaderboardData.datasets[0].data = [];
allData.forEach(function(row, index) {
var rowElement = document.getElementById('edit-row-' + index);
if (showAll) {
rowElement.classList.remove('selected');
}
if (showAll || rowElement.classList.contains('selected')) {
leaderboardData.labels.push(row.model);
leaderboardData.datasets[0].data.push(row.pass_rate_2);
}
});
leaderboardChart.update();
}
var tableBody = document.querySelector('table tbody');
allData.forEach(function(row, index) {
var tr = tableBody.children[index];
tr.id = 'edit-row-' + index;
tr.style.cursor = 'pointer';
tr.onclick = function() {
this.classList.toggle('selected');
updateChart();
};
});
var leaderboardChart = new Chart(ctx, {
type: 'bar',
data: leaderboardData,
options: {
scales: {
yAxes: [{
scaleLabel: {
display: true,
},
ticks: {
beginAtZero: true
}
}]
}
}
});
updateChart();
});
</script>
<style>
tr.selected {
color: #0056b3;
}
table {
table-layout: fixed;
}
td, th {
word-wrap: break-word;
overflow-wrap: break-word;
}
td:nth-child(3), td:nth-child(4) {
font-size: 12px;
}
</style>
## Code refactoring leaderboard
[Aider's refactoring benchmark](https://github.com/paul-gauthier/refactor-benchmark) asks the LLM to refactor 89 large methods from large python classes. This is a more challenging benchmark, which tests the model's ability to output long chunks of code without skipping sections or making mistakes. It was developed to provoke and measure [GPT-4 Turbo's "lazy coding" habit](/2023/12/21/unified-diffs.html).
The refactoring benchmark requires a large context window to
work with large source files.
Therefore, results are available for fewer models.
<table style="width: 100%; max-width: 800px; margin: auto; border-collapse: collapse; box-shadow: 0 2px 4px rgba(0,0,0,0.1); font-size: 14px;">
<thead style="background-color: #f2f2f2;">
<tr>
<th style="padding: 8px; text-align: left;">Model</th>
<th style="padding: 8px; text-align: center;">Percent completed correctly</th>
<th style="padding: 8px; text-align: center;">Percent using correct edit format</th>
<th style="padding: 8px; text-align: left;">Command</th>
<th style="padding: 8px; text-align: center;">Edit format</th>
</tr>
</thead>
<tbody>
{% assign refac_sorted = site.data.refactor_leaderboard | sort: 'pass_rate_1' | reverse %}
{% for row in refac_sorted %}
<tr style="border-bottom: 1px solid #ddd;">
<td style="padding: 8px;">{{ row.model }}</td>
<td style="padding: 8px; text-align: center;">{{ row.pass_rate_1 }}%</td>
<td style="padding: 8px; text-align: center;">{{ row.percent_cases_well_formed }}%</td>
<td style="padding: 8px;"><code>{{ row.command }}</code></td>
<td style="padding: 8px; text-align: center;">{{ row.edit_format }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<canvas id="refacChart" width="800" height="450" style="margin-top: 20px"></canvas>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function () {
var ctx = document.getElementById('refacChart').getContext('2d');
var leaderboardData = {
labels: [],
datasets: [{
label: 'Percent completed correctly',
data: [],
backgroundColor: 'rgba(54, 162, 235, 0.2)',
borderColor: 'rgba(54, 162, 235, 1)',
borderWidth: 1
}]
};
var allData = [];
{% for row in refac_sorted %}
allData.push({
model: '{{ row.model }}',
pass_rate_1: {{ row.pass_rate_1 }},
percent_cases_well_formed: {{ row.percent_cases_well_formed }}
});
{% endfor %}
function updateChart() {
var selectedRows = document.querySelectorAll('tr.selected');
var showAll = selectedRows.length === 0;
leaderboardData.labels = [];
leaderboardData.datasets[0].data = [];
allData.forEach(function(row, index) {
var rowElement = document.getElementById('refac-row-' + index);
if (showAll) {
rowElement.classList.remove('selected');
}
if (showAll || rowElement.classList.contains('selected')) {
leaderboardData.labels.push(row.model);
leaderboardData.datasets[0].data.push(row.pass_rate_1);
}
});
leaderboardChart.update();
}
var tableBody = document.querySelectorAll('table tbody')[1];
allData.forEach(function(row, index) {
var tr = tableBody.children[index];
tr.id = 'refac-row-' + index;
tr.style.cursor = 'pointer';
tr.onclick = function() {
this.classList.toggle('selected');
updateChart();
};
});
var leaderboardChart = new Chart(ctx, {
type: 'bar',
data: leaderboardData,
options: {
scales: {
yAxes: [{
scaleLabel: {
display: true,
},
ticks: {
beginAtZero: true
}
}]
}
}
});
updateChart();
});
</script>
## LLM code editing skill by model release date
[](https://aider.chat/assets/models-over-time.svg)
## Notes on benchmarking results
The key benchmarking results are:
- **Percent completed correctly** - Measures what percentage of the coding tasks that the LLM completed successfully. To complete a task, the LLM must solve the programming assignment *and* edit the code to implement that solution.
- **Percent using correct edit format** - Measures the percent of coding tasks where the LLM complied with the edit format specified in the system prompt. If the LLM makes edit mistakes, aider will give it feedback and ask for a fixed copy of the edit. The best models can reliably conform to the edit format, without making errors.
## Notes on the edit format
Aider uses different "edit formats" to collect code edits from different LLMs.
The "whole" format is the easiest for an LLM to use, but it uses a lot of tokens
and may limit how large a file can be edited.
Models which can use one of the diff formats are much more efficient,
using far fewer tokens.
Models that use a diff-like format are able to
edit larger files with less cost and without hitting token limits.
Aider is configured to use the best edit format for the popular OpenAI and Anthropic models
and the [other models recommended on the LLM page](/docs/llms.html).
For lesser known models aider will default to using the "whole" editing format
since it is the easiest format for an LLM to use.
## Contributing benchmark results
Contributions of benchmark results are welcome!
See the
[benchmark README](https://github.com/paul-gauthier/aider/blob/main/benchmark/README.md)
for information on running aider's code editing benchmarks.
Submit results by opening a PR with edits to the
[benchmark results data files](https://github.com/paul-gauthier/aider/blob/main/website/_data/).
<p class="post-date">
By Paul Gauthier,
last updated
<!--[[[cog
import subprocess
import datetime
files = [
'aider/website/docs/leaderboards/index.md',
'aider/website/_data/edit_leaderboard.yml',
'aider/website/_data/refactor_leaderboard.yml'
]
def get_last_modified_date(file):
result = subprocess.run(['git', 'log', '-1', '--format=%ct', file], capture_output=True, text=True)
if result.returncode == 0:
timestamp = int(result.stdout.strip())
return datetime.datetime.fromtimestamp(timestamp)
return datetime.datetime.min
mod_dates = [get_last_modified_date(file) for file in files]
latest_mod_date = max(mod_dates)
cog.out(f"{latest_mod_date.strftime('%B %d, %Y.')}")
]]]-->
August 10, 2024.
<!--[[[end]]]-->
</p>
```
paul-gauthier/aider/blob/main/aider/website/docs/llms.md:
```md
---
title: Connecting to LLMs
nav_order: 40
has_children: true
description: Aider can connect to most LLMs for AI pair programming.
---
# Aider can connect to most LLMs
{: .no_toc }
[](https://aider.chat/assets/llms.jpg)
## Best models
{: .no_toc }
Aider works best with these models, which are skilled at editing code:
- [GPT-4o](/docs/llms/openai.html)
- [Claude 3.5 Sonnet](/docs/llms/anthropic.html)
- [Claude 3 Opus](/docs/llms/anthropic.html)
- [DeepSeek Coder V2](/docs/llms/deepseek.html)
## Free models
{: .no_toc }
Aider works with a number of **free** API providers:
- Google's [Gemini 1.5 Pro](/docs/llms/gemini.html) works with aider, with
code editing capabilities similar to GPT-3.5.
- You can use [Llama 3 70B on Groq](/docs/llms/groq.html) which is comparable to GPT-3.5 in code editing performance.
- Cohere also offers free API access to their [Command-R+ model](/docs/llms/cohere.html), which works with aider as a *very basic* coding assistant.
## Local models
{: .no_toc }
Aider can work also with local models, for example using [Ollama](/docs/llms/ollama.html).
It can also access
local models that provide an
[Open AI compatible API](/docs/llms/openai-compat.html).
## Use a capable model
{: .no_toc }
Check
[Aider's LLM leaderboards](https://aider.chat/docs/leaderboards/)
to see which models work best with aider.
Be aware that aider may not work well with less capable models.
If you see the model returning code, but aider isn't able to edit your files
and commit the changes...
this is usually because the model isn't capable of properly
returning "code edits".
Models weaker than GPT 3.5 may have problems working well with aider.
```
paul-gauthier/aider/blob/main/aider/website/docs/llms/anthropic.md:
```md
---
parent: Connecting to LLMs
nav_order: 200
---
# Anthropic
To work with Anthropic's models, you need to provide your
[Anthropic API key](https://docs.anthropic.com/claude/reference/getting-started-with-the-api)
either in the `ANTHROPIC_API_KEY` environment variable or
via the `--anthropic-api-key` command line switch.
Aider has some built in shortcuts for the most popular Anthropic models and
has been tested and benchmarked to work well with them:
```
python -m pip install aider-chat
export ANTHROPIC_API_KEY=<key> # Mac/Linux
setx ANTHROPIC_API_KEY <key> # Windows, restart shell after setx
# Aider uses Claude 3.5 Sonnet by default (or use --sonnet)
aider
# Claude 3 Opus
aider --opus
# List models available from Anthropic
aider --models anthropic/
```
{: .tip }
Anthropic has very low rate limits.
You can access all the Anthropic models via
[OpenRouter](openrouter.md)
or [Google Vertex AI](vertex.md)
with more generous rate limits.
You can use `aider --model <model-name>` to use any other Anthropic model.
For example, if you want to use a specific version of Opus
you could do `aider --model claude-3-opus-20240229`.
```
paul-gauthier/aider/blob/main/aider/website/docs/llms/azure.md:
```md
---
parent: Connecting to LLMs
nav_order: 500
---
# Azure
Aider can connect to the OpenAI models on Azure.
```
python -m pip install aider-chat
# Mac/Linux:
export AZURE_API_KEY=<key>
export AZURE_API_VERSION=2023-05-15
export AZURE_API_BASE=https://myendpt.openai.azure.com
# Windows
setx AZURE_API_KEY <key>
setx AZURE_API_VERSION 2023-05-15
setx AZURE_API_BASE https://myendpt.openai.azure.com
# ... restart your shell after setx commands
aider --model azure/<your_deployment_name>
# List models available from Azure
aider --models azure/
```
Note that aider will also use environment variables
like `AZURE_OPENAI_API_xxx`.
```
paul-gauthier/aider/blob/main/aider/website/docs/llms/cohere.md:
```md
---
parent: Connecting to LLMs
nav_order: 500
---
# Cohere
Cohere offers *free* API access to their models.
Their Command-R+ model works well with aider
as a *very basic* coding assistant.
You'll need a [Cohere API key](https://dashboard.cohere.com/welcome/login).
To use **Command-R+**:
```
python -m pip install aider-chat
export COHERE_API_KEY=<key> # Mac/Linux
setx COHERE_API_KEY <key> # Windows, restart shell after setx
aider --model command-r-plus
# List models available from Cohere
aider --models cohere_chat/
```
```
paul-gauthier/aider/blob/main/aider/website/docs/llms/deepseek.md:
```md
---
parent: Connecting to LLMs
nav_order: 500
---
# DeepSeek
Aider can connect to the DeepSeek.com API.
The DeepSeek Coder V2 model has a top score on aider's code editing benchmark.
```
python -m pip install aider-chat
export DEEPSEEK_API_KEY=<key> # Mac/Linux
setx DEEPSEEK_API_KEY <key> # Windows, restart shell after setx
# Use DeepSeek Coder V2
aider --deepseek
```
```
paul-gauthier/aider/blob/main/aider/website/docs/llms/editing-format.md:
```md
---
parent: Connecting to LLMs
nav_order: 850
---
# Editing format
Aider uses different "edit formats" to collect code edits from different LLMs.
The "whole" format is the easiest for an LLM to use, but it uses a lot of tokens
and may limit how large a file can be edited.
Models which can use one of the diff formats are much more efficient,
using far fewer tokens.
Models that use a diff-like format are able to
edit larger files with less cost and without hitting token limits.
Aider is configured to use the best edit format for the popular OpenAI and Anthropic models
and the [other models recommended on the LLM page](https://aider.chat/docs/llms.html).
For lesser known models aider will default to using the "whole" editing format
since it is the easiest format for an LLM to use.
If you would like to experiment with the more advanced formats, you can
use these switches: `--edit-format diff` or `--edit-format udiff`.
```
paul-gauthier/aider/blob/main/aider/website/docs/llms/gemini.md:
```md
---
parent: Connecting to LLMs
nav_order: 300
---
# Gemini
Google currently offers
[*free* API access to the Gemini 1.5 Pro model](https://ai.google.dev/pricing).
This is the most capable free model to use with aider,
with code editing capability that's comparable to GPT-3.5.
You'll need a [Gemini API key](https://aistudio.google.com/app/u/2/apikey).
```
python -m pip install aider-chat
export GEMINI_API_KEY=<key> # Mac/Linux
setx GEMINI_API_KEY <key> # Windows, restart shell after setx
aider --model gemini/gemini-1.5-pro-latest
# List models available from Gemini
aider --models gemini/
```
```
paul-gauthier/aider/blob/main/aider/website/docs/llms/groq.md:
```md
---
parent: Connecting to LLMs
nav_order: 400
---
# GROQ
Groq currently offers *free* API access to the models they host.
The Llama 3 70B model works
well with aider and is comparable to GPT-3.5 in code editing performance.
You'll need a [Groq API key](https://console.groq.com/keys).
To use **Llama3 70B**:
```
python -m pip install aider-chat
export GROQ_API_KEY=<key> # Mac/Linux
setx GROQ_API_KEY <key> # Windows, restart shell after setx
aider --model groq/llama3-70b-8192
# List models available from Groq
aider --models groq/
```
```
paul-gauthier/aider/blob/main/aider/website/docs/llms/ollama.md:
```md
---
parent: Connecting to LLMs
nav_order: 500
---
# Ollama
Aider can connect to local Ollama models.
```
# Pull the model
ollama pull <model>
# Start your ollama server
ollama serve
# In another terminal window...
python -m pip install aider-chat
export OLLAMA_API_BASE=http://127.0.0.1:11434 # Mac/Linux
setx OLLAMA_API_BASE http://127.0.0.1:11434 # Windows, restart shell after setx
aider --model ollama/<model>
```
In particular, `llama3:70b` works well with aider:
```
ollama pull llama3:70b
ollama serve
# In another terminal window...
export OLLAMA_API_BASE=http://127.0.0.1:11434 # Mac/Linux
setx OLLAMA_API_BASE http://127.0.0.1:11434 # Windows, restart shell after setx
aider --model ollama/llama3:70b
```
See the [model warnings](warnings.html)
section for information on warnings which will occur
when working with models that aider is not familiar with.
```
paul-gauthier/aider/blob/main/aider/website/docs/llms/openai-compat.md:
```md
---
parent: Connecting to LLMs
nav_order: 500
---
# OpenAI compatible APIs
Aider can connect to any LLM which is accessible via an OpenAI compatible API endpoint.
```
python -m pip install aider-chat
# Mac/Linux:
export OPENAI_API_BASE=<endpoint>
export OPENAI_API_KEY=<key>
# Windows:
setx OPENAI_API_BASE <endpoint>
setx OPENAI_API_KEY <key>
# ... restart shell after setx commands
# Prefix the model name with openai/
aider --model openai/<model-name>
```
See the [model warnings](warnings.html)
section for information on warnings which will occur
when working with models that aider is not familiar with.
```
paul-gauthier/aider/blob/main/aider/website/docs/llms/openai.md:
```md
---
parent: Connecting to LLMs
nav_order: 100
---
# OpenAI
To work with OpenAI's models, you need to provide your
[OpenAI API key](https://help.openai.com/en/articles/4936850-where-do-i-find-my-secret-api-key)
either in the `OPENAI_API_KEY` environment variable or
via the `--openai-api-key` command line switch.
Aider has some built in shortcuts for the most popular OpenAI models and
has been tested and benchmarked to work well with them:
```
python -m pip install aider-chat
export OPENAI_API_KEY=<key> # Mac/Linux
setx OPENAI_API_KEY <key> # Windows, restart shell after setx
# Aider uses gpt-4o by default (or use --4o)
aider
# GPT-4 Turbo (1106)
aider --4-turbo
# GPT-3.5 Turbo
aider --35-turbo
# List models available from OpenAI
aider --models openai/
```
You can use `aider --model <model-name>` to use any other OpenAI model.
For example, if you want to use a specific version of GPT-4 Turbo
you could do `aider --model gpt-4-0125-preview`.
```
paul-gauthier/aider/blob/main/aider/website/docs/llms/openrouter.md:
```md
---
parent: Connecting to LLMs
nav_order: 500
---
# OpenRouter
Aider can connect to [models provided by OpenRouter](https://openrouter.ai/models?o=top-weekly):
You'll need an [OpenRouter API key](https://openrouter.ai/keys).
```
python -m pip install aider-chat
export OPENROUTER_API_KEY=<key> # Mac/Linux
setx OPENROUTER_API_KEY <key> # Windows, restart shell after setx
# Or any other open router model
aider --model openrouter/<provider>/<model>
# List models available from OpenRouter
aider --models openrouter/
```
In particular, many aider users access Sonnet via OpenRouter:
```
python -m pip install aider-chat
export OPENROUTER_API_KEY=<key> # Mac/Linux
setx OPENROUTER_API_KEY <key> # Windows, restart shell after setx
aider --model openrouter/anthropic/claude-3.5-sonnet
```
{: .tip }
If you get errors, check your
[OpenRouter privacy settings](https://openrouter.ai/settings/privacy).
Be sure to "enable providers that may train on inputs"
to allow use of all models.
```
paul-gauthier/aider/blob/main/aider/website/docs/llms/other.md:
```md
---
parent: Connecting to LLMs
nav_order: 800
---
# Other LLMs
Aider uses the [litellm](https://docs.litellm.ai/docs/providers) package
to connect to hundreds of other models.
You can use `aider --model <model-name>` to use any supported model.
To explore the list of supported models you can run `aider --models <model-name>`
with a partial model name.
If the supplied name is not an exact match for a known model, aider will
return a list of possible matching models.
For example:
```
$ aider --models turbo
Aider v0.29.3-dev
Models which match "turbo":
- gpt-4-turbo-preview (openai/gpt-4-turbo-preview)
- gpt-4-turbo (openai/gpt-4-turbo)
- gpt-4-turbo-2024-04-09 (openai/gpt-4-turbo-2024-04-09)
- gpt-3.5-turbo (openai/gpt-3.5-turbo)
- ...
```
See the [model warnings](warnings.html)
section for information on warnings which will occur
when working with models that aider is not familiar with.
## LiteLLM
Aider uses the LiteLLM package to connect to LLM providers.
The [LiteLLM provider docs](https://docs.litellm.ai/docs/providers)
contain more detail on all the supported providers,
their models and any required environment variables.
## Other API key variables
Here are the API key environment variables that are supported
by litellm. See their docs for more info.
<!--[[[cog
from subprocess import run
lines = run(
"egrep -ho '[A-Z_]+_API_KEY' ../litellm/litellm/*py | sort -u",
shell=True,
capture_output=True,
text=True,
).stdout
lines = ['- ' + line for line in lines.splitlines(keepends=True)]
cog.out(''.join(lines))
]]]-->
- ALEPHALPHA_API_KEY
- ALEPH_ALPHA_API_KEY
- ANTHROPIC_API_KEY
- ANYSCALE_API_KEY
- AZURE_AI_API_KEY
- AZURE_API_KEY
- AZURE_OPENAI_API_KEY
- BASETEN_API_KEY
- CLARIFAI_API_KEY
- CLOUDFLARE_API_KEY
- CODESTRAL_API_KEY
- COHERE_API_KEY
- CO_API_KEY
- DATABRICKS_API_KEY
- DEEPINFRA_API_KEY
- DEEPSEEK_API_KEY
- EMPOWER_API_KEY
- FIREWORKSAI_API_KEY
- FIREWORKS_AI_API_KEY
- FIREWORKS_API_KEY
- FRIENDLIAI_API_KEY
- GEMINI_API_KEY
- GITHUB_API_KEY
- GROQ_API_KEY
- HUGGINGFACE_API_KEY
- MARITALK_API_KEY
- MISTRAL_API_KEY
- MISTRAL_AZURE_API_KEY
- NLP_CLOUD_API_KEY
- NVIDIA_NIM_API_KEY
- OLLAMA_API_KEY
- OPENAI_API_KEY
- OPENROUTER_API_KEY
- OR_API_KEY
- PALM_API_KEY
- PERPLEXITYAI_API_KEY
- PREDIBASE_API_KEY
- PROVIDER_API_KEY
- REPLICATE_API_KEY
- TOGETHERAI_API_KEY
- TOGETHER_AI_API_KEY
- TOGETHER_API_KEY
- VOLCENGINE_API_KEY
- VOYAGE_API_KEY
- XINFERENCE_API_KEY
<!--[[[end]]]-->
```
paul-gauthier/aider/blob/main/aider/website/docs/llms/vertex.md:
```md
---
parent: Connecting to LLMs
nav_order: 550
---
# Vertex AI
Aider can connect to models provided by Google Vertex AI.
You will need to install the
[gcloud CLI](https://cloud.google.com/sdk/docs/install) and [login](https://cloud.google.com/sdk/docs/initializing) with a GCP account
or service account with permission to use the Vertex AI API.
With your chosen login method, the gcloud CLI should automatically set the
`GOOGLE_APPLICATION_CREDENTIALS` environment variable which points to the credentials file.
To configure Aider to use the Vertex AI API, you need to set `VERTEXAI_PROJECT` (the GCP project ID)
and `VERTEXAI_LOCATION` (the GCP region) [environment variables for Aider](/docs/config/dotenv.html).
Note that Claude on Vertex AI is only available in certain GCP regions,
check [the model card](https://console.cloud.google.com/vertex-ai/publishers/anthropic/model-garden/claude-3-5-sonnet)
for your model to see which regions are supported.
Example `.env` file:
```
VERTEXAI_PROJECT=my-project
VERTEXAI_LOCATION=us-east5
```
Then you can run aider with the `--model` command line switch, like this:
```
aider --model vertex_ai/claude-3-5-sonnet@20240620
```
Or you can use the [yaml config](/docs/config/aider_conf.html) to set the model to any of the
models supported by Vertex AI.
Example `.aider.conf.yml` file:
```yaml
model: vertex_ai/claude-3-5-sonnet@20240620
```
```
paul-gauthier/aider/blob/main/aider/website/docs/llms/warnings.md:
```md
---
parent: Connecting to LLMs
nav_order: 900
---
# Model warnings
{% include model-warnings.md %}
```
paul-gauthier/aider/blob/main/aider/website/docs/more-info.md:
```md
---
has_children: true
nav_order: 85
---
# More info
See below for more info about aider, including some advanced topics.
```
paul-gauthier/aider/blob/main/aider/website/docs/repomap.md:
```md
---
parent: More info
highlight_image: /assets/robot-ast.png
nav_order: 900
description: Aider uses a map of your git repository to provide code context to LLMs.
---
# Repository map

Aider
uses a **concise map of your whole git repository**
that includes
the most important classes and functions along with their types and call signatures.
This helps aider understand the code it's editing
and how it relates to the other parts of the codebase.
The repo map also helps aider write new code
that respects and utilizes existing libraries, modules and abstractions
found elsewhere in the codebase.
## Using a repo map to provide context
Aider sends a **repo map** to the LLM along with
each change request from the user.
The repo map contains a list of the files in the
repo, along with the key symbols which are defined in each file.
It shows how each of these symbols are defined, by including the critical lines of code for each definition.
Here's a part of
the repo map of aider's repo, for
[base_coder.py](https://github.com/paul-gauthier/aider/blob/main/aider/coders/base_coder.py)
and
[commands.py](https://github.com/paul-gauthier/aider/blob/main/aider/commands.py)
:
```
aider/coders/base_coder.py:
⋮...
│class Coder:
│ abs_fnames = None
⋮...
│ @classmethod
│ def create(
│ self,
│ main_model,
│ edit_format,
│ io,
│ skip_model_availabily_check=False,
│ **kwargs,
⋮...
│ def abs_root_path(self, path):
⋮...
│ def run(self, with_message=None):
⋮...
aider/commands.py:
⋮...
│class Commands:
│ voice = None
│
⋮...
│ def get_commands(self):
⋮...
│ def get_command_completions(self, cmd_name, partial):
⋮...
│ def run(self, inp):
⋮...
```
Mapping out the repo like this provides some key benefits:
- The LLM can see classes, methods and function signatures from everywhere in the repo. This alone may give it enough context to solve many tasks. For example, it can probably figure out how to use the API exported from a module just based on the details shown in the map.
- If it needs to see more code, the LLM can use the map to figure out which files it needs to look at. The LLM can ask to see these specific files, and aider will offer to add them to the chat context.
## Optimizing the map
Of course, for large repositories even just the repo map might be too large
for the LLM's context window.
Aider solves this problem by sending just the **most relevant**
portions of the repo map.
It does this by analyzing the full repo map using
a graph ranking algorithm, computed on a graph
where each source file is a node and edges connect
files which have dependencies.
Aider optimizes the repo map by
selecting the most important parts of the codebase
which will
fit into the active token budget.
The token budget is
influenced by the `--map-tokens` switch, which defaults to 1k tokens.
Aider adjusts the size of the repo map dynamically based on the state of the chat. It will usually stay within that setting's value. But it does expand the repo map
significantly at times, especially when no files have been added to the chat and aider needs to understand the entire repo as best as possible.
The sample map shown above doesn't contain *every* class, method and function from those
files.
It only includes the most important identifiers,
the ones which are most often referenced by other portions of the code.
These are the key pieces of context that the LLM needs to know to understand
the overall codebase.
## More info
Please check the
[repo map article on aider's blog](https://aider.chat/2023/10/22/repomap.html)
for more information on aider's repository map
and how it is constructed.
```
paul-gauthier/aider/blob/main/aider/website/docs/scripting.md:
```md
---
parent: More info
nav_order: 900
description: You can script aider via the command line or python.
---
# Scripting aider
You can script aider via the command line or python.
## Command line
Aider takes a `--message` argument, where you can give it a natural language instruction.
It will do that one thing, apply the edits to the files and then exit.
So you could do:
```bash
aider --message "make a script that prints hello" hello.js
```
Or you can write simple shell scripts to apply the same instruction to many files:
```bash
for FILE in *.py ; do
aider --message "add descriptive docstrings to all the functions" $FILE
done
```
User `aider --help` to see all the command line options, but these are useful for scripting:
```
--stream, --no-stream
Enable/disable streaming responses (default: True) [env var:
AIDER_STREAM]
--message COMMAND, --msg COMMAND, -m COMMAND
Specify a single message to send GPT, process reply then exit
(disables chat mode) [env var: AIDER_MESSAGE]
--message-file MESSAGE_FILE, -f MESSAGE_FILE
Specify a file containing the message to send GPT, process reply,
then exit (disables chat mode) [env var: AIDER_MESSAGE_FILE]
--yes Always say yes to every confirmation [env var: AIDER_YES]
--auto-commits, --no-auto-commits
Enable/disable auto commit of GPT changes (default: True) [env var:
AIDER_AUTO_COMMITS]
--dirty-commits, --no-dirty-commits
Enable/disable commits when repo is found dirty (default: True) [env
var: AIDER_DIRTY_COMMITS]
--dry-run, --no-dry-run
Perform a dry run without modifying files (default: False) [env var:
AIDER_DRY_RUN]
--commit Commit all pending changes with a suitable commit message, then exit
[env var: AIDER_COMMIT]
```
## Python
You can also script aider from python:
```python
from aider.coders import Coder
from aider.models import Model
# This is a list of files to add to the chat
fnames = ["greeting.py"]
model = Model("gpt-4-turbo")
# Create a coder object
coder = Coder.create(main_model=model, fnames=fnames)
# This will execute one instruction on those files and then return
coder.run("make a script that prints hello world")
# Send another instruction
coder.run("make it say goodbye")
# You can run in-chat "/" commands too
coder.run("/tokens")
```
See the
[Coder.create() and Coder.__init__() methods](https://github.com/paul-gauthier/aider/blob/main/aider/coders/base_coder.py)
for all the supported arguments.
It can also be helpful to set the equivalent of `--yes` by doing this:
```
from aider.io import InputOutput
io = InputOutput(yes=True)
# ...
coder = Coder.create(model=model, fnames=fnames, io=io)
```
```
paul-gauthier/aider/blob/main/aider/website/docs/troubleshooting.md:
```md
---
nav_order: 60
has_children: true
description: How to troubleshoot problems with aider and get help.
---
# Troubleshooting
Below are some approaches for troubleshooting problems with aider.
{% include help.md %}
```
paul-gauthier/aider/blob/main/aider/website/docs/troubleshooting/aider-not-found.md:
```md
---
parent: Troubleshooting
nav_order: 28
---
# Aider not found
In some environments the `aider` command may not be available
on your shell path.
This can occur because of permissions/security settings in your OS,
and often happens to Windows users.
You may see an error message like this:
> aider: The term 'aider' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
Below is the most fail safe way to install and run aider in these situations:
```
python -m pip install aider-chat
python -m aider
```
{% include venv-pipx.md %}
```
paul-gauthier/aider/blob/main/aider/website/docs/troubleshooting/edit-errors.md:
```md
---
parent: Troubleshooting
nav_order: 10
---
# File editing problems
Sometimes the LLM will reply with some code changes
that don't get applied to your local files.
In these cases, aider might say something like "Failed to apply edit to *filename*"
or other error messages.
This usually happens because the LLM is disobeying the system prompts
and trying to make edits in a format that aider doesn't expect.
Aider makes every effort to get the LLM
to conform, and works hard to deal with
LLMM edits that are "almost" correctly formatted.
But sometimes the LLM just won't cooperate.
In these cases, here are some things you might try.
## Use a capable model
If possible try using GPT-4o, Claude 3.5 Sonnet or Claude 3 Opus,
as they are the strongest and most capable models.
Weaker models
are more prone to
disobeying the system prompt instructions.
Most local models are just barely capable of working with aider,
so editing errors are probably unavoidable.
## Reduce distractions
Many LLM now have very large context windows,
but filling them with irrelevant code or conversation
can cofuse the model.
- Don't add too many files to the chat, *just* add the files you think need to be edited.
Aider also sends the LLM a [map of your entire git repo](https://aider.chat/docs/repomap.html), so other relevant code will be included automatically.
- Use `/drop` to remove files from the chat session which aren't needed for the task at hand. This will reduce distractions and may help GPT produce properly formatted edits.
- Use `/clear` to remove the conversation history, again to help GPT focus.
## More help
{% include help.md %}
```
paul-gauthier/aider/blob/main/aider/website/docs/troubleshooting/support.md:
```md
---
parent: Troubleshooting
excerpt: Use "/help <question>" to ask for help about using aider, customizing settings, troubleshooting, using LLMs, etc.
nav_order: 30
---
# Using /help
Type `/help <question>` and
aider will respond with helpful information.
You can ask questions about using aider,
customizing settings, troubleshooting, using LLMs, etc.
Behind the scenes, aider has indexed all of its
[documentation](https://aider.chat/).
It uses the question to find relevant docs
and share them with the LLM to do
retrieval augmented generation (RAG)
The LLM also has the full context of your ongoing
aider chat,
so it can help with the exact issue you might be facing.
<div class="chat-transcript" markdown="1">
> Aider v0.42.1-dev
> Models: claude-3-5-sonnet with diff edit format
> Repo-map: using 1024 tokens
> Use /help \<question\> to ask for help, run with --help to see cmd line args
#### /help is the .env file global or for a git repo?
Based on the provided documentation, here's the answer to your question about the .env file in aider:
The .env file in aider can be both global and specific to a git repository. Aider looks for .env files in multiple locations, with the following priority order:
1. Your home directory (global)
2. The root of your git repo (repo-specific)
3. The current directory
4. A file specified with the `--env-file <filename>` parameter
If multiple .env files exist in these locations, they are loaded in the order listed above, with files loaded last taking priority. This means you can have a global .env file in your home directory with general settings, and then override or add to those settings with a repo-specific .env file in your git repository root.
Here are some relevant documentation links that you might find helpful:
- https://aider.chat/docs/config.html
- https://aider.chat/docs/config/dotenv.html
The ability to use both global and repo-specific .env files allows for flexible configuration, where you can set default values globally and override them on a per-project basis as needed.
</div>
<div class="chat-transcript" markdown="1">
#### /help can i use local LLMs?
Yes, you can use local LLMs with Aider. Here's a summary of the options:
1. Ollama: Aider supports using local models through Ollama.
2. OpenAI-compatible API: Aider can access local models that provide an OpenAI-compatible API.
3. Other local models: Aider uses the LiteLLM package to connect to various LLM providers, which may include options for running models locally.
However, it's important to note that Aider works best with more capable models. Less capable models may have difficulty properly returning "code edits," which could result in Aider not being able to edit your files and commit changes effectively.
For more detailed information on using local LLMs and connecting to various models, you might want to check out these relevant documentation pages:
- https://aider.chat/docs/llms.html
- https://aider.chat/docs/llms/ollama.html
- https://aider.chat/docs/llms/openai-compat.html
Keep in mind that the performance and capabilities of local LLMs may vary depending on the specific model and your hardware resources.
</div>
## Getting more help
{% include help.md %}
```
paul-gauthier/aider/blob/main/aider/website/docs/troubleshooting/token-limits.md:
```md
---
parent: Troubleshooting
nav_order: 25
---
# Token limits
Every LLM has limits on how many tokens it can process for each request:
- The model's **context window** limits how many total tokens of
*input and output* it can process.
- Each model has limit on how many **output tokens** it can
produce.
Aider will report an error if a model responds indicating that
it has exceeded a token limit.
The error will include suggested actions to try and
avoid hitting token limits.
Here's an example error:
```
Model gpt-3.5-turbo has hit a token limit!
Input tokens: 768 of 16385
Output tokens: 4096 of 4096 -- exceeded output limit!
Total tokens: 4864 of 16385
To reduce output tokens:
- Ask for smaller changes in each request.
- Break your code into smaller source files.
- Try using a stronger model like gpt-4o or opus that can return diffs.
For more info: https://aider.chat/docs/token-limits.html
```
## Input tokens & context window size
The most common problem is trying to send too much data to a
model,
overflowing its context window.
Technically you can exhaust the context window if the input is
too large or if the input plus output are too large.
Strong models like GPT-4o and Opus have quite
large context windows, so this sort of error is
typically only an issue when working with weaker models.
The easiest solution is to try and reduce the input tokens
by removing files from the chat.
It's best to only add the files that aider will need to *edit*
to complete your request.
- Use `/tokens` to see token usage.
- Use `/drop` to remove unneeded files from the chat session.
- Use `/clear` to clear the chat history.
- Break your code into smaller source files.
## Output token limits
Most models have quite small output limits, often as low
as 4k tokens.
If you ask aider to make a large change that affects a lot
of code, the LLM may hit output token limits
as it tries to send back all the changes.
To avoid hitting output token limits:
- Ask for smaller changes in each request.
- Break your code into smaller source files.
- Use a strong model like gpt-4o, sonnet or opus that can return diffs.
## Other causes
Sometimes token limit errors are caused by
non-compliant API proxy servers
or bugs in the API server you are using to host a local model.
Aider has been well tested when directly connecting to
major
[LLM provider cloud APIs](https://aider.chat/docs/llms.html).
For serving local models,
[Ollama](https://aider.chat/docs/llms/ollama.html) is known to work well with aider.
Try using aider without an API proxy server
or directly with one of the recommended cloud APIs
and see if your token limit problems resolve.
## More help
{% include help.md %}
```
paul-gauthier/aider/blob/main/aider/website/docs/troubleshooting/warnings.md:
```md
---
parent: Troubleshooting
nav_order: 20
---
# Model warnings
{% include model-warnings.md %}
## More help
{% include help.md %}
```
paul-gauthier/aider/blob/main/aider/website/docs/unified-diffs.md:
```md
---
title: Unified diffs make GPT-4 Turbo 3X less lazy
excerpt: GPT-4 Turbo has a problem with lazy coding, which can be signiciantly improved by asking for code changes formatted as unified diffs.
highlight_image: /assets/benchmarks-udiff.jpg
nav_exclude: true
---
{% if page.date %}
<p class="post-date">{{ page.date | date: "%B %d, %Y" }}, by Paul Gauthier
</p>
{% endif %}
# Unified diffs make GPT-4 Turbo 3X less lazy

Aider now asks GPT-4 Turbo to use
[unified diffs](#choose-a-familiar-editing-format)
to edit your code.
This dramatically improves GPT-4 Turbo's performance on a
challenging
new benchmark
and significantly reduces its bad habit of "lazy" coding,
where it writes
code with comments
like "...add logic here...".
Aider's new "laziness" benchmark suite
is designed to both provoke and quantify lazy coding.
It consists of
89 python refactoring tasks
which tend to make GPT-4 Turbo write lazy comments like
"...include original method body...".
This new laziness benchmark produced the following results with `gpt-4-1106-preview`:
- **GPT-4 Turbo only scored 20% as a baseline** using aider's existing "SEARCH/REPLACE block" edit format. It outputs "lazy comments" on 12 of the tasks.
- **Aider's new unified diff edit format raised the score to 61%**. Using this format reduced laziness by 3X, with GPT-4 Turbo only using lazy comments on 4 of the tasks.
- **It's worse to add a prompt that says the user is blind, has no hands, will tip $2000 and fears truncated code trauma.** Widely circulated "emotional appeal" folk remedies
produced worse benchmark scores
for both the baseline SEARCH/REPLACE and new unified diff editing formats.
The older `gpt-4-0613` also did better on the laziness benchmark using unified diffs:
- **The June GPT-4's baseline was 26%** using aider's existing "SEARCH/REPLACE block" edit format.
- **Aider's new unified diff edit format raised June GPT-4's score to 59%**.
- The benchmark was designed to use large files, and
28% of them are too large to fit in June GPT-4's 8k context window.
This puts a hard ceiling of 72% on how well the June model could possibly score.
With unified diffs, GPT acts more like it's writing textual data intended to be read by a program,
not talking to a person.
Diffs are
usually
consumed by the
[patch](https://www.gnu.org/software/diffutils/manual/html_node/Merging-with-patch.html)
program, which is fairly rigid.
This seems to encourage rigor, making
GPT less likely to
leave informal editing instructions in comments
or be lazy about writing all the needed code.
Aider's new unified diff editing format
outperforms other solutions I evaluated by a wide margin.
I explored many other approaches including:
prompts about being tireless and diligent,
OpenAI's function/tool calling capabilities,
numerous variations on aider's existing editing formats,
line number based formats
and other diff-like formats.
The results shared here reflect
an extensive investigation and benchmark evaluations of many approaches.
The rest of this article will describe
aider's new editing format and refactoring benchmark.
It will highlight some key design decisions,
and evaluate their significance using ablation experiments.
## Unified diff editing format
The design and implementation of aider's new unified diff editing format
helped clarify some general principles
for GPT-4 code editing:
- FAMILIAR - Choose an edit format that GPT is already familiar with.
- SIMPLE - Choose a simple format that avoids escaping, syntactic overhead and brittle specifiers like line numbers or line counts.
- HIGH LEVEL - Encourage GPT to structure edits as new versions of substantive code blocks (functions, methods, etc), not as a series of surgical/minimal changes to individual lines of code.
- FLEXIBLE - Strive to be maximally flexible when interpreting GPT's edit instructions.
A helpful shortcut here is to have empathy for GPT, and imagine you
are the one being asked to specify code edits.
Would you want to hand type a properly escaped json data structure
to invoke surgical insert, delete, replace operations on specific code line numbers?
Do you want to use a brittle format, where any mistake
causes an error that discards all your work?
GPT is quantitatively better at code editing when you reduce the
burden of formatting edits by using a familiar, simple, high level
and flexible editing format.
### Choose a familiar editing format
Unified diffs are perhaps the most common way to show
code edits, because it's the
default output format of `git diff`:
```diff
--- a/greeting.py
+++ b/greeting.py
@@ -1,5 +1,5 @@
def main(args):
# show a greeting
- print("Hello!")
+ print("Goodbye!")
return
```
Choosing such a popular format means that GPT has
seen *many* examples in its training data.
It's been trained to generate
text that conforms to the unified diff syntax.
### Use a simple editing format
Aider's [previous benchmark results](https://aider.chat/docs/benchmarks.html) made
it clear that simple editing formats
work best.
Even though OpenAI provides extensive support for
structured formats like json and function calls,
GPT is worse at editing code if you use them.
I repeated these and other similar benchmarks against GPT-4 Turbo,
and again reached these same conclusions.
Informally, this is probably because stuffing *source code* into JSON is complicated
and error prone.
Wrapping the python code
`print("On Windows use \"C:\\\"")`
as valid json is pretty painful and error prone.
Due to escaping issues GPT's code is often syntactically incorrect when it's
unpacked from JSON,
or the JSON decode just fails entirely.
On the other hand, the core of the unified diff format is very simple.
You include a hunk of the file that needs to be changed,
with every line prefixed by a character
to indicate unchanged, new or deleted lines.
A unified diff looks pretty much like the code it is modifying.
The one complicated piece is the line numbers found at the start
of each hunk. They look something like this: `@@ -2,4 +3,5 @@`.
GPT is terrible at working with source code line numbers.
This is a general observation about *any* use of line
numbers in editing formats,
backed up by many quantitative benchmark experiments.
You've probably ignored the line numbers in every diff you've seen,
because the diffs usually still make sense without them.
Aider tells GPT not to include line numbers,
and just interprets each hunk from the unified diffs
as a search and replace operation:
This diff:
```diff
@@ ... @@
def main(args):
# show a greeting
- print("Hello!")
+ print("Goodbye!")
return
```
Means we need to search the file for the
*space* and *minus* `-` lines:
```python
def main(args):
# show a greeting
print("Hello!")
return
```
And replace them with the *space* and *plus* `+` lines:
```python
def main(args):
# show a greeting
print("Goodbye!")
return
```
Simple, right?
### Encourage high level edits
The example unified diffs we've seen so far have all been single line changes,
which makes them pretty easy to read and understand.
Consider this slightly more complex change, which renames the variable `n` to
`number`:
```diff
@@ ... @@
-def factorial(n):
+def factorial(number):
- if n == 0:
+ if number == 0:
return 1
else:
- return n * factorial(n-1)
+ return number * factorial(number-1)
```
The following "high level diff" of the same
change is not as succinct as the minimal diff above,
but it is much easier to see two different coherent versions of the
`factorial()` function.
```diff
@@ ... @@
-def factorial(n):
- if n == 0:
- return 1
- else:
- return n * factorial(n-1)
+def factorial(number):
+ if number == 0:
+ return 1
+ else:
+ return number * factorial(number-1)
```
Aider's system prompt encourages
GPT to produce these high level diffs.
This makes GPT better at producing correct diffs, which can be successfully
applied to the original file.
**Experiments without "high level diff" prompting
produce a 30-50% increase in editing errors,**
where diffs fail to apply or apply incorrectly and
produce invalid code.
When a patch fails, aider needs to ask GPT for a corrected version of the diff.
This takes time, costs tokens and sometimes fails to produce a successful edit
even after multiple retries.
There are probably a couple of reasons why high level diffs
help:
- It's easier to produce diffs that both correctly match the original code and correctly produce the intended new code. There is less risk of GPT getting confused, compared to generating a series of surgical edits that interleave lines of old and new code.
- High level hunks often contain more lines than a surgical hunk, so they are less likely to accidentally match unrelated parts of the code. This is helpful because GPT can't reliably give us line numbers to specify exactly where in the file to make changes.
### Be flexible when applying edits
GPT frequently makes imperfect diffs that won't apply cleanly.
They exhibit a variety of problems:
- GPT forgets things like comments, docstrings, blank lines, etc. Or it skips over some code that it doesn't intend to change.
- GPT forgets the leading *plus* `+` character to mark novel lines that it wants to add to the file. It incorrectly includes them with a leading *space* as if they were already there.
- GPT outdents all of the code, removing all the leading white space which is shared across the lines. So a chunk of deeply indented code is shown in a diff with only the leading white space that changes between the lines in the chunk.
- GPT jumps ahead to show edits to a different part of the file without starting a new hunk with a `@@ ... @@` divider.
As an example of the first issue, consider this source code:
```python
import sys
def main(args):
# show a greeting
print("Hello!")
return
main(sys.argv[1:])
```
**The diff below is missing the "show a greeting" comment line**,
and represents a common type of mistake GPT might make.
When we search for the *minus* `-` lines, we won't find them
in the original file
because of the missing comment.
```diff
@@ ... @@
-def main(args):
- print("Hello!")
- return
+def main(args):
+ print("Goodbye!")
+ return
```
Aider tries to be very flexible when applying diffs,
in order to handle defects.
If a hunk doesn't apply cleanly, aider uses a number of strategies:
- Normalize the hunk, by taking the *minus* `-` and *space* lines as one version of the hunk and the *space* and *plus* `+` lines as a second version and doing an actual unified diff on them.
- Try and discover new lines that GPT is trying to add but which it forgot to mark with *plus* `+` markers. This is done by diffing the *minus* `-` and *space* lines back against the original file.
- Try and apply the hunk using "relative leading white space", so we can match and patch correctly even if the hunk has been uniformly indented or outdented.
- Break a large hunk apart into an overlapping sequence of smaller hunks, which each contain only one contiguous run of *plus* `+` and *minus* `-` lines. Try and apply each of these sub-hunks independently.
- Vary the size and offset of the "context window" of *space* lines from the hunk that are used to localize the edit to a specific part of the file.
- Combine the above mechanisms to progressively become more permissive about how to apply the hunk.
These flexible patching strategies are critical, and
removing them
radically increases the number of hunks which fail to apply.
**Experiments where flexible patching is disabled show a 9X increase in editing errors** on aider's original Exercism benchmark.
## Refactoring benchmark
Aider has long used a
[benchmark suite based on 133 Exercism python exercises](https://aider.chat/2023/07/02/benchmarks.html).
But these are mostly small coding problems,
usually requiring only a few dozen lines of code.
GPT-4 Turbo is typically only lazy on 2-3 of these exercises:
the ones with the most code and which involve refactoring.
Based on this observation, I set out to build a benchmark based on refactoring
a non-trivial amount of code found in fairly large files.
To do this, I used python's `ast` module to analyze
[9 popular open source python repositories](https://github.com/paul-gauthier/refactor-benchmark)
to identify challenging refactoring tasks.
The goal was to find:
- Source files that contain classes with non-trivial methods, having 100-250+ AST nodes in their implementation.
- Focus on methods that are part of a larger class, which has at least twice as much code as the method itself.
- Select methods that don't use their `self` parameter, so they can be trivially refactored out of the class.
We can then turn each of these source files into a task for the benchmark,
where we ask GPT to do something like:
> Refactor the `_set_csrf_cookie` method in the `CsrfViewMiddleware` class to be a stand alone, top level function.
> Name the new function `_set_csrf_cookie`, exactly the same name as the existing method.
> Update any existing `self._set_csrf_cookie` calls to work with the new `_set_csrf_cookie` function.
A [simple python AST scanning script](https://github.com/paul-gauthier/aider/blob/main/benchmark/refactor_tools.py)
found 89 suitable files
and packaged them up as benchmark tasks.
Each task has a test
that checks if the refactor
was performed roughly correctly:
- The updated source file must parse as valid python, to detect misapplied edits which produce invalid code.
- The target method must now exist as a top-level function in the file.
- This new top-level function must contain approximately the same number of AST nodes as the original class method. This ensures that GPT didn't elide code and replace it with comments.
- The original class must still be present in the file, and it must be smaller by about the number of AST nodes in the method which was removed. This helps confirm that the method was removed from the class, without other significant modifications.
To be clear, this is not a rigorous test that the refactor was performed correctly.
But it does serve as a basic sanity check that the refactor was essentially done as a cut & paste, without eliding any code as comments.
And it correlates well with other laziness metrics
gathered during benchmarking like the
introduction of new comments that contain "...".
The result is a pragmatic
[benchmark suite that provokes, detects and quantifies GPT coding laziness](https://github.com/paul-gauthier/refactor-benchmark).
## Conclusions and future work
Based on the refactor benchmark results,
aider's new unified diff format seems
to dramatically increase GPT-4 Turbo's skill at more complex coding tasks.
It also seems very effective at reducing the lazy coding
which has been widely noted as a problem with GPT-4 Turbo.
Unified diffs was one of the very first edit formats I tried
when originally building aider.
I think a lot of other AI coding assistant projects have also
tried going down this path.
It seems like any naive or direct use of structured diff formats
is pretty much doomed to failure.
But the techniques described here and
incorporated into aider provide
a highly effective way to harness GPT's knowledge of unified diffs.
There could be significant benefits to
fine tuning models on
aider's simple, high level style of unified diffs.
Dropping line numbers from the hunk headers and focusing on diffs of
semantically coherent chunks of code
seems to be an important part of successful GPT code editing
(besides the relentless focus on flexibly applying edits).
Most LLMs will have already seen plenty of unified diffs
in their normal training data, and so should be
amenable to fining tuning towards this
particular diff style.
```
paul-gauthier/aider/blob/main/aider/website/docs/usage.md:
```md
---
nav_order: 30
has_children: true
description: How to use aider to pair program with AI and edit code in your local git repo.
---
# Usage
Run `aider` with the source code files you want to edit.
These files will be "added to the chat session", so that
aider can see their
contents and edit them for you.
They can be existing files or the name of files you want
aider to create for you.
```
aider <file1> <file2> ...
```
At the aider `>` prompt, ask for code changes and aider
will edit those files to accomplish your request.
```
$ aider factorial.py
Aider v0.37.1-dev
Models: gpt-4o with diff edit format, weak model gpt-3.5-turbo
Git repo: .git with 258 files
Repo-map: using 1024 tokens
Use /help to see in-chat commands, run with --help to see cmd line args
───────────────────────────────────────────────────────────────────────
> Make a program that asks for a number and prints its factorial
...
```
{% include help-tip.md %}
## Adding files
To edit files, you need to "add them to the chat".
Do this
by naming them on the aider command line.
Or, you can use the in-chat
`/add` command to add files.
Only add the files that need to be edited for your task.
Don't add a bunch of extra files.
If you add too many files, the LLM can get overwhelmed
and confused (and it costs more tokens).
Aider will automatically
pull in content from related files so that it can
[understand the rest of your code base](https://aider.chat/docs/repomap.html).
You can use aider without adding any files,
and it will try to figure out which files need to be edited based
on your requests.
{: .tip }
You'll get the best results if you think about which files need to be
edited. Add **just** those files to the chat. Aider will include
relevant context from the rest of your repo.
## LLMs
{% include works-best.md %}
```
# GPT-4o
$ aider --4o
# Claude 3.5 Sonnet
$ aider --sonnet
```
Or you can run `aider --model XXX` to launch aider with
another model.
During your chat you can switch models with the in-chat
`/model` command.
## Making changes
Ask aider to make changes to your code.
It will show you some diffs of the changes it is making to
complete you request.
[Aider will git commit all of its changes](/docs/git.html),
so they are easy to track and undo.
You can always use the `/undo` command to undo AI changes that you don't
like.
```
paul-gauthier/aider/blob/main/aider/website/docs/usage/browser.md:
```md
---
title: Aider in your browser
highlight_image: /assets/browser.jpg
parent: Usage
nav_order: 800
description: Aider can run in your browser, not just on the command line.
---
{% if page.date %}
<p class="post-date">{{ page.date | date: "%B %d, %Y" }}</p>
{% endif %}
# Aider in your browser
<div class="video-container">
<video controls loop poster="/assets/browser.jpg">
<source src="/assets/aider-browser-social.mp4" type="video/mp4">
<a href="/assets/aider-browser-social.mp4">Aider browser UI demo video</a>
</video>
</div>
<style>
.video-container {
position: relative;
padding-bottom: 101.89%; /* 1080 / 1060 = 1.0189 */
height: 0;
overflow: hidden;
}
.video-container video {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
</style>
Use aider's new experimental browser UI to collaborate with LLMs
to edit code in your local git repo.
Aider will directly edit the code in your local source files,
and [git commit the changes](https://aider.chat/docs/git.html)
with sensible commit messages.
You can start a new project or work with an existing git repo.
Aider works well with GPT 3.5, GPT-4, GPT-4 Turbo with Vision,
and Claude 3 Opus.
It also supports [connecting to almost any LLM](https://aider.chat/docs/llms.html).
Use the `--browser` switch to launch the browser version of aider:
```
python -m pip install aider-chat
export OPENAI_API_KEY=<key> # Mac/Linux
setx OPENAI_API_KEY <key> # Windows, restart shell after setx
aider --browser
```
```
paul-gauthier/aider/blob/main/aider/website/docs/usage/commands.md:
```md
---
parent: Usage
nav_order: 50
description: Control aider with in-chat commands like /add, /model, etc.
---
# In-chat commands
Aider supports commands from within the chat, which all start with `/`.
<!--[[[cog
from aider.commands import get_help_md
cog.out(get_help_md())
]]]-->
|Command|Description|
|:------|:----------|
| **/add** | Add files to the chat so GPT can edit them or review them in detail |
| **/ask** | Ask questions about the code base without editing any files |
| **/chat-mode** | Switch to a new chat mode |
| **/clear** | Clear the chat history |
| **/clipboard** | Add image/text from the clipboard to the chat (optionally provide a name for the image) |
| **/code** | Ask for changes to your code |
| **/commit** | Commit edits to the repo made outside the chat (commit message optional) |
| **/diff** | Display the diff of changes since the last message |
| **/drop** | Remove files from the chat session to free up context space |
| **/exit** | Exit the application |
| **/git** | Run a git command |
| **/help** | Ask questions about aider |
| **/lint** | Lint and fix provided files or in-chat files if none provided |
| **/ls** | List all known files and indicate which are included in the chat session |
| **/map** | Print out the current repository map |
| **/model** | Switch to a new LLM |
| **/models** | Search the list of available models |
| **/quit** | Exit the application |
| **/read** | Add a file to the chat that is for reference, not to be edited |
| **/run** | Run a shell command and optionally add the output to the chat (alias: !) |
| **/test** | Run a shell command and add the output to the chat on non-zero exit code |
| **/tokens** | Report on the number of tokens used by the current chat context |
| **/undo** | Undo the last git commit if it was done by aider |
| **/voice** | Record and transcribe voice input |
| **/web** | Scrape a webpage, convert to markdown and add to the chat |
<!--[[[end]]]-->
{: .tip }
You can easily re-send commands or messages.
Use the up arrow ⬆ to scroll back
or CONTROL-R to search your message history.
## Entering multi-line chat messages
{% include multi-line.md %}
## Interrupting with CONTROL-C
It's always safe to use Control-C to interrupt aider if it isn't providing a useful response. The partial response remains in the conversation, so you can refer to it when you reply to the LLM with more information or direction.
## Keybindings
The interactive prompt is built with [prompt-toolkit](https://github.com/prompt-toolkit/python-prompt-toolkit) which provides emacs and vi keybindings.
### Emacs
- `Ctrl-A` : Move cursor to the start of the line.
- `Ctrl-B` : Move cursor back one character.
- `Ctrl-D` : Delete the character under the cursor.
- `Ctrl-E` : Move cursor to the end of the line.
- `Ctrl-F` : Move cursor forward one character.
- `Ctrl-K` : Delete from the cursor to the end of the line.
- `Ctrl-L` : Clear the screen.
- `Ctrl-N` : Move down to the next history entry.
- `Ctrl-P` : Move up to the previous history entry.
- `Ctrl-R` : Reverse search in command history.
### Vi
To use vi/vim keybindings, run aider with the `--vim` switch.
- `Esc` : Switch to command mode.
- `i` : Switch to insert mode.
- `a` : Move cursor one character to the right and switch to insert mode.
- `A` : Move cursor to the end of the line and switch to insert mode.
- `I` : Move cursor to the beginning of the line and switch to insert mode.
- `h` : Move cursor one character to the left.
- `j` : Move cursor down one line.
- `k` : Move cursor up one line.
- `l` : Move cursor one character to the right.
- `w` : Move cursor forward one word.
- `b` : Move cursor backward one word.
- `0` : Move cursor to the beginning of the line.
- `$` : Move cursor to the end of the line.
- `x` : Delete the character under the cursor.
- `dd` : Delete the current line.
- `u` : Undo the last change.
- `Ctrl-R` : Redo the last undone change.
```
paul-gauthier/aider/blob/main/aider/website/docs/usage/conventions.md:
```md
---
parent: Usage
nav_order: 800
description: Tell aider to follow your coding conventions when it works on your code.
---
# Specifying coding conventions
Sometimes you want GPT to be aware of certain coding guidelines,
like whether to provide type hints, which libraries or packages
to prefer, etc.
The easiest way to do that with aider is to simply create
a small markdown file and include it in the chat.
For example, say we want our python code to:
```
- Prefer httpx over requests for making http requests.
- Use types everywhere possible.
```
We would simply create a file like `CONVENTIONS.md` with those lines
and then we can add it to the aider chat, along with the file(s)
that we want to edit:
<div class="chat-transcript" markdown="1">
> $ aider CONVENTIONS.md useragent.py
>
> Aider v0.24.2-dev
> Added CONVENTIONS.md to the chat.
> Added useragent.py to the chat.
#### write a function that uses httpbin to check the user agent on the request. return the ua.
To fulfill your request, I will:
1. Add an import for `httpx`.
2. Write a function named `check_user_agent` that makes a GET request to `httpbin.org/user-agent` and returns the user agent string.
Here is the diff for the `useragent.py` file:
```diff
--- useragent.py
+++ useragent.py
@@ ... @@
+import httpx
+
+def check_user_agent() -> str:
+ response = httpx.get('https://httpbin.org/user-agent')
+ return response.json()['user-agent']
```
This function uses `httpx` to make a GET request to `httpbin.org/user-agent`, which returns a JSON response containing the user agent of the HTTP client. The function then extracts the user agent string from the JSON response and returns it.
> Applied edit to useragent.py
</div>
GPT correctly used `httpx` and provided type hints.
See below for the transcript of this same
coding task conducted *without*
using `CONVENTIONS.md`.
In this case, GPT used `requests` and skipped types,
which is perhaps more typical in small python scripts.
<div class="chat-transcript" markdown="1">
> $ aider useragent.py
>
> Aider v0.24.2-dev
> Added useragent.py to the chat.
#### write a function that uses httpbin to check the user agent on the request. return the ua.
```diff
--- /dev/null
+++ useragent.py
@@ ... @@
+import requests
+
+def check_user_agent():
+ response = requests.get('https://httpbin.org/user-agent')
+ user_agent = response.json().get('user-agent')
+ return user_agent
```
> Applied edit to useragent.py
</div>
```
paul-gauthier/aider/blob/main/aider/website/docs/usage/images-urls.md:
```md
---
parent: Usage
nav_order: 700
description: Add images and web pages to the aider coding chat.
---
# Images & web pages
You can add images and URLs to the aider chat.
## Images
Aider supports working with image files for many vision-capable models
like GPT-4o and Claude 3.5 Sonnet.
Adding images to a chat can be helpful in many situations:
- Add screenshots of web pages or UIs that you want aider to build or modify.
- Show aider a mockup of a UI you want to build.
- Screenshot an error message that is otherwise hard to copy & paste as text.
- Etc.
You can add images to the chat just like you would
add any other file:
- Use `/add <image-filename>` from within the chat
- Use `/add-clipboard-image` to paste an image from your clipboard into the chat.
- Launch aider with image filenames on the command line: `aider <image-filename>` along with any other command line arguments you need.
## Web pages
Aider can scrape the text from URLs and add it to the chat.
This can be helpful to:
- Include documentation pages for less popular APIs.
- Include the latest docs for libraries or packages that are newer than the model's training cutoff date.
- Etc.
To add URLs to the chat:
- Use `/web <url>`
- Just paste the URL into the chat and aider will ask if you want to add it.
```
paul-gauthier/aider/blob/main/aider/website/docs/usage/lint-test.md:
```md
---
parent: Usage
nav_order: 900
description: Automatically fix linting and testing errors.
---
# Linting and testing
Aider can automatically lint and test your code
every time it makes changes.
This helps identify and repair any problems introduced
by the AI edits.
## Linting
Aider comes with built in linters for
[most popular languages](/docs/languages.html)
and will automatically lint code in these languages.
Or you can specify your favorite linter
with the `--lint-cmd <cmd>` switch.
The lint command should accept the filenames
of the files to lint.
If there are linting errors, aider expects the
command to print them on stdout/stderr
and return a non-zero exit code.
This is how most linters normally operate.
By default, aider will lint any files which it edits.
You can disable this with the `--no-auto-lint` switch.
## Testing
You can configure aider to run your test suite
after each time the AI edits your code
using the `--test-cmd <cmd>` switch.
Aider will run the test command without any arguments.
If there are test errors, aider expects the
command to print them on stdout/stderr
and return a non-zero exit code.
This is how most test tools normally operate.
To have aider automatically run the test command,
use the `--auto-test` switch.
## Compiled languages
If you want to have aider compile code after each edit, you
can use the lint and test commands to achieve this.
- You might want to recompile each file which was modified
to check for compile errors.
To do this,
provide a `--lint-cmd` which both lints and compiles the file.
You could create a small shell script for this.
- You might want to rebuild the entire project after files
are edited to check for build errors.
To do this,
provide a `--test-cmd` which both builds and tests the project.
You could create a small shell script for this.
Or you may be able to do something as simple as
`--test-cmd "dotnet build && dotnet test"`.
## Manually running code
You can use the `/run` command in the chat to run your code
and optionally share the output with aider.
This can be useful to share error messages or to show aider
the code's output before asking for changes or corrections.
<div class="chat-transcript" markdown="1">
> Aider v0.43.5-dev
#### /run python myscript.py
```
Traceback (most recent call last):
File "myscript.py", line 22, in \<module\
raise ValueError("something bad happened")
ValueError: something bad happened
```
> Add the output to the chat? y
</div>
```
paul-gauthier/aider/blob/main/aider/website/docs/usage/modes.md:
```md
---
parent: Usage
nav_order: 60
description: Using the chat, ask and help chat modes.
---
# Chat modes
Aider has 3 different chat modes:
- `code` - Aider will make changes to your code to satisfy your requests.
- `ask` - Aider will answer questions about your code, but never edit it.
- `help` - Aider will answer questions about using aider, configuring, troubleshooting, etc.
By default, aider starts in "code" mode. As you are talking, you can
send individual messages in a specific mode using `/code`, `/ask`, and `/help` commands:
Using `/code`, `/ask`, and `/help` applies just to that particular message.
Your next message will go back to the active mode (usually "code" mode by default).
You can switch the active mode in a sticky way
with the `/chat-mode <mode>` command:
```
/chat-mode code
/chat-mode ask
/chat-mode help
```
Or you can launch aider in one of the modes with the `--chat-mode <mode>` switch.
<div class="chat-transcript" markdown="1">
> Aider v0.47.1-dev
> Models: claude-3-5-sonnet-20240620 with diff edit format
> Git repo: .git with 298 files
> Repo-map: using 1024 tokens
> Use /help to see in-chat commands, run with --help to see cmd line args
#### /ask What is this repo?
This is the source code to the popular django package.
#### /help How do I use ollama?
Run `aider --model ollama/<ollama-model>`.
See these docs for more info: https://aider.chat/docs/llms/ollama.html
#### /code Add a function to calculate the factorial of a number
Certainly! I'll add a function to calculate the factorial of a number. Here's the change:
```python
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
# Example usage
print(factorial(5)) # Output: 120
```
This function uses recursion to calculate the factorial. It's been added to your code.
</div>
```
paul-gauthier/aider/blob/main/aider/website/docs/usage/tips.md:
```md
---
parent: Usage
nav_order: 25
description: Tips for AI pair programming with aider.
---
# Tips
- Think about which files need to be edited to make your change and add them to the chat.
Aider can help the LLM figure out which files to edit all by itself, but the most efficient approach is to add the needed files to the chat yourself.
- Don't add *everything* to the chat, just the files you think need to be edited.
Aider also sends the LLM a [map of your entire git repo](https://aider.chat/docs/repomap.html).
So the LLM can see all the other relevant parts of your code base.
- Large changes are best performed as a sequence of thoughtful bite sized steps, where you plan out the approach and overall design. Walk the LLM through changes like you might with a junior dev. Ask for a refactor to prepare, then ask for the actual change. Spend the time to ask for code quality/structure improvements.
- It's always safe to use Control-C to interrupt aider if it isn't providing a useful response. The partial response remains in the conversation, so you can refer to it when you reply to the LLM with more information or direction.
- If your code is throwing an error,
use the `/run` [in-chat command](/docs/usage/commands.html)
to share the error output with the aider.
Or just paste the errors into the chat. Let the aider figure out and fix the bug.
- If test are failing, use the `/test` [in-chat command](/docs/usage/commands.html)
to run tests and
share the error output with the aider.
- {% include multi-line.md %}
- LLMs know about a lot of standard tools and libraries, but may get some of the fine details wrong about API versions and function arguments.
You can paste doc snippets into the chat to resolve these issues.
```
paul-gauthier/aider/blob/main/aider/website/docs/usage/tutorials.md:
```md
---
parent: Usage
nav_order: 75
description: Intro and tutorial videos made by aider users.
---
# Tutorial videos
Here are some tutorial videos made by aider users:
- [Step-by-Step Development Environment Setup for AI-Assisted Coding](https://www.youtube.com/watch?v=DnBVgfe6ZQM) -- Coding the Future With AI
- [Generate FULL-STACK Apps with Claude 3.5 Sonnet](https://youtu.be/sKeIZGW8xzg) -- AICodeKing
- [Creating Games with AI from Start-To-End](https://youtu.be/sOd2YYZFMUs) -- AICodeKing
- [Claude 3.5 and aider: Use AI Assistants to Build AI Apps](https://youtu.be/0hIisJ3xAdU) -- Coding the Future With AI
- [Develop a Full-stack App Without Writing ANY Code](https://youtu.be/dzOWn8TI738) -- WorldofAI
- [Generate Games with AI (w/ Local LLMs)](https://youtu.be/DjVJpGzQbSA) -- AICodeKing
- [Aider tips and Example use](https://www.youtube.com/watch?v=OsChkvGGDgw) -- techfren
- [Aider and Claude 3.5: Develop a Full-stack App Without Writing ANY Code!](https://www.youtube.com/watch?v=BtAqHsySdSY) -- Coding the Future With AI
- [Generate application with just one prompt using Aider](https://www.youtube.com/watch?v=Y-_0VkMUiPc&t=78s) -- AICodeKing
- [Aider : the production ready AI coding assistant you've been waiting for](https://www.youtube.com/watch?v=zddJofosJuM) -- Learn Code With JV
- [Holy Grail: FREE Coding Assistant That Can Build From EXISTING CODE BASE](https://www.youtube.com/watch?v=df8afeb1FY8) -- Matthew Berman
- [Aider: This AI Coder Can Create AND Update Git Codebases](https://www.youtube.com/watch?v=EqLyFT78Sig) -- Ian Wootten
Thanks to all these great creators for taking the time
to share their experiences coding with aider!
```
paul-gauthier/aider/blob/main/aider/website/docs/usage/voice.md:
```md
---
parent: Usage
nav_order: 100
description: Speak with aider about your code!
---
# Voice-to-code with aider
Speak with aider about your code! Request new features, test cases or bug fixes using your voice and let aider do the work of editing the files in your local git repo. As with all of aider's capabilities, you can use voice-to-code with an existing repo or to start a new project.
Voice support fits quite naturally into aider's AI pair programming
chat interface. Now you can fluidly switch between voice and text chat
when you ask aider to edit your code.
## How to use voice-to-code
Use the in-chat `/voice` command to start recording,
and press `ENTER` when you're done speaking.
Your voice coding instructions will be transcribed,
as if you had typed them into
the aider chat session.
See the [installation instructions](https://aider.chat/docs/install/optional.html#enable-voice-coding) for
information on how to enable the `/voice` command.
<br/>
<div class="chat-transcript" markdown="1">
> Aider v0.11.2-dev
> Added app.py to the chat.
#### /voice
<blockquote>
<div class="recording-line">
<p style="display: inline;">Recording, press ENTER when done... <span id="timer">3.5</span>sec</p>
<div id="progress-bar">
<div id="progress"></div>
</div>
</div>
</blockquote>
<style>
.recording-line > * {
display: inline-block;
vertical-align: middle;
}
#progress-bar {
width: 100px;
height: 20px;
background-color: #333;
margin-left: 10px;
}
#progress {
height: 100%;
background-color: #f0f0f0;
animation: progress 3s infinite;
}
@keyframes progress {
0% { width: 10%; }
20% { width: 90%; }
50% { width: 30%; }
60% { width: 90%; }
80% { width: 20%; }
100% { width: 10%; }
}
</style>
<script>
window.onload = function() {
var counter = 0;
var timer = document.getElementById('timer');
setInterval(function() {
counter = (counter + 0.1) % 9;
timer.textContent = counter.toFixed(1);
}, 100);
}
</script>
<div style="display: inline-block; position: relative; width: 200px; background-color: #f0f0f0; border-radius: 10px; padding: 10px; color: #333; font-family: 'Comic Sans MS', 'Comic Sans', 'Marker Felt', sans-serif;">
<span style="position: absolute; top: 0; left: 50%; transform: translate(-50%, -100%); width: 0; height: 0; border-left: 10px solid transparent; border-right: 10px solid transparent; border-bottom: 10px solid #f0f0f0;"></span>
“ add a factorial endpoint that uses math factorial ”
</div>
#### Add a factorial endpoint that uses math.factorial.
To add a factorial endpoint to the Flask application, we need to modify the `app.py` file.
Here are the steps:
1. Add a new route `/fact/<int:x>` to the Flask application.
2. In the function for this route, call `math.factorial(x)` and return the result as a string.
Here is the *edit block* for these changes:
```python
app.py
<<<<<<< HEAD
if __name__ == '__main__':
print("Starting...")
app.run()
=======
@app.route('/fact/<int:x>')
def factorial(x):
result = math.factorial(x)
return str(result)
if __name__ == '__main__':
print("Starting...")
app.run()
>>>>>>> updated
```
> Applied edit to app.py
> Commit ef9e3e7 aider: Add a factorial endpoint that uses math.factorial.
</div>
<br/>
<br/>
<br/>
```
paul-gauthier/aider/blob/main/aider/website/index.md:
```md
---
title: Home
nav_order: 1
---
<!--[[[cog
# This page is a copy of README.md, adding the front matter above.
# Remove any cog markup before inserting the README text.
text = open("README.md").read()
text = text.replace('['*3 + 'cog', ' NOOP ')
text = text.replace('['*3 + 'end', ' NOOP ')
text = text.replace(']'*3, '')
cog.out(text)
]]]-->
<!-- Edit README.md, not index.md -->
# Aider is AI pair programming in your terminal
Aider lets you pair program with LLMs,
to edit code in your local git repository.
Start a new project or work with an existing git repo.
Aider works best with GPT-4o & Claude 3.5 Sonnet and can
[connect to almost any LLM](https://aider.chat/docs/llms.html).
<p align="center">
<img
src="https://aider.chat/assets/screencast.svg"
alt="aider screencast"
>
</p>
<p align="center">
<a href="https://discord.gg/Tv2uQnR88V">
<img src="https://img.shields.io/badge/Join-Discord-blue.svg"/>
</a>
<a href="https://aider.chat/docs/install.html">
<img src="https://img.shields.io/badge/Read-Docs-green.svg"/>
</a>
</p>
## Getting started
<!-- NOOP
# We can't "include" here.
# Because this page is rendered by GitHub as the repo README
cog.out(open("aider/website/_includes/get-started.md").read())
-->
You can get started quickly like this:
```
python -m pip install aider-chat
# Change directory into a git repo
cd /to/your/git/repo
# Work with Claude 3.5 Sonnet on your repo
export ANTHROPIC_API_KEY=your-key-goes-here
aider
# Work with GPT-4o on your repo
export OPENAI_API_KEY=your-key-goes-here
aider
```
<!-- NOOP -->
See the
[installation instructions](https://aider.chat/docs/install.html)
and other
[documentation](https://aider.chat/docs/usage.html)
for more details.
## Features
- Run aider with the files you want to edit: `aider <file1> <file2> ...`
- Ask for changes:
- Add new features or test cases.
- Describe a bug.
- Paste in an error message or or GitHub issue URL.
- Refactor code.
- Update docs.
- Aider will edit your files to complete your request.
- Aider [automatically git commits](https://aider.chat/docs/git.html) changes with a sensible commit message.
- Aider works with [most popular languages](https://aider.chat/docs/languages.html): python, javascript, typescript, php, html, css, and more...
- Aider works best with GPT-4o & Claude 3.5 Sonnet and can [connect to almost any LLM](https://aider.chat/docs/llms.html).
- Aider can edit multiple files at once for complex requests.
- Aider uses a [map of your entire git repo](https://aider.chat/docs/repomap.html), which helps it work well in larger codebases.
- Edit files in your editor while chatting with aider,
and it will always use the latest version.
Pair program with AI.
- [Add images to the chat](https://aider.chat/docs/usage/images-urls.html) (GPT-4o, Claude 3.5 Sonnet, etc).
- [Add URLs to the chat](https://aider.chat/docs/usage/images-urls.html) and aider will read their content.
- [Code with your voice](https://aider.chat/docs/usage/voice.html).
## Top tier performance
[Aider has one of the top scores on SWE Bench](https://aider.chat/2024/06/02/main-swe-bench.html).
SWE Bench is a challenging software engineering benchmark where aider
solved *real* GitHub issues from popular open source
projects like django, scikitlearn, matplotlib, etc.
## More info
- [Documentation](https://aider.chat/)
- [Installation](https://aider.chat/docs/install.html)
- [Usage](https://aider.chat/docs/usage.html)
- [Tutorial videos](https://aider.chat/docs/usage/tutorials.html)
- [Connecting to LLMs](https://aider.chat/docs/llms.html)
- [Configuration](https://aider.chat/docs/config.html)
- [Troubleshooting](https://aider.chat/docs/troubleshooting.html)
- [LLM Leaderboards](https://aider.chat/docs/leaderboards/)
- [GitHub](https://github.com/paul-gauthier/aider)
- [Discord](https://discord.gg/Tv2uQnR88V)
- [Blog](https://aider.chat/blog/)
## Kind words from users
- *The best free open source AI coding assistant.* -- [IndyDevDan](https://youtu.be/YALpX8oOn78)
- *The best AI coding assistant so far.* -- [Matthew Berman](https://www.youtube.com/watch?v=df8afeb1FY8)
- *Aider ... has easily quadrupled my coding productivity.* -- [SOLAR_FIELDS](https://news.ycombinator.com/item?id=36212100)
- *It's a cool workflow... Aider's ergonomics are perfect for me.* -- [qup](https://news.ycombinator.com/item?id=38185326)
- *It's really like having your senior developer live right in your Git repo - truly amazing!* -- [rappster](https://github.com/paul-gauthier/aider/issues/124)
- *What an amazing tool. It's incredible.* -- [valyagolev](https://github.com/paul-gauthier/aider/issues/6#issue-1722897858)
- *Aider is such an astounding thing!* -- [cgrothaus](https://github.com/paul-gauthier/aider/issues/82#issuecomment-1631876700)
- *It was WAY faster than I would be getting off the ground and making the first few working versions.* -- [Daniel Feldman](https://twitter.com/d_feldman/status/1662295077387923456)
- *THANK YOU for Aider! It really feels like a glimpse into the future of coding.* -- [derwiki](https://news.ycombinator.com/item?id=38205643)
- *It's just amazing. It is freeing me to do things I felt were out my comfort zone before.* -- [Dougie](https://discord.com/channels/1131200896827654144/1174002618058678323/1174084556257775656)
- *This project is stellar.* -- [funkytaco](https://github.com/paul-gauthier/aider/issues/112#issuecomment-1637429008)
- *Amazing project, definitely the best AI coding assistant I've used.* -- [joshuavial](https://github.com/paul-gauthier/aider/issues/84)
- *I absolutely love using Aider ... It makes software development feel so much lighter as an experience.* -- [principalideal0](https://discord.com/channels/1131200896827654144/1133421607499595858/1229689636012691468)
- *I have been recovering from multiple shoulder surgeries ... and have used aider extensively. It has allowed me to continue productivity.* -- [codeninja](https://www.reddit.com/r/OpenAI/s/nmNwkHy1zG)
- *I am an aider addict. I'm getting so much more work done, but in less time.* -- [dandandan](https://discord.com/channels/1131200896827654144/1131200896827654149/1135913253483069470)
- *After wasting $100 on tokens trying to find something better, I'm back to Aider. It blows everything else out of the water hands down, there's no competition whatsoever.* -- [SystemSculpt](https://discord.com/channels/1131200896827654144/1131200896827654149/1178736602797846548)
- *Aider is amazing, coupled with Sonnet 3.5 it’s quite mind blowing.* -- [Josh Dingus](https://discord.com/channels/1131200896827654144/1133060684540813372/1262374225298198548)
- *Hands down, this is the best AI coding assistant tool so far.* -- [IndyDevDan](https://www.youtube.com/watch?v=MPYFPvxfGZs)
- *[Aider] changed my daily coding workflows. It's mind-blowing how a single Python application can change your life.* -- [maledorak](https://discord.com/channels/1131200896827654144/1131200896827654149/1258453375620747264)
- *Best agent for actual dev work in existing codebases.* -- [Nick Dobos](https://twitter.com/NickADobos/status/1690408967963652097?s=20)
<!--[[[end]]]-->
```
paul-gauthier/aider/blob/main/aider/website/share/index.md:
```md
---
nav_exclude: true
---
# Shared aider chat transcript
A user has shared the following transcript of a pair programming chat session
created using <a href="https://aider.chat">aider</a>.
Aider is a command line tool that lets you pair program with GPT-3.5 or
GPT-4, to edit code stored in your local git repository.
The transcript is based on <a id="mdurl" href="">this chat transcript data</a>.
<div class="chat-transcript" id="shared-transcript">
</div>
## Transcript format
<div class="chat-transcript" markdown="1">
> This is output from the aider tool.
#### These are chat messages written by the user.
Chat responses from GPT are in a blue font like this,
and often include colorized "diffs" where GPT is editing code:
```python
hello.py
<<<<<<< ORIGINAL
print("hello")
=======
print("goodbye")
>>>>>>> UPDATED
```
</div>
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<script>
window.onload = function() {
var urlParams = new URLSearchParams(window.location.search);
var conv = urlParams.get('mdurl');
if (!conv) {
return;
}
document.getElementById('mdurl').href = conv;
// Check if the URL is a non-raw GitHub gist
var gistRegex = /^https:\/\/gist\.github\.com\/([^\/]+)\/([a-f0-9]+)$/;
var match = gistRegex.exec(conv);
if (match) {
// If it is, convert it into a raw URL
conv = 'https://gist.githubusercontent.com/' + match[1] + '/' + match[2] + '/raw';
}
fetch(conv)
.then(response => response.text())
.then(markdown => {
// Ensure every line that starts with '>' ends with exactly 2 spaces
markdown = markdown.split('\n').map(function(line) {
if (line.startsWith('>')) {
return line.trimEnd() + ' ';
}
return line;
}).join('\n');
var html = marked.parse(markdown);
var divElement = document.querySelector('#shared-transcript');
divElement.innerHTML = html;
})
.catch(error => {
console.error('Error fetching markdown:', error);
});
}
</script>
```
paul-gauthier/aider/blob/main/scripts/blame.py:
```py
#!/usr/bin/env python3
import argparse
import subprocess
import sys
from collections import defaultdict
from datetime import datetime
from operator import itemgetter
import semver
import yaml
from tqdm import tqdm
def blame(start_tag, end_tag=None):
commits = get_all_commit_hashes_between_tags(start_tag, end_tag)
commits = [commit[:hash_len] for commit in commits]
authors = get_commit_authors(commits)
revision = end_tag if end_tag else "HEAD"
files = run(["git", "ls-tree", "-r", "--name-only", revision]).strip().split("\n")
files = [
f
for f in files
if f.endswith((".py", ".scm", ".sh", "Dockerfile", "Gemfile"))
or (f.startswith(".github/workflows/") and f.endswith(".yml"))
]
all_file_counts = {}
grand_total = defaultdict(int)
aider_total = 0
for file in files:
file_counts = get_counts_for_file(start_tag, end_tag, authors, file)
if file_counts:
all_file_counts[file] = file_counts
for author, count in file_counts.items():
grand_total[author] += count
if "(aider)" in author.lower():
aider_total += count
total_lines = sum(grand_total.values())
aider_percentage = (aider_total / total_lines) * 100 if total_lines > 0 else 0
end_date = get_tag_date(end_tag if end_tag else "HEAD")
return all_file_counts, grand_total, total_lines, aider_total, aider_percentage, end_date
def get_all_commit_hashes_between_tags(start_tag, end_tag=None):
if end_tag:
res = run(["git", "rev-list", f"{start_tag}..{end_tag}"])
else:
res = run(["git", "rev-list", f"{start_tag}..HEAD"])
if res:
commit_hashes = res.strip().split("\n")
return commit_hashes
def run(cmd):
# Get all commit hashes since the specified tag
result = subprocess.run(cmd, capture_output=True, text=True, check=True)
return result.stdout
def get_commit_authors(commits):
commit_to_author = dict()
for commit in commits:
author = run(["git", "show", "-s", "--format=%an", commit]).strip()
commit_message = run(["git", "show", "-s", "--format=%s", commit]).strip()
if commit_message.lower().startswith("aider:"):
author += " (aider)"
commit_to_author[commit] = author
return commit_to_author
hash_len = len("44e6fefc2")
def process_all_tags_since(start_tag):
tags = get_all_tags_since(start_tag)
# tags += ['HEAD']
results = []
for i in tqdm(range(len(tags) - 1), desc="Processing tags"):
start_tag, end_tag = tags[i], tags[i + 1]
all_file_counts, grand_total, total_lines, aider_total, aider_percentage, end_date = blame(
start_tag, end_tag
)
results.append(
{
"start_tag": start_tag,
"end_tag": end_tag,
"end_date": end_date.strftime("%Y-%m-%d"),
"file_counts": all_file_counts,
"grand_total": {
author: count
for author, count in sorted(
grand_total.items(), key=itemgetter(1), reverse=True
)
},
"total_lines": total_lines,
"aider_total": aider_total,
"aider_percentage": round(aider_percentage, 2),
}
)
return results
def get_latest_version_tag():
all_tags = run(["git", "tag", "--sort=-v:refname"]).strip().split("\n")
for tag in all_tags:
if semver.Version.is_valid(tag[1:]) and tag.endswith(".0"):
return tag
return None
def main():
parser = argparse.ArgumentParser(description="Get aider/non-aider blame stats")
parser.add_argument("start_tag", nargs="?", help="The tag to start from (optional)")
parser.add_argument("--end-tag", help="The tag to end at (default: HEAD)", default=None)
parser.add_argument(
"--all-since",
action="store_true",
help=(
"Find all tags since the specified tag and print aider percentage between each pair of"
" successive tags"
),
)
parser.add_argument(
"--output", help="Output file to save the YAML results", type=str, default=None
)
args = parser.parse_args()
if not args.start_tag:
args.start_tag = get_latest_version_tag()
if not args.start_tag:
print("Error: No valid vX.Y.0 tag found.")
return
if args.all_since:
results = process_all_tags_since(args.start_tag)
yaml_output = yaml.dump(results, sort_keys=True)
else:
all_file_counts, grand_total, total_lines, aider_total, aider_percentage, end_date = blame(
args.start_tag, args.end_tag
)
result = {
"start_tag": args.start_tag,
"end_tag": args.end_tag or "HEAD",
"end_date": end_date.strftime("%Y-%m-%d"),
"file_counts": all_file_counts,
"grand_total": {
author: count
for author, count in sorted(grand_total.items(), key=itemgetter(1), reverse=True)
},
"total_lines": total_lines,
"aider_total": aider_total,
"aider_percentage": round(aider_percentage, 2),
}
yaml_output = yaml.dump(result, sort_keys=True)
if args.output:
with open(args.output, "w") as f:
f.write(yaml_output)
else:
print(yaml_output)
if not args.all_since:
print(f"- Aider wrote {round(aider_percentage)}% of the code in this release.")
def get_counts_for_file(start_tag, end_tag, authors, fname):
try:
if end_tag:
text = run(["git", "blame", f"{start_tag}..{end_tag}", "--", fname])
else:
text = run(["git", "blame", f"{start_tag}..HEAD", "--", fname])
if not text:
return None
text = text.splitlines()
line_counts = defaultdict(int)
for line in text:
if line.startswith("^"):
continue
hsh = line[:hash_len]
author = authors.get(hsh, "Unknown")
line_counts[author] += 1
return dict(line_counts)
except subprocess.CalledProcessError as e:
if "no such path" in str(e).lower():
# File doesn't exist in this revision range, which is okay
return None
else:
# Some other error occurred
print(f"Warning: Unable to blame file {fname}. Error: {e}", file=sys.stderr)
return None
def get_all_tags_since(start_tag):
all_tags = run(["git", "tag", "--sort=v:refname"]).strip().split("\n")
start_version = semver.Version.parse(start_tag[1:]) # Remove 'v' prefix
filtered_tags = [
tag
for tag in all_tags
if semver.Version.is_valid(tag[1:]) and semver.Version.parse(tag[1:]) >= start_version
]
return [tag for tag in filtered_tags if tag.endswith(".0")]
def get_tag_date(tag):
date_str = run(["git", "log", "-1", "--format=%ai", tag]).strip()
return datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S %z")
if __name__ == "__main__":
main()
```
paul-gauthier/aider/blob/main/scripts/versionbump.py:
```py
#!/usr/bin/env python
import argparse
import datetime
import re
import subprocess
import sys
from packaging import version
def check_cog_pyproject():
result = subprocess.run(["cog", "--check", "pyproject.toml"], capture_output=True, text=True)
if result.returncode != 0:
print("Error: cog --check pyproject.toml failed, updating.")
subprocess.run(["cog", "-r", "pyproject.toml"])
sys.exit(1)
def main():
parser = argparse.ArgumentParser(description="Bump version")
parser.add_argument("new_version", help="New version in x.y.z format")
parser.add_argument(
"--dry-run", action="store_true", help="Print each step without actually executing them"
)
# Function to check if we are on the main branch
def check_branch():
branch = subprocess.run(
["git", "rev-parse", "--abbrev-ref", "HEAD"], capture_output=True, text=True
).stdout.strip()
if branch != "main":
print("Error: Not on the main branch.")
sys.exit(1)
# Function to check if the working directory is clean
def check_working_directory_clean():
status = subprocess.run(
["git", "status", "--porcelain"], capture_output=True, text=True
).stdout
if status:
print("Error: Working directory is not clean.")
sys.exit(1)
# Function to fetch the latest changes and check if the main branch is up to date
def check_main_branch_up_to_date():
subprocess.run(["git", "fetch", "origin"], check=True)
local_main = subprocess.run(
["git", "rev-parse", "main"], capture_output=True, text=True
).stdout.strip()
print(f"Local main commit hash: {local_main}")
origin_main = subprocess.run(
["git", "rev-parse", "origin/main"], capture_output=True, text=True
).stdout.strip()
print(f"Origin main commit hash: {origin_main}")
if local_main != origin_main:
local_date = subprocess.run(
["git", "show", "-s", "--format=%ci", "main"], capture_output=True, text=True
).stdout.strip()
origin_date = subprocess.run(
["git", "show", "-s", "--format=%ci", "origin/main"], capture_output=True, text=True
).stdout.strip()
local_date = datetime.datetime.strptime(local_date, "%Y-%m-%d %H:%M:%S %z")
origin_date = datetime.datetime.strptime(origin_date, "%Y-%m-%d %H:%M:%S %z")
if local_date < origin_date:
print(
"Error: The local main branch is behind origin/main. Please pull the latest"
" changes."
)
elif local_date > origin_date:
print(
"Error: The origin/main branch is behind the local main branch. Please push"
" your changes."
)
else:
print("Error: The main branch and origin/main have diverged.")
sys.exit(1)
args = parser.parse_args()
dry_run = args.dry_run
# Perform checks before proceeding
check_cog_pyproject()
check_branch()
check_working_directory_clean()
check_main_branch_up_to_date()
new_version_str = args.new_version
if not re.match(r"^\d+\.\d+\.\d+$", new_version_str):
raise ValueError(f"Invalid version format, must be x.y.z: {new_version_str}")
new_version = version.parse(new_version_str)
incremented_version = version.Version(
f"{new_version.major}.{new_version.minor}.{new_version.micro + 1}"
)
with open("aider/__init__.py", "r") as f:
content = f.read()
current_version = re.search(r'__version__ = "(.+?)"', content).group(1)
if new_version <= version.parse(current_version):
raise ValueError(
f"New version {new_version} must be greater than the current version {current_version}"
)
updated_content = re.sub(r'__version__ = ".+?"', f'__version__ = "{new_version}"', content)
print("Updating aider/__init__.py with new version:")
print(updated_content)
if not dry_run:
with open("aider/__init__.py", "w") as f:
f.write(updated_content)
git_commands = [
["git", "add", "aider/__init__.py"],
["git", "commit", "-m", f"version bump to {new_version}"],
["git", "tag", f"v{new_version}"],
["git", "push", "origin"],
["git", "push", "origin", f"v{new_version}"],
]
for cmd in git_commands:
print(f"Running: {' '.join(cmd)}")
if not dry_run:
subprocess.run(cmd, check=True)
updated_dev_content = re.sub(
r'__version__ = ".+?"', f'__version__ = "{incremented_version}-dev"', content
)
print()
print("Updating aider/__init__.py with new dev version:")
print(updated_dev_content)
if not dry_run:
with open("aider/__init__.py", "w") as f:
f.write(updated_dev_content)
git_commands_dev = [
["git", "add", "aider/__init__.py"],
["git", "commit", "-m", f"set version to {incremented_version}-dev"],
["git", "push", "origin"],
]
for cmd in git_commands_dev:
print(f"Running: {' '.join(cmd)}")
if not dry_run:
subprocess.run(cmd, check=True)
if __name__ == "__main__":
main()
```
</details>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters