CodebaseGPT — это приложение, которое позволяет разработчикам "общаться" с полной кодовой базой программного проекта.

Главная особенность CodebaseGPT заключается в том, что он создает краткие описания каждого файла проекта и предоставляет эти описания LLM в первом системном промпте. Таким образом, модель имеет обобщенную информацию обо всем проекте в своем контексте на каждом этапе общения с пользователем.
Также, ? бот может загружать любой файл проекта или осуществлять поиск по кодовой базе (как семантически, так и текстово), когда это необходимо для ответа на вопрос пользователя. Он даже может обновлять файлы проекта (с подтверждением) по запросу пользователя. И, конечно же, он поддерживает все языки программирования.
Пример чата
Давайте убедимся что CodebaseGPT не выходит в интернет. CodebaseGPT будет исследовать свой собственный код:
? You: is this app accessing the web somehow? Waiting for model response... find_in_files function, query: requests.get, isCaseSensitive: False, page: 0 result: Nothing found Waiting for model response... Next input cost: $0.01 (system: $0.01, chat: $0.00) Request cost: $0.04 (input: $0.03, output: $0.00) Session cost: $0.04 ? Bot: The app does not appear to be accessing the web using the `requests.get` method, as no instances of this method were found in the project files. If the app is accessing the web, it might be using a different method or library. Would you like me to search for other common web access methods or libraries? ? You: yes please Waiting for model response... find_in_files function, query: http.client, isCaseSensitive: False, page: 0 result: Nothing found find_in_files function, query: urllib, isCaseSensitive: False, page: 0 result: Nothing found find_in_files function, query: urlopen, isCaseSensitive: False, page: 0 result: Nothing found find_in_files function, query: requests, isCaseSensitive: False, page: 0 result: Nothing found Waiting for model response... Next input cost: $0.02 (system: $0.01, chat: $0.00) Request cost: $0.04 (input: $0.04, output: $0.01) Session cost: $0.08 ? Bot: After searching for common web access methods and libraries, including `http.client`, `urllib`, `urlopen`, and `requests`, no instances of these were found in the project files. This suggests that the app does not contain code for accessing the web using these methods or libraries. If there are any other specific methods or libraries you would like me to check for, please let me know. ? You:
Да. ? прав. Понятно, что приложение обращается к OpenAI API (выходит в интернет) через родную библиотеку, но согласитесь ход его "мысли" вполне адекватный.
Основная идея
Основная идея этого проекта была в том чтобы проверить возможность управления контекстом языковой модели аналогично тому как это происходит в человеческом сознании (по крайней мере в моем). Невозможно помнить все детали относительно большого программного проекта, но можно иметь в памяти (контексте) общее понимание функций его основных компонентов, а также принцип его работы итд. Для того чтобы модель имела это "общее понимание" в первом системном промпте она получает (созданные ей ж�� на предварительном этапе) краткие описания всех файлов проекта.
Фрагмент первого системного промпта:
Project files with its descriptions: ./codebasegpt/app.py The app.py file contains the main function that initializes the app state, performs initialization, description, and chat logic based on the app state. ./codebasegpt/app_config.py app_config.py: Pydantic BaseModel for project configuration with default values for project folder, models, file inclusion/exclusion, gitignore, comments removal, and verbose logging. ./codebasegpt/app_state.py The app_state.py file contains a class AppState with attributes for app and project configurations, file paths, project state, and OpenAI integration. ...
Но если необходимо детально разобраться в некотором фрагменте приложения всегда можно посмотреть релевантные исходники. CodebaseGPT тоже это может. Для этого у него есть 3 функции которые он может вызвать, когда это необходимо для выполнения пользовательской задачи:
get_file - загрузить любой файл
find_files_semantic - найти файлы через семантический поиск
find_in_files - найти файлы через текстовый поиск
Полное описание сигнатур функций тут
Установка
Как установить и запустить проект можно прочитать в README проекта. Для его работы вам потребуется OpenAI API key.
Возможности
Мои многочисленные эксперименты с CodebaseGPT показали что он может быть очень полезным инструментом для изучения незнакомого проекта. Кстати приложение поддерживает несколько проектов, между которыми можно переключаться во время запуска приложения. Давайте посмотрим какие файлы CodebaseGPT создает чтобы работать с несколькими проектами:
? You: what files app creates to store its state/config? Waiting for model response... Next input cost: $0.02 (system: $0.01, chat: $0.00) Request cost: $0.03 (input: $0.02, output: $0.01) Session cost: $0.03 ? Bot: The CodebaseGPT software project creates and uses the following files to store its state and configuration: 1. `./codebasegpt/app_config.py`: This file contains a Pydantic BaseModel for project configuration with default values for various settings such as project folder, models, file inclusion/exclusion, gitignore, comments removal, and verbose logging. 2. `./codebasegpt/app_state.py`: This file contains a class `AppState` with attributes for app and project configurations, file paths, project state, and OpenAI integration. It is likely used to hold the current state of the application during runtime. 3. `./codebasegpt/proj_config.py`: This file defines a Pydantic model for project configuration with attributes such as path, include, exclude, gitignore, and remove_comments. It is used to store configuration settings specific to the project. 4. `./codebasegpt/proj_state.py`: This file defines data models for the project file state, including file paths, modification times, descriptions, and embedded data. It is used to store the state of the project files. 5. `./codebasegpt/utils.py`: Although not a state or config file itself, this module provides functions for loading, saving, and manipulating JSON data for application and project configurations and states. It is likely that this module handles the reading and writing of state and configuration data to and from JSON files. The actual JSON files or other storage files that hold the persistent state and configuration data are not explicitly listed, but they would be managed by the modules mentioned above and likely reside within the project directory or a specified path. ? You: please check the source code and answer me where and how this files stored Waiting for model response... find_in_files function, query: save, isCaseSensitive: False, page: 0 result: codebasegpt/desc_logic.py 5 from .utils import get_proj_state_path, load_proj_state, save_proj_state 21 save_proj_state(proj_desc, app_state.app_config.proj_folder) 93 save_proj_state(proj_state, app_state.app_config.proj_folder) codebasegpt/init_logic.py 16 save_app_config, save_proj_config 24 save_app_config(AppConfig()) 134 save_proj_config(proj_config, proj_folder) 156 save_app_config(app_config) codebasegpt/utils.py 15 def save_app_config(app_config: AppConfig): 28 def save_proj_config(proj_config: ProjConfig, proj_folder: str): 41 def save_proj_state(proj_state: ProjState, proj_folder: str): Waiting for model response... get_file function, path: codebasegpt/utils.py returned codebasegpt/utils.py file content get_file function, path: codebasegpt/app_config.py returned codebasegpt/app_config.py file content get_file function, path: codebasegpt/proj_config.py returned codebasegpt/proj_config.py file content Waiting for model response... Next input cost: $0.03 (system: $0.01, chat: $0.02) Request cost: $0.09 (input: $0.07, output: $0.01) Session cost: $0.11 ? Bot: The CodebaseGPT software project stores its state and configuration in JSON files. The `utils.py` file contains functions that handle the saving of these JSON files: 1. `save_app_config(app_config: AppConfig)`: This function saves the application configuration to a JSON file named `app_config.json`. The path to this file is constructed using the `data_root` directory and the filename. 2. `save_proj_config(proj_config: ProjConfig, proj_folder: str)`: This function saves the project configuration to a JSON file named `proj_config.json`. The path to this file is constructed using the `data_root` directory, the project folder name, and the filename. 3. `save_proj_state(proj_state: ProjState, proj_folder: str)`: This function saves the project state to a JSON file named `proj_state.json`. The path to this file is constructed using the `data_root` directory, the project folder name, and the filename. The `data_root` directory is defined in the `app_const.py` file, which is not provided in the content above, but it is used as the base directory for storing these JSON files. The `app_config.py` file defines the `AppConfig` class, which includes attributes for the project folder, description model, chat model, and other settings. The `proj_config.py` file defines the `ProjConfig` class, which includes attributes for the project path, include and exclude patterns, gitignore, and remove_comments settings. The actual JSON files (`app_config.json`, `proj_config.json`, and `proj_state.json`) are stored in the `data_root` directory, with `proj_config.json` and `proj_state.json` being stored in a subdirectory named after the project folder. The `utils.py` file provides functions to ensure the existence of these directories and to save the configuration and state data in the appropriate locations. ? You: draw me this folders/files structure please Waiting for model response... Next input cost: $0.03 (system: $0.01, chat: $0.02) Request cost: $0.04 (input: $0.04, output: $0.01) Session cost: $0.16 ? Bot: Certainly! Here's a representation of the folders and files structure for the CodebaseGPT software project's state and configuration storage: ``` data_root/ (The base directory for storing configuration and state files) │ ├── app_config.json (Stores the application configuration) │ └── [proj_folder]/ (A subdirectory named after the project folder) │ ├── proj_config.json (Stores the project configuration) │ └── proj_state.json (Stores the project state) ``` In this structure, `data_root` is a placeholder for the actual directory path defined in the `app_const.py` file. The `[proj_folder]` is a variable directory name that represents the name of the specific project folder for which the configuration and state are being stored. Each project will have its own subdirectory under `data_root` containing its `proj_config.json` and `proj_state.json` files. ? You: what actual data_root value? Waiting for model response... get_file function, path: codebasegpt/app_const.py returned codebasegpt/app_const.py file content Waiting for model response... Next input cost: $0.04 (system: $0.01, chat: $0.02) Request cost: $0.08 (input: $0.08, output: $0.01) Session cost: $0.24 ? Bot: The actual `data_root` value is set to `'./_data'`. This means that the configuration and state JSON files are stored in a directory named `_data` at the root of the project. Here is the updated folders/files structure with the actual `data_root` value: ``` ./_data/ (The base directory for storing configuration and state files) │ ├── app_config.json (Stores the application configuration) │ └── [proj_folder]/ (A subdirectory named after the project folder) │ ├── proj_config.json (Stores the project configuration) │ └── proj_state.json (Stores the project state) ``` In this structure, `./_data` is the directory where the `app_config.json`, `proj_config.json`, and `proj_state.json` files are located. The `[proj_folder]` is a placeholder for the name of the project folder. ? You:
Рассмотрим действия ? бота поэтапно:
В ответ на первый запрос ? выдал очень релевантный ответ на основе описаний файлов из первого системного промпта.
В ответ на второй, уточняющий, вопрос ? зачем-то начал искать в коде по строке "save" и получил вхождения строки в файлах "desc_logic.py", "init_logic.py" и "utils.py". Далее ? понял что ошибся и решил загрузить 3 файла (лишь один из них из результатов поиска): "utils.py", "app_config.py", "proj_config.py".
Далее ? перечисляет 3 файла которые создает CodebaseGPT и функции которые это делают и это абсолютно точный ответ!
Но я хочу большего - чтобы ? нарисовал дерево этих папок и файлов. И ? рисует! Но не находит как называется корневая папка (ее имя в отдельном файле констант)
Я прошу найти значение этой константы. И ? с этим конечно справляется.
Я считаю подобный результат более чем достойным.
Как видно из лога все это общение стоило $0.24 при использовании модели gpt-4-1106-preview. Модель gpt-3.5-turbo-1106 работает значительно хуже и я не использую ее для чата. Впрочем этой модели более чем хватает для создания описаний файлов. И так как эта модель стоит в 20 раз дешевле - то описания файлов создаются практически бесплатно.
Масштабирование
Можно сказать что это маленький проект (50кб исходного кода) и не понятно как он будет работать с проектами практического размера. Я максимально тестировал на проекте в 20 раз больше этого (1Мб исходного кода) и могу сказать что результат был аналогичный. Впрочем нужно понимать что у модели ограниченный размер контекста и больше примерно 400кб загруженных одновременно файлов она не способна обрабатывать. Поэтому если у вас в проекте есть файлы больше 40кб то программа выдаст предупреждение при инициализации. Один из способов уменьшить размер файлов - включить опцию "remove_comments" в proj_config.json. Позволяет уменьшить размер файла в случае например если закомментированы значительные фрагменты кода.
Также нужно отметить, что стоимость использования приложением прямо пропорциональна размеру исследуемого проекта. Но опять же нужно понимать, что цены на LLM падают достаточно быстро.
В последней версии приложения в файл конфигурации проекта добавлен новый параметр - desc_mode. Он задает режим создания и использования описаний файлов исследуемого проекта. Поддерживаются три значения:
desc- стандартный режим. Описание файла составляет примерно 10% его размера.desc_2- описания файлов примерно вдвое короче, чем в стандартном режиме.desc_no- описания не создаются и не используются.
Таким образом, desc_2 позволяет создать менее детальное (но занимающее меньше токенов) описание проекта. Этот режим может быть полезен при работе с более крупными проектами.
В случае desc_no описания файлов не создаются вовсе, и в первом системном промпте модель получает только список файлов. Интересно, что для решения простых задач этот режим тоже неплохо работает. То есть модель способна понять назначение файла просто по его имени и папке, в которой он находится, что само по себе довольно удивительно.
README.md
В README проекта описаны прочие аспекты работы с приложением, такие как формат конфигурационных файлов и поддерживаемые команды, поэтому не буду дублировать это здесь.
Резюме
Я полагаю, что этот инструмент может стать хорошим помощником для разработчика, когда необходимо разобраться в неизвестном проекте. Возможно, он также поможет новым сотрудникам быстрее включиться в работу над проектом.
Чтобы понять, насколько он может быть полезен именно вам, лучший способ — это попробовать его использовать.
Будет интересно получить обратную связь от сообщества. Отвечу всем в комментариях.
Если вам нужна консультация или совет, то у меня есть наработки по применению моделей OpenAI для решения очень разных задач. Пишите в комментариях или в личку, постараюсь помочь.
