Générer une sortie structurée

Travailler avec Llama 3

Imtihan Ahmed

Machine Learning Engineer

Sortie structurée en JSON

  • Exemple : les réponses de Llama peuvent alimenter un tableau de bord

  • Le texte brut ne convient pas ❌

  • Il faut des sorties structurées ✅

Employé d’une société d’analytique F&B

Schéma d’automatisation de rapports pour restaurants

Travailler avec Llama 3

Réponses JSON avec chat completion

response_format = {"type": "json_object"}


message_list = [ {"role": "system", # System role defined as market analyst "content": "You are a food industry market analyst. You analyze sales data and generate structured JSON reports of top-selling beverages."},
{"role": "user", # User role to pass the request "content": "Provide a structured report on the top-selling beverages this year."} ]
Travailler avec Llama 3

Réponses JSON avec chat completion

output = llm.create_chat_completion(
         messages = message_list,

response_format = "json_object"
)
  • Format de réponse spécifié en JSON
  • Llama génère une réponse structurée, pas de texte libre
Travailler avec Llama 3

Extraire la réponse JSON

print(output['choices'][0]['message']['content'])
{
  "report_name": "Top-Selling Beverages 2024",
  "top_beverages": [
    {
      "rank": 1,
      "beverage_name": "Coca-Cola Classic",
      "sales_volume": 2.1,
      "growth_rate": 1.9
    },... ]
}
Travailler avec Llama 3

Définir un schéma

response_format = {
"type": "json_object",

"schema": {
"type": "object",
"properties": { "Product Name": {"type": "string"}, "Category": {"type": "string"}, "Sales Growth": {"type": "float"}}
}
}
  • Possibilité de définir un schéma : règles de format des données
Travailler avec Llama 3

Définir un schéma

output = llm.create_chat_completion(
         messages = message_list,
         response_format = response_format)  

print(output['choices'][0]['message']['content'])
{
  "Product Name": "Coca-Cola",
  "Category": "Soft Drink",
  "Sales Growth": 12.5
}
Travailler avec Llama 3

Passons à la pratique !

Travailler avec Llama 3

Preparing Video For Download...