Оперативные стратегии проектирования

Prompt design is the process of creating prompts, or natural language requests, that elicit accurate, high quality responses from a language model.

This page introduces basic concepts, strategies, and best practices to get you started designing prompts to get the most out of Gemini AI models.

Тематические руководства по заданиям

Looking for more specific prompt strategies? Check out our other prompting guides on:

You can find other sample prompts in the prompt gallery meant to interactively showcase many of the concepts shared in this guide.

Четкие и конкретные инструкции

Эффективный и действенный способ настройки поведения модели — это предоставление ей четких и конкретных инструкций. Инструкции могут быть представлены в форме вопроса, пошаговых заданий или даже в сложной форме, например, в виде описания опыта и образа мышления пользователя.

Вход

Входными данными является обязательный текст в подсказке, на который вы хотите, чтобы модель дала ответ. Входными данными могут быть вопрос, на который модель отвечает (входные данные вопроса), задача, которую модель выполняет (входные данные задачи), сущность, с которой модель работает (входные данные сущности), или частичные входные данные, которые модель дополняет или продолжает (входные данные завершения).

Тип ввода Быстрый Сгенерированный вывод
Вопрос

    What's a good name for a flower shop that specializes in selling bouquets of
    dried flowers? Create a list of 5 options with just the names.

    Here are 5 names for a flower shop specializing in dried flowers:

    1. Everlasting Blooms
    2. Dried & Delightful
    3. The Petal Preserve
    4. Whispers of Wildflowers
    5. Forever Blooms
    
Задача
    Give me a simple list of just the things that I must bring on a camping trip. The list should have 5 items.
    1. **Tent:** Your shelter from the elements.
    2. **Sleeping Bag:** Stay warm and comfortable.
    3. **Sleeping Pad:** Insulation and cushioning for a good night's sleep.
    4. **Headlamp or Flashlight:** Light for nighttime activities.
    5. **First Aid Kit:** Be prepared for minor injuries.
Сущность

    Classify the following items as [large, small]:
Elephant
Mouse
Snail

Here's the classification:

* **Elephant:** Large
* **Mouse:** Small
* **Snail:** Small
    

Частичное завершение ввода

Генеративные языковые модели работают как продвинутый инструмент автозаполнения. Когда вы предоставляете часть контента, модель может предоставить оставшуюся часть контента или то, что она считает продолжением этого контента, в качестве ответа. При этом, если вы приводите какие-либо примеры или контекст, модель может учесть эти примеры или контекст.

The following example provides a prompt with an instruction and an entity input:

For the given order, return a JSON object that has the fields cheeseburger, hamburger, fries, or
drink, with the value being the quantity.

Order: A burger and a drink.
  
{
  "cheeseburger": 0,
  "hamburger": 1,
  "fries": 0,
  "drink": 1
}
  

Хотя модель и выполнила запрос, написание инструкций на естественном языке иногда может быть сложной задачей и оставляет много места для интерпретации модели. Например, меню ресторана может содержать много позиций. Чтобы уменьшить размер JSON-ответа, вероятно, следует исключить позиции, которые не были заказаны. В этом случае можно указать пример и префикс ответа и позволить модели завершить его:

Valid fields are cheeseburger, hamburger, fries, and drink.
Order: Give me a cheeseburger and fries
Output:
```
{
  "cheeseburger": 1,
  "fries": 1
}
```
Order: I want two burgers, a drink, and fries.
Output:
  
```
{
  "hamburger": 2,
  "drink": 1,
  "fries": 1
}
```
  

Notice how "cheeseburger" was excluded from the output because it wasn't a part of the order.

Хотя вы можете указать формат простых объектов JSON-ответа с помощью подсказок, мы рекомендуем использовать функцию структурированного вывода API Gemini при указании более сложной схемы JSON для ответа.

Ограничения

Укажите любые ограничения на чтение запроса или генерацию ответа. Вы можете указать модели, что делать, а что нет. Например, вы можете указать в запросе ограничение на желаемую длину резюме:

Summarize this text in one sentence:
Text: A quantum computer exploits quantum mechanical phenomena to perform calculations exponentially
faster than any modern traditional computer. At very tiny scales, physical matter acts as both
particles and as waves, and quantum computing uses specialized hardware to leverage this behavior.
The operating principles of quantum devices is beyond the scope of classical physics. When deployed
at scale, quantum computers could be used in a wide variety of applications such as: in
cybersecurity to break existing encryption methods while helping researchers create new ones, in
meteorology to develop better weather forecasting etc. However, the current state of the art quantum
computers are still largely experimental and impractical.
    

      Exploiting quantum mechanical phenomena, quantum computers can perform calculations exponentially faster than traditional computers for potential applications like cybersecurity and meteorology, although they are currently largely experimental and impractical.
    

Формат ответа

Вы можете задать инструкции, определяющие формат ответа. Например, вы можете попросить отформатировать ответ в виде таблицы, маркированного списка, краткой презентации, ключевых слов, предложения или абзаца. Следующая инструкция системы указывает модели на необходимость более разговорного стиля ответа:

    All questions should be answered comprehensively with details, unless the user requests a concise response specifically.
  
    What is a smart way to make a business that sells DVD's in 2026?
  
Starting a business selling DVDs in 2026 presents significant challenges due to the overwhelming dominance of digital streaming and on-demand services; a "smart" approach would therefore require a highly specialized niche, a strong value proposition beyond just the disc, and likely a focus on community or collector markets rather than mainstream consumption.

Here's a breakdown of what a smart DVD business in 2026 would likely entail:

1. Extreme Niche Specialization: You cannot compete with streaming libraries. Your business must focus on what digital doesn't offer easily or at all. This could include:

    * Out-of-Print & Rare Titles: Sourcing films or TV shows that have never been released digitally or are currently unavailable on major streaming platforms.
    ....
  

Форматируйте ответы, используя стратегию автозаполнения.

The completion strategy can also help format the response. The following example prompts the model to create an essay outline:

Create an outline for an essay about hummingbirds.
  
Here is a possible outline for an essay about hummingbirds:

I. Introduction
A. Hook: Start with a captivating fact or description about hummingbirds (e.g., their speed, iridescent colors, or tiny size).
B. Background: Briefly introduce hummingbirds – where they are found (Americas), their reputation as unique birds.
C. Thesis Statement: State the main point of the essay, which could be about the remarkable adaptations, behaviors, and ecological importance of hummingbirds.

II. Appearance and Identification
.....
  

В запросе не был указан формат для плана, и модель выбрала формат за вас. Чтобы модель вернула план в определенном формате, вы можете добавить текст, представляющий начало плана, и позволить модели завершить его на основе заданного вами шаблона.

Create an outline for an essay about hummingbirds.
I. Introduction
   *
  
Okay, here is an outline for an essay about hummingbirds, starting from the introduction you provided:

I. Introduction
* Hook: Start with a captivating fact or description about hummingbirds (e.g., their speed, iridescent colors, or tiny size).
* Background: Briefly introduce hummingbirds – where they are found (Americas), their reputation as unique birds, and their general characteristics.
* Thesis Statement: State the main point of the essay, focusing on the remarkable adaptations, behaviors, and ecological significance that make hummingbirds extraordinary.
.....
  

Вопросы с нулевым количеством ответов против вопросов с небольшим количеством ответов

В задание можно включить примеры, демонстрирующие модели, как выглядит правильный ответ. Модель пытается выявить закономерности и взаимосвязи в примерах и применяет их при генерации ответа. Задания, содержащие несколько примеров, называются заданиями с малым количеством примеров, а задания, не содержащие примеров, — заданиями без примеров . Задания с малым количеством примеров часто используются для регулирования форматирования, формулировок, области действия или общей структуры ответов модели. Используйте конкретные и разнообразные примеры, чтобы помочь модели сузить фокус и получить более точные результаты.

Мы рекомендуем всегда включать в ваши задания примеры, демонстрирующие выполнение нескольких заданий. Задания без таких примеров, скорее всего, будут менее эффективными. На самом деле, вы можете вообще убрать инструкции из задания, если ваши примеры достаточно наглядно показывают суть задачи.

The following zero-shot prompt asks the model to choose the best explanation.

Please choose the best explanation to the question:

Question: How is snow formed?
Explanation1: Snow is formed when water vapor in the air freezes into ice
crystals in the atmosphere, which can combine and grow into snowflakes as they
fall through the atmosphere and accumulate on the ground.
Explanation2: Water vapor freezes into ice crystals forming snow.
Answer:
  
Explanation1 is the better explanation because it provides more detail on the
process, including how ice crystals combine and grow into snowflakes as they
fall through the atmosphere.
  

If your use case requires the model to produce concise responses, you can include examples in the prompt that give preference to concise responses.

В следующем задании приведены два примера, демонстрирующие предпочтение более кратким объяснениям. В ответе видно, что примеры помогли модели выбрать более короткое объяснение ( Explanation2 ), а не более длинное объяснение ( Explanation1 ), как это было ранее.

Below are some examples showing a question, explanation, and answer format:

Question: Why is the sky blue?
Explanation1: The sky appears blue because of Rayleigh scattering, which causes
shorter blue wavelengths of light to be scattered more easily than longer red
wavelengths, making the sky look blue.
Explanation2: Due to Rayleigh scattering effect.
Answer: Explanation2

Question: What is the cause of earthquakes?
Explanation1: Sudden release of energy in the Earth's crust.
Explanation2: Earthquakes happen when tectonic plates suddenly slip or break
apart, causing a release of energy that creates seismic waves that can shake the
ground and cause damage.
Answer: Explanation1

Now, Answer the following question given the example formats above:

Question: How is snow formed?
Explanation1: Snow is formed when water vapor in the air freezes into ice
crystals in the atmosphere, which can combine and grow into snowflakes as they
fall through the atmosphere and accumulate on the ground.
Explanation2: Water vapor freezes into ice crystals forming snow.
Answer:
  
Answer: Explanation2
  

Оптимальное количество примеров

Модели, подобные Gemini, часто способны выявлять закономерности, используя всего несколько примеров, хотя для достижения наилучших результатов вам, возможно, потребуется поэкспериментировать с количеством примеров, которые следует указать в задании. В то же время, если вы включите слишком много примеров, модель может начать переобучаться на основе полученных данных.

Единое форматирование

Убедитесь, что структура и форматирование примеров, содержащих несколько примеров, одинаковы, чтобы избежать ответов с нежелательным форматом. Одна из основных целей добавления таких примеров в подсказки — показать модели формат ответа. Поэтому крайне важно обеспечить единообразный формат во всех примерах, особенно обращая внимание на XML-теги, пробелы, переносы строк и разделители примеров.

Добавить контекст

В запросе можно указать инструкции и информацию, необходимые модели для решения задачи, вместо того чтобы предполагать, что модель уже обладает всей необходимой информацией. Эта контекстная информация помогает модели понять ограничения и детали того, что вы от нее требуете.

The following example asks the model to give troubleshooting guidance for a router:

What should I do to fix my disconnected wifi? The light on my Google
Wifi router is yellow and blinking slowly.
  
  A yellow blinking light on your Google Wifi router usually indicates a problem
  with the internet connection. Here are some steps to troubleshoot and fix the
  issue:
  1. Restart your router and modem:
    - Unplug your modem from the power outlet and wait for 30 seconds.
    - Plug your modem back in and wait for it to fully boot up.
    - Unplug your Google Wifi router and wait for 30 seconds.
    - Plug your Google Wifi router back in and wait for it to fully boot up.
.....
  

The response looks like generic troubleshooting information that's not specific to the router or the status of the LED indicator lights.

To customize the response for the specific router, you can add to the prompt the router's troubleshooting guide as context for it to refer to when providing a response.

Answer the question using the text below. Respond with only the text provided.
Question: What should I do to fix my disconnected wifi? The light on my Google Wifi router is yellow and blinking slowly.

Text:
Color: Slowly pulsing yellow
What it means: There is a network error.
What to do:
Check that the Ethernet cable is connected to both your router and your modem and both devices are turned on. You might need to unplug and plug in each device again.

Color: Fast blinking yellow
What it means: You are holding down the reset button and are factory resetting this device.
What to do:
If you keep holding down the reset button, after about 12 seconds, the light will turn solid yellow. Once it is solid yellow, let go of the factory reset button.

Color: Solid yellow
What it means: Router is factory resetting.
What to do:
This can take up to 10 minutes. When it's done, the device will reset itself and start pulsing white, letting you know it's ready for setup.

Color: Solid red
What it means: Something is wrong.
What to do:
Critical failure. Factory reset the router. If the light stays red, contact Wifi customer support.
  
Check that the Ethernet cable is connected to both your router and your modem and both devices are turned on. You might need to unplug and plug in each device again.
  

Разбейте подсказки на компоненты.

For use cases that require complex prompts, you can help the model manage this complexity by breaking things down into simpler components.

  1. Break down instructions: Instead of having many instructions in one prompt, create one prompt per instruction. You can choose which prompt to process based on the user's input.

  2. Последовательность подсказок: Для сложных задач, включающих несколько последовательных шагов, каждый шаг следует рассматривать как подсказку, а подсказки — как последовательность. В этой последовательной цепочке подсказок результат одной подсказки становится входом следующей. Результат последней подсказки в последовательности является окончательным результатом.

  3. Агрегирование ответов: Агрегирование — это выполнение различных параллельных задач над разными частями данных и объединение результатов для получения конечного результата. Например, вы можете указать модели выполнить одну операцию над первой частью данных, другую — над оставшейся частью данных и агрегировать результаты.

Экспериментируйте с параметрами модели.

Каждый вызов модели включает значения параметров, которые определяют, как модель генерирует ответ. Модель может генерировать разные результаты для разных значений параметров. Экспериментируйте с различными значениями параметров, чтобы найти оптимальные значения для задачи. Доступные параметры для разных моделей могут отличаться. Наиболее распространенные параметры следующие:

  1. Max output tokens: Specifies the maximum number of tokens that can be generated in the response. A token is approximately four characters. 100 tokens correspond to roughly 60-80 words.

  2. Температура: Температура контролирует степень случайности при выборе токенов. Температура используется для выборки во время генерации ответов, которая происходит при применении topP и topK . Более низкие температуры подходят для запросов, требующих более детерминированного или менее открытого ответа, в то время как более высокие температуры могут привести к более разнообразным или креативным результатам. Температура 0 является детерминированной, то есть всегда выбирается ответ с наибольшей вероятностью.

  3. topK : Параметр topK изменяет способ выбора токенов для выходных данных. Значение topK равное 1, означает, что выбранный токен является наиболее вероятным среди всех токенов в словаре модели (также называемое жадным декодированием), а значение topK равное 3, означает, что следующий токен выбирается из числа 3 наиболее вероятных с использованием температуры. На каждом этапе выбора токенов отбираются topK токенов с наивысшими вероятностями. Затем токены дополнительно фильтруются на основе topP , и последний токен выбирается с использованием выборки по температуре.

  4. topP : Параметр topP изменяет способ выбора токенов моделью для выходных данных. Токены выбираются от наиболее вероятных к наименее вероятным до тех пор, пока сумма их вероятностей не сравняется со значением topP . Например, если токены A, B и C имеют вероятность 0,3, 0,2 и 0,1, а значение topP равно 0,5, то модель выберет либо A, либо B в качестве следующего токена, используя температуру, и исключит C из числа кандидатов. Значение topP по умолчанию равно 0,95.

  5. stop_sequences : Задайте стоп-последовательность, чтобы сообщить модели о необходимости прекратить генерацию контента. Стоп-последовательность может быть любой последовательностью символов. Старайтесь избегать использования последовательностей символов, которые могут встречаться в генерируемом контенте.

Стратегии быстрой итерации

Разработка подсказок иногда требует нескольких итераций, прежде чем вы сможете стабильно получать желаемый ответ. В этом разделе приведены рекомендации по некоторым моментам, которые вы можете попробовать при доработке ваших подсказок:

  1. Используйте разные формулировки: Использование разных слов или фраз в ваших вопросах часто приводит к разным ответам от модели, даже если все они означают одно и то же. Если вы не получаете ожидаемых результатов от своего вопроса, попробуйте переформулировать его.

    Version 1:
    How do I bake a pie?
    
    Version 2:
    Suggest a recipe for a pie.
    
    Version 3:
    What's a good pie recipe?
      

  2. Switch to an analogous task: If you can't get the model to follow your instructions for a task, try giving it instructions for an analogous task that achieves the same result.

    This prompt tells the model to categorize a book by using predefined categories:

    Which category does The Odyssey belong to:
    thriller
    sci-fi
    mythology
    biography
      
        The Odyssey belongs to the category of **mythology**. 
    
        Here's why:
    
        * **Mythology:** The Odyssey tells the story of Odysseus, a hero from Greek mythology, and his
        journey home after the Trojan War. It features gods, monsters, and supernatural events common to
        Greek mythology.
    .....
      

    Ответ правильный, но модель не уложилась в предложенные варианты. Также вам нужно, чтобы модель отвечала только одним из вариантов, а не полным предложением. В этом случае вы можете переформулировать инструкцию в виде вопроса с несколькими вариантами ответа и попросить модель выбрать один из них.

    Multiple choice problem: Which of the following options describes the book The Odyssey?
    Options:

    • thriller
    • sci-fi
    • mythology
    • biography
    The correct answer is mythology. 
    
  3. Change the order of prompt content: The order of the content in the prompt can sometimes affect the response. Try changing the content order and see how that affects the response.

    Version 1:
    [examples]
    [context]
    [input]
    
    Version 2:
    [input]
    [examples]
    [context]
    
    Version 3:
    [examples]
    [input]
    [context]
    

Резервные варианты ответов

Резервный ответ — это ответ, возвращаемый моделью, когда запрос или ответ запускают защитный фильтр. Примером резервного ответа может служить фраза: «Я не могу вам помочь, так как я всего лишь языковая модель».

If the model responds with a fallback response, try increasing the temperature.

Заземление и выполнение кода

Gemini is able to use tools to avoid hallucinations in scenarios where it might otherwise produce incorrect responses.

Grounding with Google Search connects the Gemini model to real-time web content, and should be enabled whenever the model may need to know obscure or recent facts.

Gemini's code execution tool enables the model to generate and run Python code, and should be enabled whenever the model needs to perform any kind of arithmetic, counting, or calculation.

Близнецы 3

Модели Gemini 3 разработаны для развития сложных навыков логического мышления и следования инструкциям. Они лучше всего реагируют на прямые, хорошо структурированные подсказки, четко определяющие задачу и любые ограничения. Для достижения оптимальных результатов с моделями Gemini 3 рекомендуются следующие методы:

Основные принципы подсказок

  • Be precise and direct: State your goal clearly and concisely. Avoid unnecessary or overly persuasive language.
  • Используйте согласованную структуру: применяйте четкие разделители для разделения различных частей вашего запроса. Эффективны теги в стиле XML (например, <context> , <task> ) или заголовки Markdown. Выберите один формат и используйте его последовательно в рамках одного запроса.
  • Define parameters: Explicitly explain any ambiguous terms or parameters.
  • Регулировка детализации вывода: по умолчанию модели Gemini 3 предоставляют прямые и оперативные ответы. Если вам нужен более развернутый или подробный ответ, необходимо явно указать это в инструкциях.
  • Handle multimodal inputs coherently: When using text, images, audio, or video, treat them as equal-class inputs. Ensure your instructions clearly reference each modality as needed.
  • Расставьте приоритеты для важных инструкций: укажите основные поведенческие ограничения, определения ролей (персоны) и требования к формату вывода в инструкции к системе или в самом начале запроса к пользователю.
  • Структура для длинных текстов: При предоставлении большого объема контекста (например, документов, кода) сначала изложите весь контекст. Конкретные инструкции или вопросы размещайте в самом конце вопроса.
  • Закрепление контекста: После большого блока данных используйте понятную переходную фразу, чтобы связать контекст и ваш запрос, например: «На основании приведенной выше информации...»

Стратегии Gemini 3 Flash

  • Точность по текущему дню: добавьте в инструкции системы следующий пункт, чтобы модель учитывала, что текущий день приходится на 2026 год:

    For time-sensitive user queries that require up-to-date information, you
    MUST follow the provided current time (date and year) when formulating
    search queries in tool calls. Remember it is 2026 this year.
    
  • Knowledge cutoff accuracy: Add the following clause to the system instructions to make the model aware of its knowledge cutoff:

    Your knowledge cutoff date is January 2025.
    
  • Обеспечение корректной работы: добавьте следующий пункт в инструкции системы (с соответствующими изменениями), чтобы улучшить способность модели корректно интерпретировать ответы в заданном контексте:

    You are a strictly grounded assistant limited to the information provided in
    the User Context. In your answers, rely **only** on the facts that are
    directly mentioned in that context. You must **not** access or utilize your
    own knowledge or common sense to answer. Do not assume or infer from the
    provided facts; simply report them exactly as they appear. Your answer must
    be factual and fully truthful to the provided text, leaving absolutely no
    room for speculation or interpretation. Treat the provided context as the
    absolute limit of truth; any facts or details that are not directly
    mentioned in the context must be considered **completely untruthful** and
    **completely unsupported**. If the exact answer is not explicitly written in
    the context, you must state that the information is not available.
    

Улучшение логического мышления и планирования.

Модели серий Gemini 2.5 и 3 автоматически генерируют внутренний «размышленийный» текст для повышения эффективности рассуждений. Таким образом, обычно нет необходимости в том, чтобы модель описывала, планировала или подробно описывала этапы рассуждений в самом возвращаемом ответе. Для задач, требующих сложных рассуждений, простые запросы, такие как «Тщательно подумайте, прежде чем отвечать», могут повысить производительность, хотя и за счет дополнительных токенов для размышлений.

Более подробную информацию можно найти в документации по мышлению Близнецов .

Примеры структурированных подсказок

Использование тегов или Markdown помогает модели различать инструкции, контекст и задачи.

Пример XML:

<role>
You are a helpful assistant.
</role>

<constraints>
1. Be objective.
2. Cite sources.
</constraints>

<context>
[Insert User Input Here - The model knows this is data, not instructions]
</context>

<task>
[Insert the specific user request here]
</task>

Пример Markdown:

# Identity
You are a senior solution architect.

# Constraints
- No external libraries allowed.
- Python 3.11+ syntax only.

# Output format
Return a single code block.

Пример шаблона, объединяющего лучшие практики.

Этот шаблон отражает основные принципы использования подсказок в Gemini 3. Всегда вносите изменения и дорабатывайте шаблон под конкретные задачи.

Системная инструкция:

<role>
You are Gemini 3, a specialized assistant for [Insert Domain, e.g., Data Science].
You are precise, analytical, and persistent.
</role>

<instructions>
1. **Plan**: Analyze the task and create a step-by-step plan.
2. **Execute**: Carry out the plan.
3. **Validate**: Review your output against the user's task.
4. **Format**: Present the final answer in the requested structure.
</instructions>

<constraints>
- Verbosity: [Specify Low/Medium/High]
- Tone: [Specify Formal/Casual/Technical]
</constraints>

<output_format>
Structure your response as follows:
1. **Executive Summary**: [Short overview]
2. **Detailed Response**: [The main content]
</output_format>

Запрос пользователя:

<context>
[Insert relevant documents, code snippets, or background info here]
</context>

<task>
[Insert specific user request here]
</task>

<final_instruction>
Remember to think step-by-step before answering.
</final_instruction>

Агентские рабочие процессы

Для сложных агентных рабочих процессов часто требуются конкретные инструкции для управления тем, как модель рассуждает, планирует и выполняет задачи. Хотя Gemini обеспечивает высокую общую производительность, для сложных агентов часто требуется настройка компромисса между вычислительными затратами (задержка и токены) и точностью выполнения задач.

When designing prompts for agents, consider the following dimensions of behavior that you can steer in the agent:

Рассуждения и стратегия

Настройка того, как модель мыслит и планирует действия перед их выполнением.

  • Логическая декомпозиция: определяет, насколько тщательно модель должна анализировать ограничения, предварительные условия и порядок выполнения операций.
  • Диагностика проблемы : контролирует глубину анализа при выявлении причин и использование моделью абдуктивного рассуждения. Определяет, следует ли модели принять наиболее очевидный ответ или исследовать сложные, менее вероятные объяснения.
  • Информационная полнота: компромисс между анализом всех доступных политик и документов и приоритетом эффективности и скорости.

Исполнение и надежность

Настройки, определяющие, как агент работает автономно и преодолевает препятствия.

  • Адаптируемость: то, как модель реагирует на новые данные. Определяет, должна ли она строго придерживаться своего первоначального плана или немедленно изменить курс, если наблюдения противоречат предположениям.
  • Устойчивость и восстановление: степень, в которой модель пытается самостоятельно исправлять ошибки. Высокая устойчивость повышает вероятность успеха, но увеличивает риск более высоких затрат токенов или зацикливания.
  • Оценка рисков: логика оценки последствий. Четко различает действия с низким риском (чтения) и изменения состояния с высоким риском (записи).

Взаимодействие и результат

Настройки способа взаимодействия агента с пользователем и форматирования результатов.

  • Обработка неоднозначностей и разрешений: определяет, когда модели разрешено делать предположения, а когда она должна приостановить выполнение, чтобы запросить у пользователя разъяснения или разрешение.
  • Многословность: Регулирует громкость текста, генерируемого вместе с вызовами инструментов. Это определяет, будет ли модель объяснять свои действия пользователю или останется безмолвной во время выполнения.
  • Точность и полнота: требуемая достоверность выходных данных. Указывает, должна ли модель учитывать каждый крайний случай и предоставлять точные значения, или же допустимы приблизительные оценки.

Шаблон системной инструкции

Приведенная ниже инструкция представляет собой пример, оцененный исследователями для повышения производительности в тестах на агентных моделях, где модель должна следовать сложному своду правил и взаимодействовать с пользователем. Она побуждает агента действовать как сильный рассуждающий и планирующий субъект, обеспечивает определенное поведение по всем перечисленным выше параметрам и требует от модели заблаговременного планирования перед принятием каких-либо действий.

Вы можете адаптировать этот шаблон под конкретные задачи.

You are a very strong reasoner and planner. Use these critical instructions to structure your plans, thoughts, and responses.

Before taking any action (either tool calls *or* responses to the user), you must proactively, methodically, and independently plan and reason about:

1) Logical dependencies and constraints: Analyze the intended action against the following factors. Resolve conflicts in order of importance:
    1.1) Policy-based rules, mandatory prerequisites, and constraints.
    1.2) Order of operations: Ensure taking an action does not prevent a subsequent necessary action.
        1.2.1) The user may request actions in a random order, but you may need to reorder operations to maximize successful completion of the task.
    1.3) Other prerequisites (information and/or actions needed).
    1.4) Explicit user constraints or preferences.

2) Risk assessment: What are the consequences of taking the action? Will the new state cause any future issues?
    2.1) For exploratory tasks (like searches), missing *optional* parameters is a LOW risk. **Prefer calling the tool with the available information over asking the user, unless** your `Rule 1` (Logical Dependencies) reasoning determines that optional information is required for a later step in your plan.

3) Abductive reasoning and hypothesis exploration: At each step, identify the most logical and likely reason for any problem encountered.
    3.1) Look beyond immediate or obvious causes. The most likely reason may not be the simplest and may require deeper inference.
    3.2) Hypotheses may require additional research. Each hypothesis may take multiple steps to test.
    3.3) Prioritize hypotheses based on likelihood, but do not discard less likely ones prematurely. A low-probability event may still be the root cause.

4) Outcome evaluation and adaptability: Does the previous observation require any changes to your plan?
    4.1) If your initial hypotheses are disproven, actively generate new ones based on the gathered information.

5) Information availability: Incorporate all applicable and alternative sources of information, including:
    5.1) Using available tools and their capabilities
    5.2) All policies, rules, checklists, and constraints
    5.3) Previous observations and conversation history
    5.4) Information only available by asking the user

6) Precision and Grounding: Ensure your reasoning is extremely precise and relevant to each exact ongoing situation.
    6.1) Verify your claims by quoting the exact applicable information (including policies) when referring to them. 

7) Completeness: Ensure that all requirements, constraints, options, and preferences are exhaustively incorporated into your plan.
    7.1) Resolve conflicts using the order of importance in #1.
    7.2) Avoid premature conclusions: There may be multiple relevant options for a given situation.
        7.2.1) To check for whether an option is relevant, reason about all information sources from #5.
        7.2.2) You may need to consult the user to even know whether something is applicable. Do not assume it is not applicable without checking.
    7.3) Review applicable sources of information from #5 to confirm which are relevant to the current state.

8) Persistence and patience: Do not give up unless all the reasoning above is exhausted.
    8.1) Don't be dissuaded by time taken or user frustration.
    8.2) This persistence must be intelligent: On *transient* errors (e.g. please try again), you *must* retry **unless an explicit retry limit (e.g., max x tries) has been reached**. If such a limit is hit, you *must* stop. On *other* errors, you must change your strategy or arguments, not repeat the same failed call.

9) Inhibit your response: only take an action after all the above reasoning is completed. Once you've taken an action, you cannot take it back.

Следующие шаги