Rédigez des prompts efficaces pour les modèles Mistral avec des prompts système, une structure, une mise en forme et des exemples few-shot.
Lorsque vous commencez à utiliser les modèles Mistral, vos premières interactions tournent autour des prompts. Maîtriser l’art de rédiger des prompts efficaces est essentiel pour obtenir des réponses de haute qualité des modèles Mistral ou d’autres LLM.
Concepts principaux
L’art de rédiger des prompts
Nous présentons ci-dessous les concepts fondamentaux du prompting et la manière de rédiger des prompts efficaces pour exploiter au mieux les capacités de nos modèles.
Prompt système
Lorsque vous donnez des instructions, vous pouvez fournir deux niveaux d’entrée au modèle : system et user.
Le prompt system est fourni au début de la conversation. Il définit le contexte général et les instructions qui encadrent le comportement du modèle, et il est généralement géré par le développeur.
Le prompt user est fourni au cours de la conversation pour donner au modèle un contexte ou des instructions spécifiques à l’interaction en cours.
En tant que développeur, vous pouvez toujours utiliser des prompts user pour fournir du contexte ou des instructions supplémentaires au cours de la conversation si nécessaire.
Si vous ne pouvez pas contrôler le prompt system, vous pouvez quand même inclure le contexte général et les instructions dans le prompt user en les concaténant avec la requête proprement dite.
Exemple avec rôles séparés :
Également appelée jeu de rôle, c’est la première étape de la rédaction d’un prompt : elle consiste à définir un objectif clair. Une approche courante consiste à commencer par une définition concise du rôle et de la tâche, par exemple :
"You are a <role>, your task is to <task>."
Cette technique simple mais puissante oriente le modèle vers un domaine et une tâche spécifiques, afin qu’il comprenne rapidement le contexte et la sortie attendue.
Structure
Lorsque vous donnez des instructions, organisez-les de façon hiérarchique ou selon une structure claire, par exemple en les divisant en sections et sous-sections distinctes. Le prompt doit être clair et complet.
Une règle empirique utile consiste à imaginer que vous écrivez pour quelqu’un qui n’a aucun contexte préalable : cette personne doit pouvoir comprendre et exécuter la tâche uniquement en lisant le prompt.
Exemple de prompt bien structuré :
You are a language detection model, your task is to detect the language of the given text.# Available LanguagesSelect the language from the following list:- English: "en"- French: "fr"- Spanish: "es"- German: "de"Any language not listed must be classified as "other" with the code "on".# Response FormatYour answer must follow this format:{"language_iso": <language_code>}# ExamplesBelow are sample inputs and expected outputs:## EnglishUser: Hello, how are you?Answer: {"language_iso": "en"}## FrenchUser: Bonjour, comment allez-vous?Answer: {"language_iso": "fr"}
Formatting
La mise en forme est essentielle pour rédiger des prompts efficaces. Elle permet de mettre explicitement en évidence les différentes sections, rendant la structure intuitive à la fois pour le modèle et pour les développeurs. Le Markdown et/ou les balises de style XML sont idéaux, car ils sont :
Lisibles : faciles à parcourir pour un humain.
Analysables : il est simple d’en extraire des informations par programmation.
Familiers : ils ont probablement été massivement vus pendant l’entraînement du modèle.
Une bonne mise en forme aide non seulement le modèle à comprendre le prompt, mais permet aussi aux développeurs d’itérer sur l’application et de la maintenir plus facilement.
Prompting par l’exemple
Le prompting par l’exemple est une technique qui consiste à fournir quelques exemples de la tâche pour améliorer la compréhension et la précision du modèle, et surtout le format de sortie.
Prompting few-shot
Un cas particulier est le prompting few-shot, où des interactions artificielles entre l’utilisateur et le modèle sont incluses dans l’historique de la conversation. À l’inverse, le prompting zero-shot n’utilise aucun exemple.
Exemple direct dans un prompt :
[...]# ExamplesInput: Hello, how are you?Output: {"language_iso": "en"}[...]
Structure standard de prompting few-shot :
[ { "role": "system", "content": "You are a language detection model. Your task is to detect the language of the given text.\n[...]" }, { "role": "user", "content": "Hello, how are you?" }, { "role": "assistant", "content": "{\"language_iso\": \"en\"}" }, { "role": "user", "content": "Bonjour, comment allez-vous?" }, { "role": "assistant", "content": "{\"language_iso\": \"fr\"}" }]
Sorties structurées
Une fois votre prompt prêt, vous pouvez vous concentrer sur la sortie. Pour que le modèle génère des réponses structurées et prévisibles, nous permettons d’imposer un format de sortie JSON spécifique. C’est particulièrement utile pour les tâches qui nécessitent une structure cohérente, facile à analyser et à traiter par programmation.
Appliquée à l’exemple ci-dessus, cette technique garantirait des réponses cohérentes en termes de format et permettrait aussi d’imposer les catégories à utiliser.
Pour plus de détails sur l’utilisation des sorties structurées, consultez la documentation Structured Outputs.
Advice
Lorsque vous construisez un prompt, il est important de rester flexible et d’expérimenter : des modèles de laboratoires différents, voire une simple mise à jour, peuvent modifier le comportement du modèle, et un prompt jusque-là fiable peut en être affecté.
N’hésitez donc pas à revoir vos prompts et à en mesurer l’impact : comme vous itérez sur votre code et sur l’entraînement de vos modèles, itérez sur vos prompts et évaluez l’impact de vos modifications.
À éviter
Ce qu’il faut éviter
Vous trouverez ci-dessous une liste de conseils utiles sur ce qu’il faut éviter. Cette liste n’est pas exhaustive et peut dépendre de votre cas d’usage, mais ces points sont bons à garder à l’esprit lorsque vous construisez vos prompts.
Évitez les termes subjectifs et flous
Évitez les adjectifs quantitatifs flous : « trop long », « trop court », « beaucoup », « peu », etc.
Fournissez plutôt des mesures objectives.
Évitez les termes flous comme « des choses », « des trucs », « rédige un rapport intéressant », « rends-le meilleur », etc.
Indiquez plutôt précisément ce que vous entendez par « intéressant », « meilleur », etc.
Évitez les contradictions
À mesure que votre prompt système s’allonge, de légères contradictions peuvent apparaître.<br />
Exemple :
« Si les nouvelles données sont liées à un enregistrement existant de la base de données, mets à jour cet enregistrement. »
« Si les données sont nouvelles, crée un nouvel enregistrement. »
Ce n’est pas clair, car de nouvelles données pourraient soit mettre à jour un enregistrement existant, soit en créer un nouveau.
Utilisez plutôt un arbre de décision :
## How to update database recordsFollow these steps:- If the data does not include new information (i.e., it already exists in a record): - Ignore this data.- Otherwise, if the data is not related to any existing record in the same table: - Create a new record.- Otherwise, if the related record is larger than 100 characters: - Create a new record.- Otherwise, if the data directly contradicts the existing record: - Delete the existing record and create a new one.- Otherwise: - Update the existing record to include the new data.
Ne demandez pas aux LLM de compter des mots
À éviter : « Si l’enregistrement est trop long, divise-le en plusieurs enregistrements. »
À éviter : « Si l’enregistrement dépasse 100 caractères, divise-le en plusieurs enregistrements. »
Fournissez plutôt le nombre de caractères en entrée :
Les modèles ingèrent les tokens plus vite qu’ils ne les génèrent. Si vous utilisez des sorties structurées, ne demandez au modèle de générer que ce qui est strictement nécessaire.<br />
Mauvais exemples :
Générer le contenu complet d’un enregistrement pour une opération NO_OP.
Générer un livre entier d’un seul coup.
Ne générez que la mise à jour ou les données nécessaires.
Préférez les échelles verbales
Si vous avez besoin qu’un modèle évalue quelque chose, utilisez une échelle verbale pour de meilleures performances.<br />
À éviter :
"Rate these options on a 1 to 5 scale, 1 being highly irrelevant and 5 being highly relevant."
À utiliser :
Rate these options using this scale:- Very Low: if the option is highly irrelevant- Low: if the option is not good enough- Neutral: if the option is not particularly interesting- Good: if the option is worth considering- Very Good: for highly relevant options
Vous pouvez convertir cette échelle verbale en échelle numérique si nécessaire.
Exemples de prompts
Nous vous présentons ci-dessous des exemples de prompts illustrant quatre capacités de prompting différentes :
Classification
Summarization
Personalization
Evaluation
Les modèles Mistral peuvent facilement classer du texte dans des catégories distinctes. Prenons l’exemple d’un bot de support client pour une banque : nous pouvons définir une série de catégories prédéterminées dans le prompt, puis demander aux modèles Mistral AI de classer la question du client en conséquence.
Dans l’exemple suivant, face à la demande du client, les modèles Mistral AI la classent correctement dans « country_support » :
Demande de l’utilisateur : « Je me renseigne sur la disponibilité de vos cartes dans l’UE, car je réside en France et je souhaite utiliser vos cartes. »
Réponse de l’assistant : "country_support"
Prompt système
Le prompt de classification a dû être soigneusement conçu pour que le modèle classe correctement la demande du client.
Pour la classification, il existe 2 stratégies principales :
Demander directement l’étiquette : le modèle doit alors répondre par un seul mot ou une seule chaîne.
Efficace, rapide et économique, cette stratégie utilise le moins de tokens de sortie possible, mais peut manquer de fiabilité et de flexibilité.
Demander une sortie JSON : le modèle doit alors répondre par un objet JSON facile à traiter en aval.
Fiable, flexible et pratique, cette stratégie génère un peu plus de tokens, mais permet des cas d’usage plus complexes et davantage de flexibilité.
Ce prompt est conçu pour que le modèle réponde par un seul terme composé, en très peu de tokens.
You are a bank customer service bot. Your task is to assess customer intent and categorize customer inquiry into one of the predefined categories.# CategoriesThe main categories available are the following:- card_arrival: Inquiries about the arrival of the card, or if it is lost.- change_pin: Inquiries about changing the pin code of the card.- exchange_rate: Inquiries about the exchange rate of the card.- country_support: Inquiries about the countries supported by the card.- cancel_transfer: Inquiries about canceling a transfer.- charge_dispute: Inquiries about a charge dispute.If the text doesn't fit into any of the above categories, classify it as:- customer_service: Inquiries about customer service in general that do not fit into the previous categories.# Answer FormatYou will only respond with the category among the categories listed above without any explanations or notes, in a single self-contained compound term.## ExamplesBelow are some examples of customer inquiries and their corresponding categories, you will receive a new customer inquiry and you will respond with the corresponding category.User: How do I know if I will get my card, or if it is lost? I am concerned about the delivery process and would like to ensure that I will receive my card as expected. Could you please provide information about the tracking process for my card, or confirm if there are any indicators to identify if the card has been lost during delivery?Answer: card_arrivalUser: I am planning an international trip to Paris and would like to inquire about the current exchange rates for Euros as well as any associated fees for foreign transactions.Answer: exchange_rateUser: What countries are getting support? I will be traveling and living abroad for an extended period of time, specifically in France and Germany, and would appreciate any information regarding compatibility and functionality in these regions.Answer: country_supportUser: Can I get help starting my computer? I am having difficulty starting my computer,and would appreciate your expertise in helping me troubleshoot the issue.Answer: customer_service
Ce prompt est conçu pour que le modèle réponde par un objet JSON facile à traiter en aval.
Vous pouvez utiliser le paramètre response_format pour forcer le modèle à répondre par un objet JSON, voire imposer un schéma JSON spécifique. Consultez notre documentation Structured Outputs pour plus de détails.
You are a bank customer service bot. Your task is to assess customer intent and categorize customer inquiry into one of the predefined categories.# CategoriesThe main categories available are the following:- card_arrival: Inquiries about the arrival of the card, or if it is lost.- change_pin: Inquiries about changing the pin code of the card.- exchange_rate: Inquiries about the exchange rate of the card.- country_support: Inquiries about the countries supported by the card.- cancel_transfer: Inquiries about canceling a transfer.- charge_dispute: Inquiries about a charge dispute.If the text doesn't fit into any of the above categories, classify it as:- customer_service: Inquiries about customer service in general that do not fit into the previous categories.# Answer FormatYou will only respond with the following JSON format:{"category": <category_name>}Category name must correspond to one of the categories listed above as a single self-contained compond term.## ExamplesBelow are some examples of customer inquiries and their corresponding categories, you will receive a new customer inquiry and you will respond with the corresponding category.User: How do I know if I will get my card, or if it is lost? I am concerned about the delivery process and would like to ensure that I will receive my card as expected. Could you please provide information about the tracking process for my card, or confirm if there are any indicators to identify if the card has been lost during delivery?Answer: {"category": "card_arrival"}User: I am planning an international trip to Paris and would like to inquire about the current exchange rates for Euros as well as any associated fees for foreign transactions.Answer: {"category": "exchange_rate"}User: What countries are getting support? I will be traveling and living abroad for an extended period of time, specifically in France and Germany, and would appreciate any information regarding compatibility and functionality in these regions.Answer: {"category": "country_support"}User: Can I get help starting my computer? I am having difficulty starting my computer,and would appreciate your expertise in helping me troubleshoot the issue.Answer: {"category": "customer_service"}
Le résumé est une tâche courante pour les LLM grâce à leurs capacités de compréhension et de génération du langage naturel. Voici un exemple de prompt permettant de générer des questions intéressantes sur un essai et de le résumer.
Prompt
You are a commentator. Your task is to write a report on an essay.When presented with the essay, come up with interesting questions to ask, and answer each question.Afterward, combine all the information and write a report in the markdown format.# Essay:{essay}# Instructions:## Summarize:In clear and concise language, summarize the key points and themes presented in the essay.## Interesting Questions:Generate three distinct and thought-provoking questions that can be asked about the content of the essay. For each question:- After "Q: ", describe the problem- After "A: ", provide a detailed explanation of the problem addressed in the question.- Enclose the ultimate answer in <>.## Write a reportUsing the essay summary and the answers to the interesting questions, create a comprehensive report in Markdown format.
Stratégies utilisées :
Instructions étape par étape : cette stratégie s’inspire du prompting chain-of-thought, qui permet aux LLM d’utiliser une série d’étapes de raisonnement intermédiaires pour traiter des tâches complexes. Il est souvent plus facile de résoudre des problèmes complexes en les décomposant en étapes plus simples et plus petites, et il est alors plus facile de déboguer et d’inspecter le comportement du modèle. Dans notre exemple, nous décomposons la tâche en trois étapes : résumer, générer des questions intéressantes et rédiger un rapport. Cela aide le modèle à réfléchir à chaque étape et à générer un rapport final plus complet.
Génération d’exemples : nous pouvons demander aux LLM de guider automatiquement le processus de raisonnement et de compréhension en générant des exemples accompagnés d’explications et d’étapes. Dans cet exemple, nous demandons au LLM de générer trois questions et de fournir des explications détaillées pour chacune.
Formatage de la sortie : nous pouvons demander aux LLM de produire une sortie dans un format donné en le demandant directement, par exemple « rédige un rapport au format Markdown ».
Les LLM excellent dans les tâches de personnalisation, car ils peuvent produire du contenu adapté à chaque utilisateur. Dans cet exemple, nous créons des réponses personnalisées par e-mail aux questions de clients.
Utilisateur : Madame, Monsieur,
Quel est votre TAEG pour un prêt à taux fixe sur 30 ans, et comment se compare-t-il au taux fixe sur 15 ans ?
Cordialement,<br />
Anna
A : Chère Anna,
Merci pour votre demande concernant nos prêts immobiliers à taux fixe.<br />
Notre taux d’intérêt fixe actuel sur 30 ans est de 6,403 %, avec un taux annuel effectif global (TAEG) de 6,484 %. En comparaison, notre taux d’intérêt fixe sur 15 ans est de 5,705 %, avec un TAEG de 5,848 %.
Comme vous pouvez le constater, l’option à taux fixe sur 15 ans présente un taux d’intérêt et un TAEG inférieurs à ceux de l’option sur 30 ans. Vous paieriez donc moins d’intérêts sur la durée du prêt en choisissant l’option sur 15 ans. En revanche, les mensualités seraient plus élevées en raison de la durée plus courte du prêt.
N’hésitez pas à nous contacter si vous avez d’autres questions ou si nous pouvons vous aider davantage à choisir l’option de prêt la plus adaptée à vos besoins.
Bien cordialement,<br />
Service client du prêteur
Prompt
You are a mortgage lender customer service bot, and your task is to create personalized email responses to address customer questions. Answer the customer's inquiry using the provided facts below. Ensure that your response is clear, concise, and directly addresses the customer's question. Address the customer in a friendly and professional manner. Sign the email with "Lender Customer Support."# Facts30-year fixed-rate: interest rate 6.403%, APR 6.484%20-year fixed-rate: interest rate 6.329%, APR 6.429%15-year fixed-rate: interest rate 5.705%, APR 5.848%10-year fixed-rate: interest rate 5.500%, APR 5.720%7-year ARM: interest rate 7.011%, APR 7.660%5-year ARM: interest rate 6.880%, APR 7.754%3-year ARM: interest rate 6.125%, APR 7.204%30-year fixed-rate FHA: interest rate 5.527%, APR 6.316%30-year fixed-rate VA: interest rate 5.684%, APR 6.062%# Email{insert customer email here}
Stratégies utilisées :
Fournir des faits : intégrer des faits dans les prompts peut être utile pour développer des bots de support client. Il est important d’utiliser un langage clair et concis pour présenter ces faits. Cela aide le LLM à répondre de façon précise et rapide aux demandes des clients.
Il existe de nombreuses façons d’évaluer les sorties d’un LLM. Voici trois approches à titre de référence : inclure un score de confiance, introduire une étape d’évaluation ou utiliser un autre LLM pour l’évaluation.
Inclure un score de confiance
Nous pouvons inclure un score de confiance avec la sortie générée.
Assistant
{ "Summaries": [ { "Summary": "The author discusses their early experiences with programming and writing, starting with writing short stories and programming on an IBM 1401 in 9th grade. They then moved on to working with microcomputers, building their own from a Heathkit, and eventually convincing their father to buy a TRS-80 in 1980. They wrote simple games, a program to predict rocket flight trajectories, and a word processor.", "Confidence": 0.9 }, { "Summary": "The author began college as a philosophy major, but found it to be unfulfilling and switched to AI. They were inspired by a novel and a PBS documentary, as well as the potential for AI to create intelligent machines like those in the novel. Despite this excitement, they eventually realized that the traditional approach to AI was flawed and shifted their focus to Lisp.", "Confidence": 0.85 }, { "Summary": "The author briefly worked at Interleaf, where they found that their Lisp skills were highly valued. They eventually left Interleaf to return to RISD, but continued to work as a freelance Lisp hacker. While at RISD, they started painting still lives in their bedroom at night, which led to them applying to art schools and eventually attending the Accademia di Belli Arti in Florence.", "Confidence": 0.9 } ]}
Prompt
You are a summarization system that can provide summaries with associated confidence scores.In clear and concise language, provide three short summaries of the following essay, along with their confidence scores.You will only respond with a JSON object with the key Summary and Confidence. Do not provide explanations.# Essay:{insert essay text here}
Stratégies utilisées :
Sortie JSON : pour faciliter les traitements en aval, une sortie au format JSON est souvent préférée. Nous pouvons activer le mode JSON en définissant response_format sur {"type": "json_object"} et en précisant dans le prompt « You will only respond with a JSON object with the key Summary and Confidence. » Spécifier ces clés dans l’objet JSON favorise la clarté et la cohérence.
Température plus élevée : dans cet exemple, nous augmentons la température pour encourager le modèle à être plus créatif et à produire trois résumés différents les uns des autres.
Introduire une étape d’évaluation
Nous pouvons aussi ajouter une seconde étape d’évaluation dans le prompt. Nous demandons au LLM de générer trois résumés et de les évaluer.
Assistant
Summary 1: The essay discusses the author's experiences with writing and programming before college, his initial struggles with learning Fortran on an IBM 1401, and the shift towards microcomputers that led to his interest in AI. He also touches on his decision to pursue a degree in AI and the disillusionment he felt when he realized that AI as practiced at the time was a hoax.Summary 2: The author tells the story of his journey into programming, starting with writing short stories before discovering the world of computers. He describes his early experiences with an IBM 1401 and how it was like a mini Bond villain's lair. He also talks about his fascination with microcomputers and how it led him to learn Lisp and become interested in AI. However, he eventually became disillusioned with AI and decided to focus on Lisp instead.Summary 3: The essay recounts the author's experiences with writing and programming before college, including his early attempts at writing short stories and his struggles with learning to program on an IBM 1401. He discusses how the arrival of microcomputers changed everything and sparked his interest in AI. However, he eventually realized that AI, as practiced at the time, was a hoax, and he turned his attention to Lisp. He also touches on his decision to pursue a degree in AI despite his disillusionment with the field.Evaluation: I believe that Summary 1 is the best summary because it provides a clear and concise overview of the author's experiences with writing and programming before college, the shift towards microcomputers, and his eventual disillusionment with AI. It covers the key points of the essay without getting bogged down in unnecessary details. Summary 2 is also good, but it focuses more on the author's early experiences with computers and less on his later experiences with AI. Summary 3 is the weakest summary because it does not capture the full scope of the author's experiences and does not mention his decision to pursue a degree in AI despite his disillusionment with the field.
Prompt
You are given an essay text and need to provide summaries and evaluate them.# Essay:{insert essay text here}Step 1: In this step, provide three short summaries of the given essay. Each summary should be clear, concise, and capture the key points of the speech. Aim for around 2-3 sentences for each summary.Step 2: Evaluate the three summaries from Step 1 and rate which one you believe is the best. Explain your choice by pointing out specific reasons such as clarity, completeness, and relevance to the speech content.
Utiliser un autre LLM pour l’évaluation
Dans les systèmes en production, il est courant d’utiliser un autre LLM pour l’évaluation, afin de séparer l’étape d’évaluation de la génération des résumés.
Étape 1 : utiliser un premier LLM pour générer trois résumés
Assistant
Summary 1: The author writes about their experiences with programming and writing before college. They started programming using Fortran on an IBM 1401 and wrote short stories. They later got into AI, but became disillusioned with it while in graduate school. The author then turned their focus to Lisp, eventually writing a book about it called "On Lisp". They also tried pursuing art, but found it difficult to make a living from it.Summary 2: The author describes their experiences with programming in college and later in the workforce. They learned Lisp while in college, which expanded their concept of what a program could do. After graduation, the author worked at Interleaf, a company that made document creation software. They also did some consulting and writing on the side, eventually writing a book called "On Lisp". The author enjoyed working at Interleaf, but found that the Lisp they used was just a thin layer on top of a larger C cake.Summary 3: The author tells the story of their early experiences with programming and writing. They started writing short stories before college, but they were not very good. The first programs they wrote were on an IBM 1401 using Fortran. In college, they got into AI, but found it disappointing. The author then turned their focus to Lisp, which they found to be more interesting. They also tried pursuing art, but found it difficult to make a living from it. The author eventually wrote a book called "On Lisp" and worked at Interleaf, a company that made document creation software. They enjoyed their time at Interleaf, but found that the Lisp they used was just a thin layer on top of a larger C cake.
Prompt
Provide three short summaries of the given essay. Each summary should be clear, concise, and capture the key points of the essay.Aim for around 2-3 sentences for each summary.# essay:{insert essay text here}
Étape 2 : utiliser un autre LLM pour noter les résumés générés
Assistant
Summary 3 provides the most complete and accurate summary of the essay. It covers the author's experiences with writing and programming before college, their disappointment with AI in college, and their eventual focus on Lisp and work at Interleaf. Summary 1 is missing some key details, such as the author's work at Interleaf and their writing of "On Lisp". Summary 2 focuses too much on the author's time at Interleaf and neglects their early experiences with writing and programming before college. Overall, Summary 3 is the best choice as it is the most complete and accurate summary of the essay.
Prompt
You are given an essay and three summaries of the essay. Evaluate the three summaries and rate which one you believe is the best.Explain your choice by pointing out specific reasons such as clarity, completeness, and relevance to the essay content.# Essay:{insert essay text here}# Summaries{insert the previous output}
Stratégies utilisées :
Chaînage de LLM : dans cet exemple, nous enchaînons deux LLM, la sortie du premier servant d’entrée au second. La méthode de chaînage peut être adaptée à vos cas d’usage. Par exemple, vous pouvez enchaîner trois LLM, la sortie de deux d’entre eux alimentant le troisième. Si le chaînage de LLM offre de la flexibilité, gardez à l’esprit qu’il peut entraîner des appels d’API supplémentaires et donc des coûts plus élevés.