Оптимизируйте свои подборки
Сохраняйте и классифицируйте контент в соответствии со своими настройками.
Предоставьте Gemini в Android Studio индивидуальные инструкции, используя один или несколько файлов AGENT.md . Файлы AGENT.md размещаются вместе с другими файлами в вашей кодовой базе, поэтому их легко зарегистрировать в системе контроля версий (VCS) и поделиться инструкциями, правилами стиля кодирования и другими рекомендациями для каждого проекта со всей вашей командой.
Чтобы начать, выполните следующие действия:
Создайте файл AGENT.md в любом месте файловой системы вашего проекта. Gemini сканирует текущий каталог и все родительские каталоги на наличие файлов AGENT.md при отправке запроса. Подробнее см. в разделе «Как работают файлы AGENT.md .
Добавьте инструкции. Пишите инструкции с помощью Markdown. Для удобства чтения используйте заголовки и маркеры для разных правил. См. примеры инструкций .
Сохраните и загрузите файл в систему контроля версий, чтобы поделиться им со своей командой.
Управление файлами AGENT.md как контекстом
Вы можете использовать или удалять файлы AGENT.md в качестве контекста для конкретного запроса, используя панель контекста на панели чата. Параметры файлов AGENT.md включают все файлы AGENT.md в текущем каталоге и его родительских каталогах.
Рисунок 1. Управление файлами AGENT.md как контекстом.
Примеры инструкций
Вы можете использовать файл AGENT.md для предоставления инструкций агенту. Ниже приведены несколько примеров, но предоставляемые вами инструкции должны соответствовать специфике вашего проекта.
«Основное действие — /path/to/MainActivity.kt ».
Код для поддержки навигации между экранами — path/to/navigation/UiNavigation.kt .
«Код обработки HTTP-запросов находится по адресу <path> ».
Архитектура проекта
«Разместите всю бизнес-логику в ViewModels».
Всегда следуйте официальным рекомендациям по архитектуре, включая использование многоуровневой архитектуры. Используйте однонаправленный поток данных (UDF), ViewModels, сбор состояний пользовательского интерфейса с учётом жизненного цикла и другие рекомендации.
Предпочтительные библиотеки: «Использовать библиотеку <имя библиотеки> для навигации».
Определение имен-заполнителей для общих служб API или внутренней терминологии: «Основная внутренняя служба называется „PhotoSift-API“».
Руководства по стилю компании: «Все новые компоненты пользовательского интерфейса должны быть созданы с помощью Jetpack Compose. Не предлагайте макеты на основе XML».
Модулируйте ваши файлы AGENT.md
Вы можете разбить большие файлы AGENT.md на файлы меньшего размера, которые можно использовать повторно в различных контекстах:
Выделите набор инструкций и сохраните их в другом файле Markdown, например style-guidance.md .
Ссылайтесь на файлы Markdown меньшего размера в файле AGENT.md , используя символ @ и путь к файлу, который вы хотите импортировать. Поддерживаются следующие форматы путей:
Относительные пути:
@./file.md - Импорт из того же каталога
@../file.md - Импорт из родительского каталога
@./subdirectory/file.md — импорт из подкаталога
Абсолютные пути: @/absolute/path/to/file.md
Например, следующий файл AGENT.md ссылается на два других файла инструкций:
# My AGENT.md
You are an experienced Android app developer.
@./get-started.md
## Coding style
@./shared/style-guidance.md
Как работают файлы AGENT.md
Gemini автоматически сканирует текущий каталог и родительские каталоги на наличие файлов AGENT.md и добавляет их содержимое в начало каждого запроса в качестве преамбулы. Если при отправке запроса файл не открыт, то по умолчанию включается файл AGENT.md в корне проекта (если он есть).
В чем разница между файлами AGENT.md и правилами?
Правила также позволяют определять инструкции и настройки, применяемые ко всем запросам. Однако правила определяются в файле IntelliJ /.idea/project.prompts.xml , тогда как файлы AGENT.md сохраняются рядом с исходным кодом и не зависят от среды разработки. Мы рекомендуем использовать файлы AGENT.md , если одной из основных целей является предоставление инструкций вашей команде.
Контент и образцы кода на этой странице предоставлены по лицензиям. Java и OpenJDK – это зарегистрированные товарные знаки корпорации Oracle и ее аффилированных лиц.
Последнее обновление: 2025-08-22 UTC.
[[["Прост для понимания","easyToUnderstand","thumb-up"],["Помог мне решить мою проблему","solvedMyProblem","thumb-up"],["Другое","otherUp","thumb-up"]],[["Отсутствует нужная мне информация","missingTheInformationINeed","thumb-down"],["Слишком сложен/слишком много шагов","tooComplicatedTooManySteps","thumb-down"],["Устарел","outOfDate","thumb-down"],["Проблема с переводом текста","translationIssue","thumb-down"],["Проблемы образцов/кода","samplesCodeIssue","thumb-down"],["Другое","otherDown","thumb-down"]],["Последнее обновление: 2025-08-22 UTC."],[],[],null,["# Customize Gemini using AGENT.md files\n\nGive Gemini in Android Studio customized instructions to follow using one or\nmore `AGENT.md` files. `AGENT.md` files are placed alongside the other files in\nyour codebase, so it's straightforward to check them in to your version control\nsystem (VCS) and share project-specific instructions, coding style rules, and\nother guidance with your entire team.\n\nTo get started, follow these steps:\n\n1. Create an `AGENT.md` file anywhere in your project's file system. Gemini\n scans the current directory and all parent directories for `AGENT.md` files when\n you submit a query. For more details, see [How `AGENT.md` files work](#how-agent-files-work).\n\n | **Tip:** Use multiple instruction files across different directories for more granular control over different parts of your codebase. For example, you can have a global `AGENT.md` file at the project root and more specific `AGENT.md` files in subdirectories for different modules.\n2. Add your instructions. Write your instructions using Markdown. For\n readability, consider using headings and bullet points for different rules.\n [See example instructions](#example-instructions).\n\n3. Save and commit the file to your VCS to share it with your team.\n\nManage `AGENT.md` files as context\n----------------------------------\n\nYou can apply or remove `AGENT.md` files as context for a particular query\nusing the **Context** drawer in the chat panel. The **`AGENT.md` Files** options\nincludes all `AGENT.md` files in the current directory and its parent\ndirectories.\n**Figure 1.** Manage `AGENT.md` files as context.\n\nExample instructions\n--------------------\n\nYou can use the `AGENT.md` file to give instructions to the agent. The following\nare some examples, but the instructions that you provide should be specific to\nyour project.\n\n- \"The main activity is `/path/to/MainActivity.kt`.\"\n- \"The code to support navigating between screens is `path/to/navigation/UiNavigation.kt`\"\n- \"The code handling HTTP requests is at `\u003cpath\u003e`.\"\n- Project architecture\n - \"Place all business logic in ViewModels.\"\n - \"Always follow official architecture recommendations, including use of a layered architecture. Use a unidirectional data flow (UDF), ViewModels, lifecycle-aware UI state collection, and other recommendations.\"\n- Preferred libraries: \"Use the \\\u003clibrary name\\\u003e library for navigation.\"\n- Defining placeholder names for common API services or internal terminology: \"The primary backend service is referred to as 'PhotoSift-API'.\"\n- Company style guides: \"All new UI components must be built with Jetpack Compose. Don't suggest XML-based layouts.\"\n\nModularize your `AGENT.md` files\n--------------------------------\n\nYou can break down large `AGENT.md` files into smaller files that can be reused\nin different contexts:\n\n1. Separate out a set of instructions and save them in another Markdown file,\n such as `style-guidance.md`.\n\n2. Reference the smaller Markdown files in an `AGENT.md` file by using the `@`\n symbol followed by the path to the file you want to import. The following path\n formats are supported:\n\n - Relative paths:\n - `@./file.md` - Import from the same directory\n - `@../file.md` - Import from the parent directory\n - `@./subdirectory/file.md` - Import from a subdirectory\n - Absolute paths: `@/absolute/path/to/file.md`\n\nFor example, the following `AGENT.md` file references two other instruction\nfiles: \n\n # My AGENT.md\n\n You are an experienced Android app developer.\n\n @./get-started.md\n\n ## Coding style\n\n @./shared/style-guidance.md\n\nHow `AGENT.md` files work\n-------------------------\n\nGemini automatically scans the current directory and parent directories for\n`AGENT.md` files and adds their content to the beginning of every prompt as a\npreamble. If you don't have a file open when you submit a query, then the\n`AGENT.md` file at the project root (if there is one) is included by default.\n| **Note:** If you have a `GEMINI.md` file and `AGENT.md` file in the same directory, the `GEMINI.md` file takes precedence.\n\nWhat's the difference between `AGENT.md` files and Rules?\n---------------------------------------------------------\n\n[Rules](/studio/gemini/rules) also let you define instructions and preferences\nthat apply to all prompts. However, rules are defined in the IntelliJ file\n`/.idea/project.prompts.xml`, whereas `AGENT.md` files are saved next to your\nsource code and are IDE-neutral. We recommend using `AGENT.md` files if one of\nthe primary purposes is to share the instructions with your team.\n| **Note:** Gemini combines rules and instructions in `AGENT.md` files when processing your query."]]