# Parameters
BATCH_MODE = TruePDF Recipe Generator
# Parameters
BATCH_MODE = TrueIntroduction - receipe maker
Navigation: Index
This notebook covers the main concepts and techniques of receipe maker. The educational objectives include understanding the fundamentals, hands-on practice through exercises, and analysis of results.
Prerequisites: basic knowledge of Python and algorithms.
Adapted from an EPF student production: Dorian & Bastien (cooking). Universalization: refactor #890.
This notebook orchestrates a multi-agent collaboration to: 1. Collect user constraints 2. Generate a personalized recipe 3. Produce a styled PDF
Agents:
- InputCollector → Collects preferences
- RecipeGenerator → Creates the recipe via LLM
- PDFGenerator → Generates the final document
Installing libraries
Why this notebook relies on Semantic Kernel rather than a simple API call: generating a structured recipe (title, listed ingredients, numbered steps, dietary constraints honored) in a single LLM request produces a free-format and often inconsistent result. Semantic Kernel orchestrates several specialized agents (criteria collector, recipe generator, PDF producer) that hand off a shared state — it is this multi-agent architecture that guarantees the final recipe honors every constraint (vegetarian, no mushrooms, 6 guests). The import guards in the next cell make the two optional dependencies explicit (dotenv, semantic_kernel): if one is missing, the notebook prints it and continues in degraded mode. The other dependencies (reportlab, openai, pypdf) import without a guard: they are required for the generation part, and their absence will show up in the ImportError of their cell.
# Import guards - availability flags for external dependencies
try:
from dotenv import load_dotenv
DOTENV_AVAILABLE = True
except ImportError:
DOTENV_AVAILABLE = False
print(f' dotenv non disponible - certaines fonctionnalites seront limitees')
try:
import semantic_kernel
SEMANTIC_KERNEL_AVAILABLE = True
except ImportError:
SEMANTIC_KERNEL_AVAILABLE = False
print(f' semantic_kernel non disponible - certaines fonctionnalites seront limitees')Global State & Configuration
Why a shared global state is indispensable in multi-agent: each agent (collector, generator, PDF producer) handles part of the problem but must see the whole set of constraints. The RecipeState class is that shared state — it carries the diet, the excluded ingredients, the number of guests, and the recipe under construction. Without global state, each agent would have to re-pass every constraint in its prompt (redundant, costly in tokens, prone to omissions); with global state, an agent reads state.diet and acts accordingly. It is the classic-AI blackboard pattern modernized: agents do not talk to each other directly, they communicate through the state — which decouples the agents and lets you add one (a nutritionist agent) without modifying the others.
# Etat partage du workflow : les agents (Chef, Critique...) lisent et ecrivent
# ces champs au fil du dialogue ; `ready_to_generate` bascule quand le Chef
# estime que les informations sont completes, `pdf_path` porte la sortie finale.
class RecipeState:
def __init__(self):
self.diet: str = ""
self.excluded_ingredients: list[str] = []
self.guests: int = 4
self.ingredients: list[str] = []
self.steps: list[str] = []
self.cooking_time: float = 0.0
self.ready_to_generate: bool = False
self.pdf_path: str = ""
print("Classe RecipeState définie")Classe RecipeState définie
Agent plugins and state modification functions
Why agents modify state through functions (plugins) rather than by generating free text: if an agent wrote « diet = vegetarian » in prose, the other agents would have to parse that sentence to extract the constraint — fragile and error-prone. The plugins expose typed functions (set_diet, exclude_ingredient, set_guests) that the kernel calls in a structured way: the constraint lands directly in the right field of RecipeState, with no parsing ambiguity. This is the gap between an agent that describes an action (« I note that the user is vegetarian ») and an agent that executes an action (state.diet = vegetarien) — the latter is reproducible and verifiable, the former depends on the reader’s interpretation.
import textwrap
from semantic_kernel.functions import kernel_function
from reportlab.pdfgen import canvas
class InputCollectorPlugin:
def __init__(self, state: RecipeState):
self.state = state
@kernel_function(name="set_diet", description="Définit le régime alimentaire")
def set_diet(self, diet: str) -> str:
self.state.diet = diet
return f"Régime {diet} enregistré"
@kernel_function(name="exclude_ingredient", description="Ajoute un ingrédient à exclure")
def exclude_ingredient(self, ingredient: str) -> str:
self.state.excluded_ingredients.append(ingredient)
return f"Ingrédient {ingredient} exclu"
@kernel_function(name="set_guests", description="Définit le nombre de convives")
def set_guests(self, guests: int) -> str:
self.state.guests = guests
return f"{guests} convives prévus"
class RecipeGeneratorPlugin:
def __init__(self, state: RecipeState):
self.state = state
@kernel_function(name="submit_recipe", description="Valide la recette générée")
def submit_recipe(self, ingredients: list[str], steps: list[str], cooking_time: float) -> str:
self.state.ingredients = ingredients
self.state.steps = steps
self.state.cooking_time = cooking_time
self.state.ready_to_generate = True
return "Recette validée et prête pour la génération PDF"
class PDFGeneratorPlugin:
def __init__(self, state: RecipeState):
self.state = state
@kernel_function(name="generate_pdf", description="Génère le PDF final")
def generate_pdf(self, output_path: str) -> str:
c = canvas.Canvas(output_path)
PAGE_W, PAGE_H = 595, 842 # A4 en points
MARGIN_L, MARGIN_R, MARGIN_TOP, MARGIN_BOTTOM = 100, 80, 50, 50
LINE_H = 15
MAX_LINE_W = (PAGE_W - MARGIN_L - MARGIN_R) # 415 pts de large utile
y = PAGE_H - MARGIN_TOP
def draw_wrapped(text, x, y, font_size=10, indent=0):
"""Dessine text enveloppe sur MAX_LINE_W avec retour a la ligne."""
c.setFont("Helvetica", font_size)
avg_char_w = font_size * 0.5 # approximation ReportLab Helvetica
chars_per_line = int(MAX_LINE_W / avg_char_w) - indent
for line in textwrap.wrap(text, width=chars_per_line) or [""]:
if y < MARGIN_BOTTOM + LINE_H:
c.showPage() # pagination -- nouvelle page si debordement
c.setFont("Helvetica", font_size)
y = PAGE_H - MARGIN_TOP
c.drawString(x + indent, y, line)
y -= LINE_H
return y
c.setFont("Helvetica-Bold", 14)
c.drawString(MARGIN_L, y, "Recette personnalisée")
y -= 25
c.setFont("Helvetica", 10)
y = draw_wrapped(f"Pour {self.state.guests} personnes", MARGIN_L, y)
y = draw_wrapped(f"Régime: {self.state.diet}", MARGIN_L, y)
y -= 5
c.setFont("Helvetica-Bold", 11)
c.drawString(MARGIN_L, y, "Ingrédients:")
y -= LINE_H
c.setFont("Helvetica", 10)
for ing in (self.state.ingredients or []):
y = draw_wrapped(f"- {ing}", MARGIN_L, y, indent=15)
y -= 5
c.setFont("Helvetica-Bold", 11)
c.drawString(MARGIN_L, y, "Étapes:")
y -= LINE_H
c.setFont("Helvetica", 10)
for i, step in enumerate(self.state.steps or [], start=1):
y = draw_wrapped(f"{i}. {step}", MARGIN_L, y, indent=15)
y -= 5
c.setFont("Helvetica-Oblique", 10)
y = draw_wrapped(f"Temps de cuisson: {self.state.cooking_time} min", MARGIN_L, y)
c.save()
self.state.pdf_path = output_path
return f"PDF généré : {output_path}"
print("Imports Semantic Kernel OK")Imports Semantic Kernel OK
Guided example: nutrition estimation plugin (contribution by hellsgame14-create, PR #28531)
The existing plugins handle information collection and recipe generation; no nutritional information is provided. This lab submission adds a NutritionPlugin that estimates the calories per portion.
The approach: a reference table CALORIES_REF (ingredient → kcal/100 g) is defined inside the method. The ingredient list is read line by line; a regular expression extracts the mass ("200 g", "100g", decimal comma accepted). Two normalisations make the comparison robust: lowercasing, and removing accents through Unicode NFD normalisation, so that épinards in the text matches the key epinards. The first ingredient of the reference table found on the line is counted, then the total is divided by state.guests — after an explicit guard against guests <= 0. Note: the substring search ("riz" is also inside "surizu") is a possible improvement, taken up in the exercise below.
# Exemple guide : plugin d'estimation nutritionnelle -- NutritionPlugin
# (contribution de hellsgame14-create, PR #28531 -- code etudiant conserve tel quel)
class NutritionPlugin:
"""Plugin d'estimation nutritionnelle pour les recettes."""
def __init__(self, state: RecipeState):
self.state = state
@kernel_function(
name="estimate_nutrition",
description="Estime les calories par portion"
)
def estimate_nutrition(self, ingredients: str) -> str:
# Référentiel approximatif en kcal pour 100 g
CALORIES_REF = {
"poulet": 165,
"riz": 130,
"pates": 150,
"lentilles": 116,
"carottes": 41,
"courgette": 17,
"poivron": 31,
"tomates": 18,
"epinards": 23,
"oignons": 40,
"ail": 149,
"huile": 884,
"beurre": 717,
"fromage": 350,
"creme": 300,
"noix": 654,
"pois chiches": 164,
"pommes de terre": 77
}
import re
import unicodedata
def normaliser(texte):
texte = texte.lower()
texte = unicodedata.normalize("NFD", texte)
return "".join(
c for c in texte
if unicodedata.category(c) != "Mn"
)
total_calories = 0
lignes = ingredients.splitlines()
for ligne in lignes:
ligne = normaliser(ligne)
# Recherche de la quantité en grammes
match = re.search(r"(\d+(?:[.,]\d+)?)\s*g\b", ligne)
if not match:
continue
quantite = float(match.group(1).replace(",", "."))
# Recherche de l'ingrédient dans le référentiel
for ingredient, calories in CALORIES_REF.items():
if normaliser(ingredient) in ligne:
total_calories += (quantite / 100) * calories
break
# Calcul par personne
if self.state.guests <= 0:
return "Erreur : nombre de convives invalide."
calories_par_portion = total_calories / self.state.guests
result = (
f"Calories totales estimées : {total_calories:.0f} kcal\n"
f"Nombre de personnes : {self.state.guests}\n"
f"Calories par portion : {calories_par_portion:.0f} kcal"
)
return result
print("NutritionPlugin défini avec succès")NutritionPlugin défini avec succès
Exercise 2: plugin auditing a shopping list
The previous example estimates calories and silently ignores what it does not recognise. An agent preparing a recipe needs the opposite: knowing what was not understood, and comparing two lists of ingredients.
Objective: write AuditPlugin with a method auditer(liste: str) -> str annotated @kernel_function, which returns the list of unrecognised lines (neither a mass nor a known ingredient) and the total in grams.
Hints: - # Étape 1: reuse a CALORIES_REF reference table and the normaliser function from the example (copy them into the method or define them outside). - # Étape 2: accept kg in addition to g ("1,2 kg de farine" is worth 1200 g) — the example reads grams only. - # Étape 3: a line without a mass or without a known ingredient goes into the list of unrecognised lines; the example skips it, here it is reported. - # Indice: the key "riz" is a substring of "surizu"; splitting the line into words (split()) avoids this false positive.
class AuditPlugin:
"""Plugin qui rapporte les lignes non reconnues et pese une liste de courses."""
def __init__(self, state: RecipeState):
self.state = state
@kernel_function(name="auditer_liste", description="Rapporte les lignes non reconnues et le total en grammes")
def auditer(self, liste: str) -> str:
# TODO etudiant : referentiel d'ingredients + normaliser (accent-insensible)
CALORIES_REF = {} # TODO etudiant : remplir quelques entrees
non_reconnues = [] # TODO etudiant : lignes sans masse OU sans ingredient connu
total_grammes = 0 # TODO etudiant : additionner g et kg (1 kg = 1000 g)
result = None # TODO etudiant : formater "non reconnues" + "total en grammes"
return result
# Temoin : une liste melant g, kg, ligne inconnue et faux positif "surizu"
_extrait = (
"200 g de poulet\n"
"1,2 kg de farine\n"
"une pincee de sel\n"
"50 g de surizu\n"
)
print("Exercice a completer : AuditPlugin")Exercice a completer : AuditPlugin
Creating agents
Why several agents rather than a single « generate a recipe » prompt: a single agent would have to handle simultaneously the collection of criteria, the generation of the recipe, and the production of the PDF deliverable — three cognitively different roles, each with its own prompt and reasoning system. Splitting into specialized agents (an empathetic collector that asks the right questions, a creative generator that proposes, a PDF producer that finalizes the deliverable) follows the single responsibility principle applied to LLMs: each agent has a clear role, a focused prompt, and a measurable success criterion. This is also what makes the system debuggable — if a recipe violates a constraint, you know to interrogate the prompt and the functions of the agent concerned (here, the generator).
import os
from dotenv import load_dotenv
from openai import AsyncOpenAI
from semantic_kernel import Kernel
from semantic_kernel.agents import ChatCompletionAgent
from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion
load_dotenv()
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
CHAT_MODEL = os.getenv("OPENAI_CHAT_MODEL", "gpt-5-mini")
def build_kernel(plugin, plugin_name: str) -> Kernel:
"""Cree un kernel avec un service de chat OpenAI et le plugin fourni.
Sans add_service, l'agent leve "No service found" des le premier appel LLM.
Note gpt-5 / function-tools : SK 1.42 refuse la valeur `none` pour
`reasoning_effort` (Literal["low","medium","high"] uniquement), mais
OpenAI l'accepte pour /v1/chat/completions et le requiert pour les
function tools (400 : "Function tools with reasoning_effort are not
supported for gpt-5-mini"). On force donc la valeur via `default_query`
sur le client AsyncOpenAI, ce qui ajoute le parametre a TOUTES les
requetes HTTP du service (chat, completions, etc.) sans validation
pydantic cote SK. `async_client=` est le seul point d'injection reconnu
par OpenAIChatCompletion.__init__ pour un client custom (le kwarg
`client=` n'apparait pas dans la signature).
"""
client = AsyncOpenAI(
api_key=OPENAI_API_KEY,
default_query={"reasoning_effort": "none"},
)
kernel = Kernel()
kernel.add_service(
OpenAIChatCompletion(
service_id="openai",
ai_model_id=CHAT_MODEL,
async_client=client,
)
)
kernel.add_plugin(plugin, plugin_name)
return kernel
shared_state = RecipeState()
# InputCollector
input_kernel = build_kernel(InputCollectorPlugin(shared_state), "input_plugin")
input_agent = ChatCompletionAgent(
kernel=input_kernel,
name="InputCollector",
instructions="""Collectez les informations utilisateur de maniere structuree.
- Demandez d'abord le regime alimentaire
- Puis les ingredients a exclure
- Enfin le nombre de convives"""
)
# RecipeGenerator avec son plugin
recipe_kernel = build_kernel(RecipeGeneratorPlugin(shared_state), "recipe_plugin")
recipe_agent = ChatCompletionAgent(
kernel=recipe_kernel,
name="RecipeGenerator",
instructions="""Generez des recettes en respectant les contraintes.
- Convertir les ingredients en liste Python
- Structurer les etapes de preparation
- Calculer le temps de cuisson"""
)
# PDFGenerator
pdf_kernel = build_kernel(PDFGeneratorPlugin(shared_state), "pdf_plugin")
pdf_agent = ChatCompletionAgent(
kernel=pdf_kernel,
name="PDFGenerator",
instructions="""Generez un PDF professionnel:
- Structurez en sections claires
- Utilisez une mise en page aeree
- Quand la recette est validee, appelez la fonction generate_pdf avec
output_path='recette_generee.pdf'"""
)
print("Imports et configuration OK")Imports et configuration OK
creating the conversation with termination and/or selection criteria
Why the conversation needs explicit termination criteria: without a stopping rule, the agents could loop forever (one agent asks for a clarification, the other answers, the first one asks again…). Termination criteria define when the conversation stops — here: as soon as the PDF deliverable is produced (the strategy polls the shared state), or after a maximum number of exchanges. Selection criteria define which agent speaks next — this notebook defines none: the default selection gives the floor to the agents in turn, in list order, which the executed conversation shows (InputCollector then RecipeGenerator then PDFGenerator). These two mechanisms turn a potentially chaotic stream of LLM exchanges into an ordered protocol with a guaranteed beginning, middle and end.
from semantic_kernel.agents import AgentGroupChat
from pydantic import PrivateAttr
from semantic_kernel.agents.strategies import TerminationStrategy
class ReadyTerminationStrategy(TerminationStrategy):
_state: RecipeState = PrivateAttr()
def __init__(self, state: RecipeState, **kwargs):
super().__init__(**kwargs)
self._state = state
async def should_agent_terminate(self, agent, history):
# Terminer sur le LIVRABLE produit (pdf_path), pas sur la demande
# de le produire (ready_to_generate) : sinon la conversation
# s'arrête exactement au tour où PDFGenerator devrait parler.
return bool(self._state.pdf_path)
group_chat = AgentGroupChat(
agents=[input_agent, recipe_agent, pdf_agent],
termination_strategy=ReadyTerminationStrategy(shared_state, maximum_iterations=12),
)
print("Imports agents OK")Imports agents OK
Main loop
Why the main loop orchestrates instead of executing sequentially: the loop does not stop after one round per agent — as long as the deliverable is not produced (and up to the iteration maximum), the conversation resumes: an agent can take the floor again on the next round to complete whatever is missing. This is the difference between a pipeline (a single pass, no return) and a conversation (iterative, with feedback). The main loop is the conductor: it reads the state, gives the floor to the next agent (default selection: round-robin), executes the agent, checks the termination criteria, and repeats until convergence. This is what allows the system to correct its own errors instead of propagating them.
# Fallback: s'assurer que group_chat est défini
try:
group_chat
except NameError:
print("⚠️ group_chat non défini - vérifiez que la cellule précédente a été exécutée")
group_chat = None
from semantic_kernel.contents import ChatMessageContent, AuthorRole
async def recipe_workflow():
if group_chat is None:
print("❌ Impossible d'exécuter: group_chat non initialisé")
return
# En mode batch (Papermill/CI), stdin n'existe pas : demande de recette
# fixée -- même patron que Medical-Chatbot et Fort-Boyard.
if BATCH_MODE:
recipe_query = (
"Je souhaite une recette végétarienne pour 6 personnes, "
"sans champignons ni produits laitiers."
)
print(f"[Batch] Demande de démonstration : {recipe_query}")
else:
recipe_query = input("Décrivez votre demande de recette : ")
# Amorcer la conversation (API SK 1.42 : add_chat_message est asynchrone,
# l'appeler sans await laisse un coroutine jamais attendue).
await group_chat.add_chat_message(
ChatMessageContent(role=AuthorRole.USER, content=recipe_query)
)
try:
async for message in group_chat.invoke():
print(f"[{message.name}] {message.content}")
except Exception as e:
print(f"Erreur lors de la génération: {str(e)}")
print("\nProcessus terminé")
await recipe_workflow()[Batch] Demande de démonstration : Je souhaite une recette végétarienne pour 6 personnes, sans champignons ni produits laitiers.
[InputCollector] Parfait — voici une recette végétarienne (et végétalienne) pour 6 personnes, sans champignons ni produits laitiers : Curry de pois chiches et légumes rôtis au lait de coco, servi avec du riz basmati.
Ingrédients (6 personnes)
- 450–500 g de riz basmati sec (environ 75–85 g par personne)
- 3 boîtes de pois chiches (environ 3 x 400 g = 1200 g, égouttés ≈ 750–800 g) ou 700–800 g de pois chiches cuits maison
- 2 patates douces moyennes (≈600–700 g), pelées et coupées en cubes
- 4 carottes, coupées en tronçons
- 2 poivrons (rouge et/ou jaune), épépinés et coupés en lanières
- 1 oignon jaune ou rouge, émincé
- 3 gousses d’ail, hachées
- 30 g de gingembre frais, râpé (ou 1–2 c. à café de gingembre en poudre si nécessaire)
- 1 boîte (400 ml) de lait de coco (vérifier qu’il n’y a pas d’additifs indésirables)
- 1 boîte (400 g) de tomates concassées (ou 4 tomates fraîches mûres hachées)
- 250 ml de bouillon de légumes (ou eau)
- 2 c. à soupe d’huile d’olive ou d’huile neutre
- 2–3 c. à soupe de pâte de curry doux ou 2 c. à soupe de curry en poudre (ajuster selon goût)
- 1 c. à café de curcuma
- 1 c. à café de cumin moulu
- 1/2 c. à café de piment en poudre ou flocons (facultatif)
- Sel et poivre au goût
- Jus d’un citron vert (ou citron)
- Quelques poignées d’épinards frais ou de chou kale (facultatif)
- Coriandre fraîche pour servir (facultatif)
- Graines de sésame ou noix de cajou grillées (facultatif pour le croustillant — vérifier tolérances allergènes)
Temps
- Préparation : 20–25 min
- Cuisson : 30–35 min
- Total : ~55–60 min
Préparation
1. Préchauffer le four à 200 °C.
2. Préparer les légumes à rôtir : patates douces et carottes coupées en cubes/tronçons, poivrons en lanières. Mélanger avec 1 c. à soupe d’huile, sel et poivre. Étaler sur une plaque et rôtir 20–25 min, jusqu’à tendreté et légère caramélisation (retourner à mi-cuisson).
3. Pendant ce temps, rincer le riz et le cuire selon les instructions du paquet (environ 12–15 min). Réserver au chaud.
4. Dans une grande sauteuse ou casserole, chauffer 1 c. à soupe d’huile à feu moyen. Ajouter l’oignon et cuire 4–5 min jusqu’à translucide. Ajouter l’ail et le gingembre, cuire 1 min.
5. Ajouter la pâte de curry (ou curry en poudre), curcuma, cumin et piment; faire revenir 1 min pour libérer les arômes.
6. Verser les tomates concassées, le lait de coco et le bouillon. Porter à ébullition douce, puis réduire le feu.
7. Ajouter les pois chiches égouttés et rincés. Laisser mijoter 10–12 min pour que les saveurs se mélangent et que la sauce épaississe légèrement. Ajouter sel et poivre au goût.
8. Incorporer les légumes rôtis à la casserole. Si vous utilisez des épinards ou du kale, ajoutez-les en fin de cuisson pour qu’ils flétrissent.
9. Ajuster l’acidité avec le jus de citron vert. Goûter et rectifier épices/sel.
10. Servir le curry chaud sur un lit de riz basmati, garnir de coriandre fraîche et de quelques noix/graines si désiré.
Variantes et substitutions
- Plus de protéines : ajouter du tofu ferme grillé ou du tempeh poêlé (sans produits laitiers).
- Version plus crémeuse : augmenter la quantité de lait de coco (vérifier l’étiquette) ou ajouter une cuillère de purée d’amande (si tolérée).
- Remplacer le riz par du quinoa ou du riz complet (temps de cuisson à ajuster).
- Si vous aimez épicé, ajoutez plus de piment ou du gingembre frais.
Conseils pratiques
- Préparation à l’avance : le curry se conserve très bien et gagne même en goût le lendemain. Conserver 3–4 jours au réfrigérateur dans un récipient hermétique.
- Congélation : portionner sans le riz, congeler jusqu’à 2 mois. Décongeler au réfrigérateur la veille et réchauffer doucement.
- Ajuster la quantité de liquide si vous préférez une sauce plus épaisse ou plus fluide.
Allergènes / remarques
- Recette sans produits laitiers et sans champignons. Si vous ajoutez noix de cajou ou graines, mentionnez allergènes.
- La noix de coco (lait de coco) est techniquement un fruit à coque par la législation mais beaucoup de personnes allergiques aux fruits à coque la tolèrent ; vérifiez selon les allergies.
Souhaitez-vous que j’adapte la recette (par ex. plus épicée, sans noix, version sans gluten garantie avec substitutions), ou que je vous fournisse une liste de courses imprimable ?
[RecipeGenerator] Recette validée. Voici la version finale, structurée selon vos contraintes et prête à l'emploi.
Détails fournis au plugin
- Ingrédients (liste Python) : ['450-500 g de riz basmati sec', '3 boîtes de pois chiches (≈1200 g, égouttés ≈750-800 g) ou 700-800 g pois chiches cuits', '2 patates douces moyennes (≈600-700 g), pelées et coupées en cubes', '4 carottes, coupées en tronçons', '2 poivrons (rouge/jaune), épépinés et coupés en lanières', '1 oignon, émincé', "3 gousses d'ail, hachées", "30 g de gingembre frais, râpé (ou 1-2 c. à café de gingembre en poudre)", '1 boîte (400 ml) de lait de coco', '1 boîte (400 g) de tomates concassées (ou 4 tomates fraîches)', '250 ml de bouillon de légumes ou eau', "2 c. à soupe d'huile d'olive ou huile neutre", "2-3 c. à soupe de pâte de curry doux ou 2 c. à soupe de curry en poudre", "1 c. à café de curcuma", "1 c. à café de cumin moulu", "1/2 c. à café de piment en poudre ou flocons (facultatif)", 'Sel et poivre', "Jus d'un citron vert (ou citron)", "Quelques poignées d'épinards frais ou chou kale (facultatif)", 'Coriandre fraîche pour servir (facultatif)', 'Graines de sésame ou noix de cajou grillées (facultatif)']
- Étapes : ['Préchauffer le four à 200 °C.', 'Couper les patates douces et les carottes en cubes/tronçons ; couper les poivrons en lanières.', "Mélanger les patates douces, carottes et poivrons avec 1 c. à soupe d'huile, sel et poivre ; étaler sur une plaque allant au four.", "Rôtir les légumes 20-25 min à 200 °C, en les retournant à mi-cuisson, jusqu'à ce qu'ils soient tendres et légèrement caramélisés.", "Rincer le riz et le cuire selon les instructions du paquet (environ 12-15 min). Maintenir au chaud.", "Dans une grande sauteuse, chauffer 1 c. à soupe d'huile à feu moyen ; ajouter l'oignon et cuire 4-5 min jusqu'à translucide.", "Ajouter l'ail et le gingembre ; cuire 1 min.", "Ajouter la pâte de curry (ou curry en poudre), le curcuma, le cumin et le piment ; faire revenir 1 min pour libérer les arômes.", "Verser les tomates concassées, le lait de coco et le bouillon ; porter à légère ébullition puis réduire le feu.", "Ajouter les pois chiches égouttés et rincés ; laisser mijoter 10-12 min pour que les saveurs se mélangent et que la sauce épaississe.", "Incorporer les légumes rôtis à la sauce ; ajouter les épinards ou le kale en fin de cuisson pour qu'ils flétrissent.", "Rectifier l'assaisonnement avec sel, poivre et jus de citron vert ; goûter et ajuster les épices.", "Servir le curry chaud sur le riz basmati, garnir de coriandre fraîche et de graines/noix si désiré.", "Conserver au réfrigérateur 3-4 jours ou congeler sans le riz (jusqu'à 2 mois).']
- Temps de cuisson calculé (minutes) : 60
Would you like a printable shopping list or a version with calories and nutrition per portion?
[PDFGenerator] Le PDF a été généré : recette_generee.pdf
Voici la recette incluse dans le PDF :
- Curry de pois chiches et légumes rôtis au lait de coco (végétarien, sans champignons, sans produits laitiers)
Si vous voulez des modifications (format, ajout d'images, liste de courses séparée, informations nutritionnelles), dites-moi ce que vous souhaitez.
Processus terminé
Reading the generation — the multi-agent system produced a vegetarian recipe (the model varies the recipe at each run — we do not freeze its name in the notebook) for 6 people that respects the collected constraints: no mushrooms and no dairy products. The [InputCollector] first recorded the three criteria (diet, exclusions, guests), then the [RecipeGenerator] proposed a suitable recipe — here we see the two agents collaborating through the shared state.
What this output demonstrates about the multi-agent system: the recipe is not a free-form response to “write a vegetarian recipe” — it is the result of a protocol in which each constraint was explicitly collected and then propagated to the generator via RecipeState. If we changed “6 guests” to “2 guests,” the recipe quantities would adjust because the generator reads state.guests. This is the added value of the architecture compared with a monolithic prompt: the constraints are structured and traceable, not buried in a sentence. This is also what makes the system reusable for other cases (meal menu, shopping list) by changing the plugins, not by rewriting the prompt.
Guided example: validating the constraints before generation (contribution by hellsgame14-create, PR #28531)
The current workflow launches generation without checking that the constraints are coherent. This lab submission implements valider_contraintes, which checks the coherence of the user preferences before passing them to the agents.
The approach: errors are accumulated in a list instead of returning at the first anomaly — the user sees everything at once. Six rules: guests <= 0, negative cooking time, a diet outside the recognised list (both spellings, with and without accent, are accepted), excluded ingredients present in the recipe, and two incompatible ingredient lists (vegan, then vegetarian via elif, which thereby inherits from the first). The final boolean is simply len(erreurs) == 0. Note: the exclusion comparison is done by substring, see the next exercise.
# Exemple guide : validation des contraintes avant generation -- valider_contraintes
# (contribution de hellsgame14-create, PR #28531 -- code etudiant conserve tel quel)
def valider_contraintes(state: RecipeState) -> tuple[bool, list[str]]:
erreurs = []
# 1. Vérification du nombre de convives
if state.guests <= 0:
erreurs.append(
"Le nombre de convives doit être supérieur à zéro."
)
# 2. Vérification du temps de cuisson
if state.cooking_time < 0:
erreurs.append(
"Le temps de cuisson ne peut pas être négatif."
)
# 3. Vérification du régime alimentaire
regime = state.diet.lower()
if regime not in ["", "omnivore", "végétarien", "vegetarien", "vegan", "végane"]:
erreurs.append(
"Le régime alimentaire indiqué n'est pas reconnu."
)
# 4. Vérification des ingrédients exclus
ingredients = [
ingredient.lower()
for ingredient in state.ingredients
]
for ingredient_exclu in state.excluded_ingredients:
for ingredient in ingredients:
if ingredient_exclu.lower() in ingredient:
erreurs.append(
f"L'ingrédient {ingredient_exclu} est interdit "
"mais apparaît dans la recette."
)
# 5. Vérification des ingrédients incompatibles avec le régime vegan
if regime in ["vegan", "végane"]:
ingredients_interdits = [
"viande",
"poulet",
"boeuf",
"porc",
"poisson",
"saumon",
"lait",
"fromage",
"beurre",
"crème",
"oeuf",
"miel"
]
for ingredient in ingredients:
for interdit in ingredients_interdits:
if interdit in ingredient:
erreurs.append(
f"Ingrédient incompatible avec le régime vegan : "
f"{ingredient}"
)
# 6. Vérification des ingrédients incompatibles avec le régime végétarien
elif regime in ["végétarien", "vegetarien"]:
ingredients_interdits = [
"viande",
"poulet",
"boeuf",
"porc",
"poisson",
"saumon",
"jambon",
"lard"
]
for ingredient in ingredients:
for interdit in ingredients_interdits:
if interdit in ingredient:
erreurs.append(
f"Ingrédient incompatible avec le régime "
f"végétarien : {ingredient}"
)
# Résultat final
est_valide = len(erreurs) == 0
return est_valide, erreurs
print("Fonction de validation définie avec succès")Fonction de validation définie avec succès
Exercise 3: repairing an invalid state instead of only reporting it
The previous example detects incoherences and returns them. An agent collecting the preferences must go further: correcting what can be corrected without ambiguity, and reporting only the rest.
Objective: write reparer_etat(state: RecipeState) -> tuple[RecipeState, list[str]] which returns the corrected state and the list of errors that remain (without duplicates, even if the same problem is detected twice).
Hints: - # Étape 1: guests <= 0 is repairable → reset the value to the default 4 and add a single error “number of guests reset to 4”, whatever the number of calls. - # Étape 2: an excluded ingredient that appears in state.ingredients is repairable → remove it from the list, one error per removed ingredient. - # Étape 3: an unknown diet is not repairable → keep it in the errors, unmodified. - # Indice: compare word by word (split()), not by substring — "riz" must exclude "riz basmati" but not "surizu". valider_contraintes from the example can be used to re-read the corrected state.
def reparer_etat(state: RecipeState) -> tuple[RecipeState, list[str]]:
erreurs = [] # TODO etudiant : erreurs qui RESTENT apres reparation, sans doublon
# Etape 1 : guests <= 0 -> remettre 4, une seule erreur
# Etape 2 : ingredient exclu present dans state.ingredients -> le retirer, une erreur par retrait
# Etape 3 : regime inconnu -> non reparable, reste dans les erreurs
return state, erreurs # TODO etudiant : retourner l'etat corrige et les erreurs restantes
# Temoin : etat invalide sur les trois points, a reparer puis a relire
_etat = RecipeState()
_etat.guests = -2
_etat.diet = "carnivore"
_etat.excluded_ingredients = ["noix"]
_etat.ingredients = ["noix de pecan", "surizu", "courgette"]
_etat_corrige, _restent = reparer_etat(_etat)
print("Erreurs restantes :", _restent)
print("Exercice a completer : reparer_etat")Erreurs restantes : []
Exercice a completer : reparer_etat
PDF generation
Why export the recipe as a PDF: the PDF is the final deliverable — what the user takes away, prints, shares. The entire multi-agent pipeline leads to this document, produced by PDFGeneratorPlugin.generate_pdf (reportlab, imported with the plugins).
The orchestration trap lurking at this step: the conversation is driven by ReadyTerminationStrategy, which queries the shared state at the end of every turn. If the strategy terminates on ready_to_generate — the flag RecipeGenerator sets when it validates the recipe — the conversation stops exactly on the turn where PDFGenerator should speak: the agent is listed in the roster passed to AgentGroupChat, but it is structurally unreachable. No exception is raised; the loop ends cleanly, and the failure reads as a rendering-tool problem (PDF library, fonts) when the actual cause is the stop condition. The rule applied here: terminate on the produced deliverable (state.pdf_path), not on the request to produce it.
import os
PDF_PATH = "recette_generee.pdf"
# Filet de sécurité : si l'agent PDFGenerator n'a pas invoqué generate_pdf
# pendant la conversation, on produit le livrable directement via le même
# plugin que celui exposé à l'agent -- la capacité démontrée est identique.
if not shared_state.pdf_path:
pdf_plugin = PDFGeneratorPlugin(shared_state)
print(pdf_plugin.generate_pdf(PDF_PATH))
if shared_state.pdf_path and os.path.exists(shared_state.pdf_path):
taille = os.path.getsize(shared_state.pdf_path)
print(f"PDF présent sur le disque : {shared_state.pdf_path} ({taille} octets)")
else:
print("Aucun PDF produit : ni par l'agent, ni par le filet de sécurité.")PDF présent sur le disque : recette_generee.pdf (4332 octets)
The PDF file recette_generee.pdf is confirmed to be present on the disk with a size of a few kilobytes (the size varies depending on the generated recipe), validating that the generation produced a usable file.
import pypdf
import re
# Phase 1 -- extraction : on relit le PDF produit par la cellule precedente
# et on en fait un texte plat comparable a l'etat attendu.
pdf_path = shared_state.pdf_path
reader = pypdf.PdfReader(pdf_path)
pdf_text = chr(10).join(p.extract_text() or "" for p in reader.pages)
print(f"PDF généré avec succès: {pdf_path}")
print(f"Taille: {os.path.getsize(pdf_path)} octets")
print(f"Contenu extrait ({len(pdf_text)} caracteres):")
print(pdf_text)
def _norm(s):
# Normalisation commune : espaces multiples, casse et bordures ; le texte
# extrait d'un PDF contient des sauts de ligne au milieu des phrases.
return re.sub(r"\s+", " ", s).strip().lower()
def _endswith(s, n_words=2):
words = _norm(s).split()
return " ".join(words[-n_words:]) if len(words) >= n_words else _norm(s)
def _check_ingredient(ing, pdf_text):
"""Vrai si l'ingredient (quantite + nom) est present dans le PDF.
Test: chaine normalisee directe, OU variante sans virgule, OU split (nom + quantite)
tous deux presents. Necessaire car le PDF peut mettre l'ingredient sur plusieurs lignes ou
avec une virgule differente.
"""
pdf_n = _norm(pdf_text)
ing_n = _norm(ing)
if ing_n in pdf_n:
return True
ing_no_comma = ing_n.replace(",", " ")
if ing_no_comma in pdf_n:
return True
parts = [p.strip() for p in ing.split(",")]
if len(parts) == 2 and _norm(parts[0]) in pdf_n and _norm(parts[1]) in pdf_n:
return True
return False
def _check_step(s, pdf_text, n_min_overlap=0.4):
"""Vrai si l'etape est presente dans le PDF avec un overlap de mots >= n_min_overlap
ET les 2 derniers mots de l'etape sont dans le PDF (signe que la fin n'est pas
tronquee). Le seul debut [:30] de V4 ne protegeait pas contre la troncature finale.
"""
pdf_n = _norm(pdf_text)
s_n = _norm(s)
if s_n in pdf_n:
return True
s_words = s_n.split()
if not s_words:
return False
p_words = set(pdf_n.split())
overlap = sum(1 for w in s_words if w in p_words) / len(s_words)
# Garde anti-troncature : la fin de l'etape doit exister telle quelle.
end_ok = _endswith(s, 2) in pdf_n
return overlap >= n_min_overlap and end_ok
# Phase 2 -- assertions : chaque champ de l'etat partage doit se retrouver
# dans le PDF ; tout manquement leve une erreur (le carnet ne peut pas finir
# vert sur une recette incomplete).
missing = []
if not shared_state.diet or _norm(shared_state.diet) not in _norm(pdf_text):
missing.append(f"regime={shared_state.diet!r} absent du PDF")
if not shared_state.ingredients:
missing.append("ingredients vides")
else:
missing_ing = [i for i in shared_state.ingredients if not _check_ingredient(i, pdf_text)]
if missing_ing:
missing.append(
f"{len(missing_ing)}/{len(shared_state.ingredients)} ingredients absents: {missing_ing[:3]}"
)
if not shared_state.steps:
missing.append("etapes vides")
else:
missing_step = [s for s in shared_state.steps if not _check_step(s, pdf_text)]
if missing_step:
missing.append(
f"{len(missing_step)}/{len(shared_state.steps)} etapes absentes: {missing_step[0][:50]}"
)
if missing:
raise RuntimeError(
f"PDF incomplet -- {len(missing)} chaine(s) manquante(s) : "
+ " / ".join(missing)
)
print("OK : PDF exporte la recette complete (regime + tous ingredients + toutes etapes).")PDF généré avec succès: recette_generee.pdf
Taille: 4332 octets
Contenu extrait (2575 caracteres):
Recette personnalisée
Pour 6 personnes
Régime: végétarien
Ingrédients:
- 450-500 g de riz basmati sec
- 3 boîtes de pois chiches (≈1200 g, égouttés ≈750-800 g) ou 700-800
g pois chiches cuits
- 2 patates douces moyennes (≈600-700 g), pelées et coupées en cubes
- 4 carottes, coupées en tronçons
- 2 poivrons (rouge/jaune), épépinés et coupés en lanières
- 1 oignon, émincé
- 3 gousses d'ail, hachées
- 30 g de gingembre frais, râpé (ou 1-2 c. à café de gingembre en
poudre)
- 1 boîte (400 ml) de lait de coco
- 1 boîte (400 g) de tomates concassées (ou 4 tomates fraîches)
- 250 ml de bouillon de légumes ou eau
- 2 c. à soupe d'huile d'olive ou huile neutre
- 2-3 c. à soupe de pâte de curry doux ou 2 c. à soupe de curry en
poudre
- 1 c. à café de curcuma
- 1 c. à café de cumin moulu
- 1/2 c. à café de piment en poudre ou flocons (facultatif)
- Sel et poivre
- Jus d'un citron vert (ou citron)
- Quelques poignées d'épinards frais ou chou kale (facultatif)
- Coriandre fraîche pour servir (facultatif)
- Graines de sésame ou noix de cajou grillées (facultatif)
Étapes:
1. Préchauffer le four à 200 °C.
2. Couper les patates douces et les carottes en cubes/tronçons ;
couper les poivrons en lanières.
3. Mélanger les patates douces, carottes et poivrons avec 1 c. à
soupe d'huile, sel et poivre ; étaler sur une plaque allant au four.
4. Rôtir les légumes 20-25 min à 200 °C, en les retournant à mi-
cuisson, jusqu'à ce qu'ils soient tendres et légèrement caramélisés.
5. Rincer le riz et le cuire selon les instructions du paquet
(environ 12-15 min). Maintenir au chaud.
6. Dans une grande sauteuse, chauffer 1 c. à soupe d'huile à feu
moyen ; ajouter l'oignon et cuire 4-5 min jusqu'à translucide.
7. Ajouter l'ail et le gingembre ; cuire 1 min.
8. Ajouter la pâte de curry (ou curry en poudre), le curcuma, le
cumin et le piment ; faire revenir 1 min pour libérer les arômes.
9. Verser les tomates concassées, le lait de coco et le bouillon ;
porter à légère ébullition puis réduire le feu.
10. Ajouter les pois chiches égouttés et rincés ; laisser mijoter
10-12 min pour que les saveurs se mélangent et que la sauce
épaississe.
11. Incorporer les légumes rôtis à la sauce ; ajouter les épinards
ou le kale en fin de cuisson pour qu'ils flétrissent.
12. Rectifier l'assaisonnement avec sel, poivre et jus de citron
vert ; goûter et ajuster les épices.
13. Servir le curry chaud sur le riz basmati, garnir de coriandre
fraîche et de graines/noix si désiré.
14. Conserver au réfrigérateur 3-4 jours ou congeler sans le riz
(jusqu'à 2 mois).
Temps de cuisson: 60.0 min
OK : PDF exporte la recette complete (regime + tous ingredients + toutes etapes).
Reading the PDF deliverable — the conversation played out the three expected roles: [InputCollector] recorded the constraints in the shared state, [RecipeGenerator] validated the recipe (ready_to_generate flag set), then [PDFGenerator] took its turn by invoking generate_pdf — this is precisely the turn that the original stopping condition (ready_to_generate) cut off. The verification cell confirms the file on disk (path + size in bytes), then the next cell displays the success branch with the structured content of the shared state.
What this example demonstrates: the termination strategy of an AgentGroupChat is not a cosmetic detail — it is what decides which agents actually exist in the conversation. A flag set one turn too early makes an agent in the list unreachable with no visible error: the loop ends cleanly, the state remains incomplete, and instinct leads one to blame the external tool. Diagnosing this flaw requires reading the sequence of turns (who spoke? who never spoke?), not the exceptions — there are none. The reasoning/execution boundary remains real (the reportlab plugin can fail independently of the LLM), but the failure observed before the correction was an orchestration flaw, not a rendering flaw.
Conclusion
This notebook implemented a multi-agent collaboration to generate a personalized recipe and produce a PDF.
Key points:
- Shared state: the
RecipeStateclass serves as shared memory for the three agents. Each plugin reads from and writes to this single instance, which makes it possible to pass the user constraints through to PDF generation. - Plugins and
@kernel_function: the@kernel_functiondecorator exposes Python methods as tools callable by the LLM (set_diet,submit_recipe,generate_pdf). AgentGroupChatorchestration: theInputCollector,RecipeGenerator, andPDFGeneratoragents interact in a group conversation, each with its own kernel and chat service.- Termination strategy:
ReadyTerminationStrategyqueries the shared state (pdf_path) to stop the loop as soon as the PDF deliverable is produced — terminating earlier (onready_to_generate) would leave thePDFGeneratoragent unreachable. - Service configuration: each kernel must receive a service via
add_service(hereOpenAIChatCompletion), otherwise invocation fails withNo service found.
To go further:
- Enhance the PDF with a styled layout (sections, images, ingredients table) via
reportlab.platypus. - Connect a nutritional API to calculate the recipe’s calorie intake.
- Generate an illustration of the dish with an image model and insert it into the document.