mistralM

Docs

sideBar

Citations et références

Faites en sorte que les modèles fondent leurs réponses sur des documents ou des résultats d’outils et renvoient des citations et références pour les applications RAG et agentiques.

Les citations permettent aux modèles d’ancrer leurs réponses et de fournir des références, ce qui en fait une fonctionnalité puissante pour la génération augmentée par récupération (RAG) et les applications agentiques. Cette fonctionnalité permet au modèle d’indiquer la source des informations extraites d’un document ou d’un fragment de données issu d’un appel d’outil.

Nos modèles ont été entraînés en profondeur pour s’ancrer dans des documents et fournir des sources, avec une fonctionnalité intégrée d’extraction des références et citations.

lightbulb

Avant de continuer, nous vous recommandons de lire la documentation Chat Completions pour en savoir plus sur l’API chat completions et son utilisation.

Usage

Utiliser les citations et références

Pour fournir des documents au modèle, vous pouvez inclure les sources dans la réponse à un appel de fonction.<br /> Voici un exemple de références, ici issues de Wikipédia, à l’aide d’appels d’outils.

Configurer l’outil

Pour utiliser les citations et références, vous devez configurer un appel d’outil qui renverra les références.

Exemple de références

references = {
  "0": {
    "url": "https://en.wikipedia.org/wiki/2024_Nobel_Peace_Prize",
    "title": "2024 Nobel Peace Prize",
    "snippets": [
      [
        "The 2024 Nobel Peace Prize, an international peace prize established according to Alfred Nobel's will, was awarded to Nihon Hidankyo (the Japan Confederation of A- and H-Bomb Sufferers Organizations), for their activism against nuclear weapons, assisted by victim/survivors (known as Hibakusha) of the atomic bombings of Hiroshima and Nagasaki in 1945.",
        "They will receive the prize at a ceremony on 10 December 2024 at Oslo, Norway."
      ]
    ],
    "description": None,
    "date": "2024-11-26T17:39:55.057454",
    "source": "wikipedia"
  },
  "1": {
    "url": "https://en.wikipedia.org/wiki/Climate_Change",
    "title": "Climate Change",
    "snippets": [
      [
        "Present-day climate change includes both global warming—the ongoing increase in global average temperature—and its wider effects on Earth’s climate system. Climate change in a broader sense also includes previous long-term changes to Earth's climate. The current rise in global temperatures is driven by human activities, especially fossil fuel burning since the Industrial Revolution. Fossil fuel use, deforestation, and some agricultural and industrial practices release greenhouse gases. These gases absorb some of the heat that the Earth radiates after it warms from sunlight, warming the lower atmosphere. Carbon dioxide, the primary gas driving global warming, has increased in concentration by about 50% since the pre-industrial era to levels not seen for millions of years."
      ]
    ],
    "description": None,
    "date": "2024-11-26T17:39:55.057454",
    "source": "wikipedia"
  },
  "2": {
    "url": "https://en.wikipedia.org/wiki/Artificial_Intelligence",
    "title": "Artificial Intelligence",
    "snippets": [
      [
        "Artificial intelligence (AI) refers to the capability of computational systems to perform tasks typically associated with human intelligence, such as learning, reasoning, problem-solving, perception, and decision-making. It is a field of research in computer science that develops and studies methods and software that enable machines to perceive their environment and use learning and intelligence to take actions that maximize their chances of achieving defined goals. Such machines may be called AIs."
      ]
    ],
    "description": None,
    "date": "2024-11-26T17:39:55.057454",
    "source": "wikipedia"
  }
}

Ensuite, vous devez définir l’outil qui servira à récupérer les informations depuis la source externe. Ici, nous allons créer un outil get_information qui renverra les références mentionnées précédemment.

get_information_tool = {
    "type": "function",
    "function": {
        "name": "get_information",
        "description": "Get information from external source.",
        "parameters": {
          "type": "object",
          "properties": {},
          "additionalProperties": False
        },
        "strict": True
    },
}

def get_information():
    return json.dumps(references)

Initialiser le client

Pour commencer, initialisez le client avec votre clé API comme d’habitude.

import os
from mistralai import Mistral
from mistralai import ToolMessage
import json

api_key = os.environ["MISTRAL_API_KEY"]
model = "mistral-small-latest"

client = Mistral(api_key=api_key)

Configurer l’historique du chat

Vous pouvez configurer l’historique du chat avec le message utilisateur initial et le message système facultatif.

chat_history = [
    {
        "role": "system",
        "content": "Answer the user by providing references to the source of the information."
    },
    {
        "role": "user",
        "content": "Who won the Nobel Prize in 2024?"
    }
]

Envoyer la requête de chat initiale

Vous pouvez envoyer la requête de chat initiale au modèle avec l’historique du chat et l’outil.

chat_response = client.chat.complete(
    model=model,
    messages=chat_history,
    tools=[get_information_tool],
)

tool_call = chat_response.choices[0].message.tool_calls[0]
chat_history.append(chat_response.choices[0].message)
Sortie
{
  "id": "3af5113805d6422cb3f89199786dc1e1",
  "created": 1756910314,
  "model": "mistral-small-latest",
  "usage": {
    "prompt_tokens": 70,
    "total_tokens": 90,
    "completion_tokens": 20
  },
  "object": "chat.completion",
  "choices": [
    {
      "index": 0,
      "finish_reason": "tool_calls",
      "message": {
        "role": "assistant",
        "tool_calls": [
          {
            "id": "PxtchOaKx",
            "function": {
              "name": "get_information",
              "arguments": "{\"query\": \"Nobel Prize winners 2024\"}"
            },
            "index": 0
          }
        ],
        "content": ""
      }
    }
  ]
}

Le modèle souhaite appeler l’outil get_information pour récupérer les informations depuis la source externe.

De notre côté, nous pouvons maintenant traiter l’appel d’outil et ajouter le résultat à l’historique du chat.

result = get_information()

tool_call_result = ToolMessage(
    content=result,
    tool_call_id=tool_call.id,
    name=tool_call.function.name,
)

# Append the tool call message to the chat_history
chat_history.append(tool_call_result)

Envoyer la requête de chat finale

Enfin, vous pouvez envoyer la requête de chat finale au modèle avec l’historique mis à jour, contenant la requête d’origine, l’appel d’outil du modèle et le résultat de l’outil.

chat_response = client.chat.complete(
    model=model,
    messages=chat_history,
    tools=[get_information_tool],
)
Sortie
{
  "id": "60b20a6ea61649248662aa0178dd8f57",
  "created": 1756913113,
  "model": "mistral-small-latest",
  "usage": {
    "prompt_tokens": 706,
    "total_tokens": 802,
    "completion_tokens": 96
  },
  "object": "chat.completion",
  "choices": [
    {
      "index": 0,
      "finish_reason": "stop",
      "message": {
        "role": "assistant",
        "tool_calls": null,
        "content": [
          {
            "type": "text",
            "text": "The 2024 Nobel Peace Prize was awarded to Nihon Hidankyo (the Japan Confederation of A- and H-Bomb Sufferers Organizations) for their activism against nuclear weapons, with assistance from the Hibakusha, survivors of the atomic bombings of Hiroshima and Nagasaki in 1945. The award ceremony will take place on December 10, 2024, in Oslo, Norway "
          },
          {
            "type": "reference",
            "reference_ids": [0]
          },
          {
            "type": "text",
            "text": "."
          }
        ]
      }
    }
  ]
}

Comme vous pouvez le voir, le modèle a répondu à la question de l’utilisateur et fourni la référence à la source de l’information.

Vous pouvez extraire et afficher ces références à partir de la réponse comme bon vous semble.

from mistralai.models import TextChunk, ReferenceChunk

refs_used = []

# Print the main response and save each reference
for chunk in chat_response.choices[0].message.content:
    if isinstance(chunk, TextChunk):
        print(chunk.text, end="")
    elif isinstance(chunk, ReferenceChunk):
        refs_used += chunk.reference_ids

# Print references only
if refs_used:
    print("\n\nSources:")
    for i, ref in enumerate(set(refs_used), 1):
        reference = json.loads(result)[str(ref)]
        print(f"\n{i}. {reference['title']}: {reference['url']}")
Sortie
The 2024 Nobel Peace Prize was awarded to Nihon Hidankyo (the Japan Confederation of A- and H-Bomb Sufferers Organizations) for their activism against nuclear weapons, with assistance from the Hibakusha, survivors of the atomic bombings of Hiroshima and Nagasaki in 1945. The award ceremony will take place on December 10, 2024, in Oslo, Norway .

Sources:

1. 2024 Nobel Peace Prize: https://en.wikipedia.org/wiki/2024_Nobel_Peace_Prize

Cookbooks

Vous trouverez un cookbook complet sur les citations et références exploitant le RAG avec Wikipédia herearrowUpRight.<br /> Ce modèle vous aidera à démarrer avec la recherche web et l’ancrage documentaire avec citations.