Utiliser les instructions système

Les instructions système sont comme un préambule que vous ajoutez avant que le LLM ne soit exposé à d'autres instructions de l'utilisateur. Elles permettent aux utilisateurs d'orienter le comportement du modèle en fonction de leurs besoins et de leurs cas d'utilisation spécifiques. Lorsque vous définissez une instruction système, vous fournissez au modèle un contexte supplémentaire pour qu'il comprenne la tâche, renvoie des réponses plus personnalisées et respecte des consignes spécifiques pendant toute l'interaction de l'utilisateur avec le modèle. Pour les développeurs, le comportement au niveau du produit peut être spécifié dans des instructions système, distinctes des requêtes fournies par les utilisateurs finaux. Par exemple, vous pouvez inclure des éléments tels que le rôle ou la persona, des informations contextuelles et des instructions de mise en forme :

You are a friendly and helpful assistant.
Ensure your answers are complete, unless the user requests a more concise approach.
When generating code, offer explanations for code segments as necessary and maintain good coding practices.
When presented with inquiries seeking information, provide answers that reflect a deep understanding of the field, guaranteeing their correctness.
For any non-english queries, respond in the same language as the prompt unless otherwise specified by the user.
For prompts involving reasoning, provide a clear explanation of each step in the reasoning process before presenting the final answer.

Les modèles Gemini suivants sont compatibles avec les instructions système :

  • gemini-1.5-flash-preview-0514 (preview)
  • gemini-1.5-pro-preview-0514 (preview)
  • gemini-1.0-pro-002

Si vous utilisez un autre modèle, consultez plutôt la section Attribuer un rôle.

Vous pouvez utiliser les instructions système de différentes manières, par exemple :

  • Définir un persona ou un rôle (pour un chatbot, par exemple)
  • Définir le format de sortie (Markdown, YAML, etc.)
  • Définir le style et le ton de sortie (par exemple, la verbosité, la formalité et le niveau de lecture cible)
  • Définir des objectifs ou des règles pour la tâche (par exemple, renvoyer un extrait de code sans autre explication)
  • Fournir du contexte supplémentaire pour l'invite (par exemple, une limite de connaissances)

Lorsqu'une instruction système est définie, elle s'applique à l'ensemble de la requête. Elle fonctionne sur plusieurs tours d'utilisateur et de modèle lorsqu'elle est incluse dans la requête. Bien que les instructions système soient distinctes du contenu de la requête, elles font toujours partie de vos requêtes globales et sont donc soumises aux règles standards d'utilisation des données.

Exemples de code

Les exemples de code dans les onglets suivants montrent comment utiliser des instructions système dans votre application d'IA générative.

Python

Avant d'essayer cet exemple, suivez les instructions de configuration pour Python décrites dans le guide de démarrage rapide de Vertex AI à l'aide des bibliothèques clientes. Pour en savoir plus, consultez la documentation de référence de l'API Vertex AI Python.

Pour vous authentifier auprès de Vertex AI, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

import vertexai

from vertexai.generative_models import GenerativeModel

# TODO(developer): Update and un-comment below lines
# project_id = "PROJECT_ID"

vertexai.init(project=project_id, location="us-central1")

model = GenerativeModel(
    model_name="gemini-1.5-flash-preview-0514",
    system_instruction=[
        "You are a helpful language translator.",
        "Your mission is to translate text in English to French.",
    ],
)

prompt = """
User input: I like bagels.
Answer:
"""

contents = [prompt]

response = model.generate_content(contents)
print(response.text)

Node.js

Avant d'essayer cet exemple, suivez les instructions de configuration pour Node.js décrites dans le guide de démarrage rapide de Vertex AI à l'aide des bibliothèques clientes. Pour en savoir plus, consultez la documentation de référence de l'API Vertex AI Node.js.

Pour vous authentifier auprès de Vertex AI, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

const {VertexAI} = require('@google-cloud/vertexai');

/**
 * TODO(developer): Update these variables before running the sample.
 */
async function set_system_instruction(projectId = 'PROJECT_ID') {
  const vertexAI = new VertexAI({project: projectId, location: 'us-central1'});

  const generativeModel = vertexAI.getGenerativeModel({
    model: 'gemini-1.5-pro-preview-0409',
    systemInstruction: {
      parts: [
        {text: 'You are a helpful language translator.'},
        {text: 'Your mission is to translate text in English to French.'},
      ],
    },
  });

  const textPart = {
    text: `
    User input: I like bagels.
    Answer:`,
  };

  const request = {
    contents: [{role: 'user', parts: [textPart]}],
  };

  const resp = await generativeModel.generateContent(request);
  const contentResponse = await resp.response;
  console.log(JSON.stringify(contentResponse));
}

C#

Avant d'essayer cet exemple, suivez les instructions de configuration pour C# décrites dans le guide de démarrage rapide de Vertex AI à l'aide des bibliothèques clientes. Pour en savoir plus, consultez la documentation de référence de l'API Vertex AI C#.

Pour vous authentifier auprès de Vertex AI, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.


using Google.Cloud.AIPlatform.V1;
using System;
using System.Threading.Tasks;

public class SystemInstruction
{
    public async Task<string> SetSystemInstruction(
        string projectId = "your-project-id",
        string location = "us-central1",
        string publisher = "google",
        string model = "gemini-1.5-pro-preview-0409")
    {

        var predictionServiceClient = new PredictionServiceClientBuilder
        {
            Endpoint = $"{location}-aiplatform.googleapis.com"
        }.Build();

        string prompt = @"User input: I like bagels.
Answer:";

        var generateContentRequest = new GenerateContentRequest
        {
            Model = $"projects/{projectId}/locations/{location}/publishers/{publisher}/models/{model}",
            Contents =
            {
                new Content
                {
                    Role = "USER",
                    Parts =
                    {
                        new Part { Text = prompt },
                    }
                }
            },
            SystemInstruction = new()
            {
                Parts =
                {
                    new Part { Text = "You are a helpful assistant." },
                    new Part { Text = "Your mission is to translate text in English to French." },
                }
            }
        };

        GenerateContentResponse response = await predictionServiceClient.GenerateContentAsync(generateContentRequest);

        string responseText = response.Candidates[0].Content.Parts[0].Text;
        Console.WriteLine(responseText);

        return responseText;
    }
}

Exemples de requêtes

Voici un exemple de base de définition de l'instruction système à l'aide du SDK Python pour l'API Gemini :

model=genai.GenerativeModel(
    model_name="gemini-1.5-pro-preview-0514",
    system_instruction="You are a cat. Your name is Neko.")

Vous trouverez ci-dessous des exemples de requêtes système qui définissent le comportement attendu du modèle.

Génération de code

Génération de code

    You are a coding expert that specializes in rendering code for front-end interfaces. When I describe a component of a website I want to build, please return the HTML and CSS needed to do so. Do not give an explanation for this code. Also offer some UI design suggestions.
    

    Create a box in the middle of the page that contains a rotating selection of images each with a caption. The image in the center of the page should have shadowing behind it to make it stand out. It should also link to another page of the site. Leave the URL blank so that I can fill it in.
    

Génération de données formatées

Génération de données formatées

    You are an assistant for home cooks. You receive a list of ingredients and respond with a list of recipes that use those ingredients. Recipes which need no extra ingredients should always be listed before those that do.

    Your response must be a JSON object containing 3 recipes. A recipe object has the following schema:

    * name: The name of the recipe
    * usedIngredients: Ingredients in the recipe that were provided in the list
    * otherIngredients: Ingredients in the recipe that were not provided in the
      list (omitted if there are no other ingredients)
    * description: A brief description of the recipe, written positively as if
      to sell it
    

    * 1 lb bag frozen broccoli
    * 1 pint heavy cream
    * 1 lb pack cheese ends and pieces
    

Chatbot de musique

Chatbot de musique

    You will respond as a music historian, demonstrating comprehensive knowledge across diverse musical genres and providing relevant examples. Your tone will be upbeat and enthusiastic, spreading the joy of music. If a question is not related to music, the response should be, "That is beyond my knowledge."
    

    If a person was born in the sixties, what was the most popular music genre being played when they were born? List five songs by bullet point.
    

Analyse financière

Analyse financière

    As a financial analysis expert, your role is to interpret complex financial data, offer personalized advice, and evaluate investments using statistical methods to gain insights across different financial areas.

    Accuracy is the top priority. All information, especially numbers and calculations, must be correct and reliable. Always double-check for errors before giving a response. The way you respond should change based on what the user needs. For tasks with calculations or data analysis, focus on being precise and following instructions rather than giving long explanations. If you're unsure, ask the user for more information to ensure your response meets their needs.

    For tasks that are not about numbers:

    * Use clear and simple language to avoid confusion and don't use jargon.
    * Make sure you address all parts of the user's request and provide complete information.
    * Think about the user's background knowledge and provide additional context or explanation when needed.

    Formatting and Language:

    * Follow any specific instructions the user gives about formatting or language.
    * Use proper formatting like JSON or tables to make complex data or results easier to understand.
    

    Please summarize the key insights of given numerical tables.

    CONSOLIDATED STATEMENTS OF INCOME (In millions, except per share amounts)

    |Year Ended December 31                | 2020        | 2021        | 2022        |

    |---                                                        | ---                | ---                | ---                |

    |Revenues                                        | $ 182,527| $ 257,637| $ 282,836|

    |Costs and expenses:|

    |Cost of revenues                                | 84,732        | 110,939        | 126,203|

    |Research and development        | 27,573        | 31,562        | 39,500|

    |Sales and marketing                        | 17,946        | 22,912        | 26,567|

    |General and administrative        | 11,052        | 13,510        | 15,724|

    |Total costs and expenses                | 141,303| 178,923| 207,994|

    |Income from operations                | 41,224        | 78,714        | 74,842|

    |Other income (expense), net        | 6,858        | 12,020        | (3,514)|

    |Income before income taxes        | 48,082        | 90,734        | 71,328|

    |Provision for income taxes        | 7,813        | 14,701        | 11,356|

    |Net income                                        | $40,269| $76,033        | $59,972|

    |Basic net income per share of Class A, Class B, and Class C stock        | $2.96| $5.69| $4.59|

    |Diluted net income per share of Class A, Class B, and Class C stock| $2.93| $5.61| $4.56|

    Please list important, but no more than five, highlights from 2020 to 2022 in the given table.

    Please write in a professional and business-neutral tone.

    The summary should only be based on the information presented in the table.
    

Étapes suivantes