Verbal Duel: Barbie vs Shrek’s Donkey

Lancer : Codespaces Colab
# Parameters
BATCH_MODE = "true"

Introduction - barbie schreck

Navigation : Index

This notebook covers the main concepts and techniques of barbie schreck. The learning objectives include understanding the fundamentals, putting them into practice through exercises, and analyzing results.

Prerequisites : basic knowledge of Python and algorithms.

Adapted from an EPF student production: Carole & Cléo. Universalization: refactor #890.

Notebook using Semantic Kernel to run a constrained debate between two agents — Barbie and Shrek’s Donkey — where each of the Donkey’s replies is illustrated by an image generated on the series’ ComfyUI instance.

The pedagogical thread unfolds in four acts:

  1. Constraint — a linguistic style (rhyme, Shakespeare, song) is drawn at random and imposed on both agents through their system instructions;
  2. Agents — two ChatCompletionAgent with opposite personalities, each on its own kernel;
  3. Plugin — an ImagePlugin wired to the Donkey illustrates each reply through the ComfyUI instance’s API;
  4. Orchestration — an AgentGroupChat + a termination strategy keep the duel running up to MAX_TURNS.

The three original exercises were solved by an APP3A group (PR #21089): their solutions are integrated as guided examples 1, 2 and 3, each followed by the reading of its result and its limits. Three replacement exercises extend them in the « 9. Exercices » section.

# Import guards - availability flags for external dependencies

try:
    from IPython.display import display, Audio, Image as IPImage
    IPYTHON_AVAILABLE = True
except ImportError:
    IPYTHON_AVAILABLE = False
    print(f'  IPython non disponible - certaines fonctionnalites seront limitees')

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')

Initial configuration

This cell imports all the required building blocks and prepares the environment:

  • os, random, logging — standard utilities (environment variables, constraint draw, logs);
  • dotenv — load_dotenv() loads the API keys from the local .env file (see OPENAI_API_KEY used below);
  • semantic_kernel — the core: Kernel, ChatCompletionAgent, AgentGroupChat, the OpenAI connectors (chat + text-to-image), kernel_function, ChatMessageContent/AuthorRole.

The logging.basicConfig(level=logging.INFO) enables the INFO logs that make the debate execution readable (agent selection, API usage). The Imports et configuration OK output confirms that every dependency is present on the execution machine.

The # Import guards cell above plays a pre-flight role: it checks the availability of IPython, dotenv and semantic_kernel and defines flags (IPYTHON_AVAILABLE, etc.) — but these guards do not protect the notebook: the next cell imports dotenv and semantic_kernel at module level, unguarded, so a missing dependency interrupts execution at that import. The flags document the machine’s state; they stop nothing.

import os
import random
import logging
from pathlib import Path
from dotenv import load_dotenv
from semantic_kernel import Kernel
from semantic_kernel.agents import ChatCompletionAgent, AgentGroupChat
from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion
from semantic_kernel.functions import kernel_function, KernelArguments
from semantic_kernel.contents import ChatMessageContent, AuthorRole


def _charger_env_genai():
    """Charge le .env de la serie GenAI en remontant depuis le dossier du carnet.

    load_dotenv() nu chercherait l'emplacement de l'appelant, pas le dossier du
    carnet : sous papermill comme dans un terminal, la remontee explicite depuis
    le repertoire courant est la seule forme fiable.
    """
    # Remontee d'au plus 6 niveaux : le carnet vit a 3 niveaux sous la racine
    # de la serie ; la marge couvre les executions depuis un autre cwd.
    courant = Path.cwd()
    for _ in range(6):
        env = courant / ".env"
        if env.exists():
            load_dotenv(dotenv_path=env, override=True)
            return f"{env.parent.name}/{env.name}"
        courant = courant.parent
    return None


# Point d'entree unique pour les cles de la serie (endpoint du modele de chat).
CHEMIN_ENV = _charger_env_genai()
print("Env de la série chargé :", CHEMIN_ENV or "introuvable")

# Journalisation shared par le duel et les strategies de terminaison.
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger('BarbieVsAne')
print("Imports et configuration OK")
Env de la série chargé : GenAI/.env
Imports et configuration OK

Definition of Linguistic Constraints

The debate only becomes interesting if the replies follow a rule. The CONTRAINTES list defines three possible styles, each as a (name, description) tuple:

Name Rule
Rime Each reply contains a perfect rhyme
Shakespeare Imitate Shakespeare’s theatrical style
Chanson Answer to the tune of I’m a Believer

random.choice draws a constraint at random on every execution: the draw is therefore not reproducible — the effective constraint is the one the next cell displays, and the debate replies follow it. (In the committed output, Chanson — « Answer to the tune of ‘I’m a Believer’ » — was drawn.) The (name, description) tuple structure is the one Exercise 1 asks you to extend: the description is interpolated into the agents’ instructions, so any new entry in the list automatically propagates to both duelists’ behavior.

# Contraintes declaratives du duel : un nom court et une phrase d'instruction
# qui sera injectee dans les instructions des agents (section suivante).
CONTRAINTES = [
    ("Rime", "Chaque réplique doit contenir une rime parfaite"),
    ("Shakespeare", "Imiter le style théâtral de Shakespeare"),
    ("Chanson", "Répondre sur l'air de 'I'm a Believer'")
]

# Tirage au sort : chaque execution impose une contrainte differente au duel.
contrainte_choisie = random.choice(CONTRAINTES)
print(f"Contrainte choisie : {contrainte_choisie[0]}")
print("Contraintes de debate definies")
Contrainte choisie : Chanson
Contraintes de debate definies

Guided example 1 — Adding custom linguistic constraints

Student contribution from the group of PR #21089, integrated as a guided example.

The CONTRAINTES list contains three styles (Rhyme, Shakespeare, Song). The example adds three entries in the (name, description) format. Since the description is interpolated into both agents’ system instructions, each added entry changes their behavior without touching the rest of the setup.

What the code below does:

  • # Étape 1 — define the new constraints in NOUVELLES_CONTRAINTES (Haiku, Python Code, Pirate);
  • # Étape 2 — attach them to CONTRAINTES with extend, then display the full list.

The hint from the original statement is preserved: respect the existing format ("Nom", "Description de la règle").

# Exemple guidé 1 — Ajout de contraintes linguistiques personnalisées.
# Contribution étudiante du groupe de la PR #21089, intégrée comme exemple guidé.

# Etape 1 : definir les nouvelles contraintes (format : (nom, description))
NOUVELLES_CONTRAINTES = [
    ("Haiku", "Chaque réplique doit être un haïku japonais : trois lignes de 5, 7 et 5 syllabes"),
    ("Code Python", "Répondre uniquement en syntaxe Python (print, def, if/else, boucles...)"),
    ("Pirate", "Parler comme un pirate : 'Arrr', 'matelot', 'par tous les kraken'..."),
]

# Etape 2 : les ajouter a CONTRAINTES
CONTRAINTES.extend(NOUVELLES_CONTRAINTES)

print(f"{len(CONTRAINTES)} contraintes disponibles :")
for nom, description in CONTRAINTES:
    print(f"  - {nom} : {description}")
6 contraintes disponibles :
  - Rime : Chaque réplique doit contenir une rime parfaite
  - Shakespeare : Imiter le style théâtral de Shakespeare
  - Chanson : Répondre sur l'air de 'I'm a Believer'
  - Haiku : Chaque réplique doit être un haïku japonais : trois lignes de 5, 7 et 5 syllabes
  - Code Python : Répondre uniquement en syntaxe Python (print, def, if/else, boucles...)
  - Pirate : Parler comme un pirate : 'Arrr', 'matelot', 'par tous les kraken'...

Reading the result — guided example 1

The list goes from 3 to 6 constraints, and the three new ones are displayed with their description: the format (nom, description) is indeed the one expected by the system instructions.

Limitation of the example, to know before using it. The duel constraint was chosen at random before this addition (contrainte_choisie = random.choice(CONTRAINTES), cell from the original list). The three new constraints therefore exist in CONTRAINTES, but the duel that follows still uses the one that was drawn. For a new constraint to actually be played, you must draw after extending the list — this is precisely what replacement exercise 1 does, by another route.

Kernel creation

create_kernel() instantiates a Semantic Kernel Kernel and registers the conversation service on it, identified by its service_id:

  • chat: OpenAIChatCompletion — the conversation model (id read from OPENAI_CHAT_MODEL_ID);
  • keys are read from the environment (os.getenv), never written in the notebook.

The service_id pattern is central: it is what lets agents find the right service, even when a kernel carries several. The function is called twice (one kernel per agent): each duelist has its own service stack, which isolates their calls.

Images do not go through a kernel service: they are produced by the series’ ComfyUI instance, called over HTTP by the plugin in the next section. The URL and token of this instance live in the series’ .env — never in a cell.

def create_kernel():
    # Fabrique de kernel : chaque agent recoit le sien (section Agent configuration),
    # tous pointent vers le meme service OpenAI-compatible de la serie.
    kernel = Kernel()
    kernel.add_service(OpenAIChatCompletion(
        service_id="chat",
        ai_model_id=os.getenv("OPENAI_CHAT_MODEL_ID"),
        api_key=os.getenv("OPENAI_API_KEY")
    ))
    return kernel

print("Fonction create_kernel définie")
Fonction create_kernel définie

Image generation plugin

ImagePlugin wraps the call to the series’ ComfyUI instance as a Semantic Kernel invocable function. The @kernel_function(name="generate_image", description="...") decorator exposes the generate method as a capability the kernel can invoke by name.

Implementation details:

  • transport and authentication: the shared client shared/helpers/comfyui_client.py reads COMFYUI_API_URL and the token from the series’ .env — the token never appears in a cell;
  • graph: the workflow qwen_image_2_1_text2image.json (folder scripts/genai-stack/workflows/qwen_image_2_1/) is loaded then converted from the UI format to the API format. It is this versioned file that describes the models used, not a copy pasted into the notebook;
  • applied template: each image starts from a template that names the subject (a grey donkey on four legs, standing on its hooves, long ears, elongated muzzle, short mane) and explicitly rules out what drifted in without it — horns, antlers, a human silhouette, a biped — before appending the visual description of the scene as Scène illustrée: …. The template is the GABARIT_ILLUSTRATION constant of the next cell;
  • text/image separation: Qwen-Image renders as lettering any text quoted in the prompt (measured on 2026-10-22: two cross-checked visual readings saw the lines drawn inside the image); the reply is therefore never passed as-is to the generator — decrire_scene_visuelle paraphrases it into visual terms through the kernel’s LLM, and the plugin only receives that description; the description is further constrained to the donkey alone (four legs, four hooves on the ground, no human character, no audience) — a freely described scene drifts towards the rearing posture or the duel’s opponent (round 3 of 2026-10-22), and the retained scene is displayed before each image;
  • robustness: on failure (unreachable instance, server-side execution error), the exception is logged (logger.error) and the method returns None — the debate continues without an illustration rather than stopping.

The received image is written to a temporary file, and it is its path that the method returns: the duel cell then displays it.

# Plugin de generation d'images : instance ComfyUI de la serie (Qwen-Image 2.1).
import json
import sys
import tempfile
from pathlib import Path


def _charger_aide_comfyui():
    """Importe le client partage de la serie GenAI (shared/helpers)."""
    courant = Path.cwd()
    for _ in range(6):
        aide = courant / "MyIA.AI.Notebooks" / "GenAI" / "shared" / "helpers"
        if aide.is_dir():
            if str(aide) not in sys.path:
                sys.path.insert(0, str(aide))
            break
        courant = courant.parent
    else:
        raise FileNotFoundError(
            "MyIA.AI.Notebooks/GenAI/shared/helpers introuvable depuis " + str(Path.cwd())
        )
    import comfyui_client
    return comfyui_client


comfyui = _charger_aide_comfyui()
client_comfyui = comfyui.load_from_env()
CHEMIN_WORKFLOW = comfyui.dossier_workflows_qwen_image_2_1() / "qwen_image_2_1_text2image.json"
WORKFLOW_IMAGE = comfyui.ui_vers_api(comfyui.charger_workflow_ui(CHEMIN_WORKFLOW))
GRAINE_IMAGE = 12345

# Sujet epingle. Un prompt libre (« style cartoon » + la replique seule) laisse le
# modele choisir le sujet : mesure du 2026-10-22, il a produit un ane a bois de
# cervide puis une silhouette bipede. Le gabarit nomme donc le sujet et ecarte
# explicitement ce qui a derive, AVANT la description de la scene.
GABARIT_ILLUSTRATION = (
    "Style cartoon comique, dessin animé pour enfants. "
    "Un âne gris vu de profil, strictement quadrupède : les quatre sabots "
    "posés au sol et les quatre pattes portant le poids, longues oreilles, "
    "museau allongé, crinière courte. Aucune pose cabrée, aucun appui sur "
    "les pattes arrière seules, aucune corne, aucun bois de cervidé, "
    "aucune silhouette humaine, pas de bipède. Aucun texte, aucune "
    "inscription, aucun lettrage dans l'image : la réplique ne doit pas "
    "y être écrite. "
    "Scène illustrée : {scene}"
)


# Separation texte/image : Qwen-Image rend en lettrage tout texte cite
# dans le prompt. Mesure du 2026-10-22 (deux QA visuelles croisees) : les
# paroles passees telles quelles etaient dessinees ; la scene est donc
# paraphrasee visuellement par le LLM du kernel, sans recopier la replique.
PROMPT_SCENE = (
    "Tu prépares une illustration où NE FIGURE QUE L'ÂNE. Décris en UNE "
    "phrase courte, uniquement en termes visuels, ce que fait l'Âne dans "
    "la réplique ci-dessous. Contraintes : l'âne est le seul personnage "
    "(aucun humain, aucune silhouette debout, aucun public, aucun autre "
    "animal), strictement à quatre pattes, les quatre sabots au sol, "
    "aucune pose cabrée ni redressée ; seuls l'âne et le décor (sol, "
    "rideau, lumière) apparaissent. Ne recopie aucun mot de la réplique : "
    "aucune citation. Réponds en français, en une seule phrase, sans "
    "guillemets.\n\n"
    "Réplique :\n{replique}"
)


async def decrire_scene_visuelle(kernel, replique):
    """Renvoie une description visuelle de la scène, sans aucun texte
    recopié de la réplique — le générateur dessine le texte qu'on cite.
    """
    resultat = await kernel.invoke_prompt(
        prompt=PROMPT_SCENE.format(replique=replique)
    )
    valeur = getattr(resultat, "value", resultat)
    if isinstance(valeur, list):
        valeur = "".join(getattr(m, "content", str(m)) or "" for m in valeur)
    scene = " ".join(str(valeur).split())
    return scene or "l'âne gris, seul, à quatre pattes, chante sur une scène de théâtre vide"


class ImagePlugin:
    def __init__(self, client, workflow, graine=GRAINE_IMAGE):
        self.client = client
        self.workflow = workflow
        self.graine = graine

    @kernel_function(name="generate_image", description="Genere une illustration via l'instance ComfyUI de la serie ; context = description visuelle de la scene, jamais la replique mot a mot")
    async def generate(self, context: str) -> str:
        try:
            # Copie : chaque replique part du graphe versionne, sans le modifier.
            prompt_api = json.loads(json.dumps(self.workflow))
            comfyui.noeud_de_classe(prompt_api, "CLIPTextEncode")["inputs"]["text"] = (
                GABARIT_ILLUSTRATION.format(scene=context)
            )
            comfyui.noeud_de_classe(prompt_api, "KSampler")["inputs"]["seed"] = self.graine
            prompt_id = self.client.queue_prompt(prompt_api)
            # 1800 s : une generation seule mesuree a 568 s le 2026-10-22,
            # et l'instance est partagee -- une requete en file depasse 900 s.
            resultat = self.client.wait_for_completion(prompt_id, timeout=1800)
            images = [im for sortie in resultat.get("outputs", {}).values()
                      for im in sortie.get("images", [])]
            if not images:
                logger.error("Instance ComfyUI : aucune image renvoyee")
                return None
            donnee = self.client.get_output_file(
                images[0]["filename"], images[0].get("subfolder", ""), images[0].get("type", "output")
            )
            chemin = Path(tempfile.gettempdir()) / f"barbie_ane_{prompt_id}.png"
            chemin.write_bytes(donnee)
            return str(chemin)
        except Exception as e:
            logger.error(f"Erreur generation image: {(str(e).splitlines() or [repr(e)])[0]}")
            return None


print("Classe ImagePlugin définie (instance ComfyUI)")
Classe ImagePlugin définie (instance ComfyUI)

Agent configuration

Each duelist is a ChatCompletionAgent with its own kernel (kernel_barbie, kernel_ane) and distinct system instructions:

  • Barbie: « Defend optimistic positions with elegance » — the polished tone;
  • Shrek’s Donkey: « Use absurd, offbeat humor » — the uninhibited tone.

Both instructions embed the chosen linguistic constraint (contrainte_choisie[1]), interpolated into the system prompt: this is what guarantees that every reply, whichever agent speaks, follows the debate’s rule.

Important wiring point: the ImagePlugin plugin is added only to the Donkey’s kernel (kernel_ane.add_plugin(...)). Barbie talks; the Donkey talks and illustrates — the asymmetry is deliberate, and it shows that plugins attach per kernel, not globally.

# Création des kernels séparés
kernel_barbie = create_kernel()
kernel_ane = create_kernel()

image_Plugin = ImagePlugin(client_comfyui, WORKFLOW_IMAGE)
# Ajout du plugin uniquement à l'Âne
kernel_ane.add_plugin(image_Plugin, plugin_name="image_gen")


barbie = ChatCompletionAgent(
    kernel=kernel_barbie,
    name="Barbie",
    instructions=f"""
    Tu es Barbie. Défends des positions optimistes avec élégance.
    Contrainte obligatoire : {contrainte_choisie[1]}
    """
)

ane = ChatCompletionAgent(
    kernel=kernel_ane,
    name="Ane_Shrek",
    instructions=f"""
    Tu es l'Âne de Shrek. Utilise l'humour absurde et décalé.
    Contrainte obligatoire : {contrainte_choisie[1]}
    """
)

print("Kernels et agents Barbie/Âne créés")
Kernels et agents Barbie/Âne créés

Guided example 2 — Creating a third agent

Student contribution from the group of PR #21089, integrated as a guided example.

The debate pits Barbie against the Donkey. The example adds a third character: a Referee who comments on the two duelists’ performance.

What the code below does:

  • # Étape 1 — create a kernel dedicated to the Referee with create_kernel();
  • # Étape 2 — define its system instructions (judge constraint compliance, creativity, humor, end with a score out of 10);
  • the arbitre agent is then instantiated like the other two.

The instruction from the original statement is preserved: draw inspiration from Barbie’s and the Donkey’s instructions for the prompt format.

# Exemple guidé 2 — Création d'un troisième agent (Arbitre).
# Contribution étudiante du groupe de la PR #21089, intégrée comme exemple guidé.

# Etape 1 : un kernel dedie, comme pour Barbie et l'Ane
kernel_arbitre = create_kernel()

# Etape 2 : les instructions systeme de l'arbitre
ARBITRE_INSTRUCTIONS = """
Tu es l'Arbitre du duel verbal entre Barbie et l'Âne de Shrek.
À chaque tour, commente en 2 phrases maximum la dernière réplique :
  1. le respect de la contrainte linguistique (rime, style imposé...) ;
  2. la créativité et l'humour.
Termine par une note sur 10. Reste neutre et impartial.
Contrainte obligatoire pour tes propres commentaires : %s
""" % contrainte_choisie[1]

# Creation de l'agent
arbitre = ChatCompletionAgent(
    kernel=kernel_arbitre,
    name="Arbitre",
    instructions=ARBITRE_INSTRUCTIONS,
)

print(f"Agent créé : {arbitre.name}")
# Pour l'utiliser dans le duel : AgentGroupChat(agents=[barbie, ane, arbitre], ...)
Agent créé : Arbitre

Reading the result — guided example 2

The Arbitre agent is created with its own kernel and instructions, and the print call correctly displays Agent créé : Arbitre. The construction requested by the prompt is therefore complete.

Limitation of the example, and it is a major one: the Arbiter does not take part in any duel. The comment on the last line says so — # Pour l'utiliser dans le duel : AgentGroupChat(agents=[barbie, ane, arbitre], ...) — but the duel cell below still constructs AgentGroupChat(agents=[barbie, ane]). In other words, the Arbiter exists, but is never summoned: the notebook never shows its comments or scores. An agent that is created but absent from the loop produces nothing — this is exactly what replacement exercise 2 asks you to correct.

Termination strategy

Without a stopping rule, an AgentGroupChat would run forever. DebateTerminationStrategy subclasses TerminationStrategy: the debate stops as soon as the history reaches MAX_TURNS = 5 messages.

Three implementation details to note:

  • ClassVar[int]: MAX_TURNS is a class constant, not an instance field — the ClassVar annotation avoids the conflict with Semantic Kernel’s annotation machinery;
  • the hook: in Semantic Kernel, the method the orchestrator calls is should_terminate, which checks the strategy’s scope then delegates to should_agent_terminate — it is this second method that the documentation designates as the one to implement in a subclass. Overriding should_terminate works (the orchestrator does call it), but bypasses the built-in scope check;
  • the async contract: should_agent_terminate is async, which allows dynamic termination — inspecting the last message’s content, an external service, etc. This is the lead of guided example 3.

The strategy is passed to the AgentGroupChat when it is constructed, and is consulted after each message added to the history.

from typing import ClassVar
from semantic_kernel.agents.strategies.termination.termination_strategy import TerminationStrategy

class DebateTerminationStrategy(TerminationStrategy):
    MAX_TURNS: ClassVar[int] = 5  # Annotation correcte avec ClassVar

    async def should_agent_terminate(self, agent, history) -> bool:
        return len(history) >= self.MAX_TURNS

print("Stratégie de terminaison du débat configurée")
Stratégie de terminaison du débat configurée

Launching the debate

The AgentGroupChat gathers the two agents (barbie, ane) and the termination strategy defined above. The add_chat_message call primes the conversation — Semantic Kernel requires a non-empty history — then group_chat.invoke() runs the duel:

  • each agent produces its reply in turn, in accordance with the sequential selection strategy;
  • pedagogical specificity: on each of the Donkey’s replies, the code first has the reply paraphrased into a visual description by decrire_scene_visuelle, constrained to the donkey alone on four legs (a freely described scene drifts towards the rearing posture or the duel’s opponent) — the generator renders as lettering any text quoted in the prompt, so the reply is never passed to it as-is — then invokes the image_gen plugin (generate_image) with that description as context and displays the image returned by the ComfyUI instance (width=320);
  • the replies are also kept in repliques_du_duel: the exercises in section 9 reuse them instead of restarting a duel.

This is where the speak then illustrate loop materializes: an agent’s reply is first summarized into a visual scene, which becomes the argument of the image call, linking the conversation service and the ComfyUI instance within the same debate. Generating an illustration takes several minutes — model loading followed by ComfyUI’s diffusion steps dominate the rest by far; it is by far the slowest part of the setup.

repliques_du_duel = []

async def run_debate():
    logger.info(f"Contrainte active : {contrainte_choisie[0]}")

    group_chat = AgentGroupChat(
        agents=[barbie, ane],
        termination_strategy=DebateTerminationStrategy()
    )

    # Add initial topic message (SK requires non-empty chat history)
    await group_chat.add_chat_message(
        ChatMessageContent(role=AuthorRole.USER, content="Commencez le duel verbal !")
    )

    async for msg in group_chat.invoke():
        repliques_du_duel.append(msg)
        print(f"\n{msg.name}: {msg.content}")

        if msg.name == "Ane_Shrek":
            try:
                # Separation replique/image : le generateur rend en lettrage
                # tout texte cite dans le prompt (mesure du 2026-10-22) ; la
                # scene est decrite visuellement, sans recopier la replique.
                scene = await decrire_scene_visuelle(ane.kernel, msg.content)
                print(f"Scène visuelle envoyée au générateur : {scene}")
                image_result = await ane.kernel.invoke(
                    function_name="generate_image",
                    plugin_name="image_gen",
                    arguments=KernelArguments(context=scene)
                )
                chemin = str(image_result) if image_result else ""
                if chemin and os.path.exists(chemin):
                    display(IPImage(filename=chemin, width=320))
                else:
                    logger.warning("Illustration indisponible pour cette replique")
            except Exception as e:
                logger.warning(f"Image generation skipped: {e}")

await run_debate()

Barbie: Je lance le duel, sur l’air de **“I’m a Believer”** :

J’étais venue pour parler, sans chercher la bagarre,  
Puis tu dis “duel verbal”, et mon regard s’éclaire.  
Tu veux des mots qui piquent ? Moi je sers du brillant,  
Parce qu’un trait d’esprit peut rester élégant.

Alors vas-y, envoie : ta meilleure petite phrase,  
Moi je riposte chic, je transforme tout en extase.  
Et même si tu attaques, moi je garde la saveur :  
Car l’optimisme gagne — and I’m a believer.

À toi : quel est ton premier coup (thème au choix : amour, ambition, style, ou confiance) ?

Ane_Shrek: Je débarque, **sur l’air de “I’m a Believer”**, c’est parti le duel verbal !

Je traînais dans mon marais, peinard, sans grand malheur,  
Puis t’as crié “DUEL VERBAL !” et j’ai senti la fureur.  
J’me suis dit “tiens, c’est marrant, j’vais faire le professeur”,  
Parce que moi, j’suis un âne… mais un âne avec auteur.

Tu veux du clash bien croustillant, version poésie qui déraille ?  
J’te réponds avec des rimes qui font des roues de brouette en bataille.  
Et si tu crois m’impressionner avec ton petit ton supérieur :  
J’ai déjà gagné un débat contre une porte. Elle avait tort, d’ailleurs.

Alors vas-y, envoie ton premier tir, ton plus grand coup de voix :  
Et moi j’te renvoie la réplique… **et j’suis un believer, tu vois.**
Scène visuelle envoyée au générateur : Un âne seul, à quatre pattes, les quatre sabots ancrés dans une flaque de marais sur une scène éclairée, tourne la tête vers les coulisses devant un rideau entrouvert comme prêt à répliquer.


Barbie: Je monte sur scène, **sur l’air de “I’m a Believer”**, et j’ouvre le duel, version Barbie — optimiste et élégante :

Je marchais sans heurt, tranquille, pleine de douceur,  
Puis t’as crié “DUEL VERBAL !” et j’ai vu la lueur.  
Tu veux des mots qui claquent ? Moi j’les rends couture,  
Parce que même un bon pic peut garder de l’allure.

Vas-y, lance ta phrase, ton meilleur petit ton,  
Moi je réponds plus haut — mais avec distinction.  
Et quoi que tu me serves, je garde la couleur :  
Car je transforme l’ombre… **and I’m a believer.**

À toi : attaque sur quel thème — **ego, style, courage, ou ambition** ?

Ane_Shrek: Je trotte dans l’coin du marais, tranquille, sans trop d’aigreur,  
Puis tu cries “DUEL VERBAL !” et là… j’sens la chaleur.  
J’ai secoué mes grandes oreilles, j’ai chauffé mon moteur :  
“OK, je rappe en rimes bizarres… **and I’m a believer**.”

Tu veux du punchline maison, du sarcasme qui fait peur ?  
Moi j’te sers du grand art : du **n’importe quoi** de qualité supérieure.  
J’suis l’Âne de Shrek, champion toutes catégories du bavardage,  
Je peux te faire une vanne… et une autre… et une autre… (c’est mon héritage).

Alors envoie ton premier coup, ton meilleur petit venin,  
Moi je te renvoie la réplique, version marais, version câlin.  
Et si tu trébuches sur tes mots, je crie très fort en chœur :  
“Ça arrive même aux humains… **and I’m a believer** !”
Scène visuelle envoyée au générateur : Un âne seul, à quatre pattes dans un coin de marais, trottine calmement sous une lumière chaude en secouant vivement ses longues oreilles devant un rideau sombre au fond.

Reading the result: the real verbal duel

The execution shows the complete protocol in action, turn by turn:

  • Sequential agent selection: the logs Selected agent at index 0/1 alternate Barbie then the Donkey, in accordance with AgentGroupChat and its default selection strategy;
  • Constraint respected: the randomly drawn constraint is carried by both agents’ system instructions, and their replies follow it;
  • The image plugin is wired to the Donkey only: only Ane_Shrek triggers image_gen-generate_image, in accordance with the kernel_ane.add_plugin(...) wiring;
  • Termination works: as soon as the history reaches MAX_TURNS, DebateTerminationStrategy cuts the loop.

The output is the end-to-end proof of the setup: two constrained agents, an image plugin wired to the series’ ComfyUI instance, a termination strategy — all orchestrated by Semantic Kernel.

Guided example 3 — Custom termination strategy

Student contribution from the group of PR #21089, integrated as a guided example.

The base implementation stops the debate after a fixed number of turns (MAX_TURNS = 5). The example aims at stopping on content: cutting the debate as soon as a character capitulates.

What the code below does:

  • # Étape 1 — define the list of trigger keywords (TRIGGER_WORDS) — radicals, to cover “capitule”, “capituler”, “capitulation”;
  • # Étape 2 — read the last message (history[-1]), lowercase it, and trigger the stop if one of the keywords appears in it;
  • a failsafe MAX_TURNS = 10 stops the debate even if nobody gives in.

The hint from the original statement is preserved: use str(history[-1].content).lower() to read the last message.

# Exemple guidé 3 — Stratégie de terminaison personnalisée (capitulation).
# Contribution étudiante du groupe de la PR #21089, intégrée comme exemple guidé.
from typing import ClassVar
from semantic_kernel.agents.strategies.termination.termination_strategy import TerminationStrategy

class SurrenderTerminationStrategy(TerminationStrategy):
    # Etape 1 : mots-cles declencheurs (radicaux, pour couvrir capitule / capituler / capitulation...)
    TRIGGER_WORDS: ClassVar[list[str]] = ["capitul", "abandon", "je me rends", "j'abandonne"]
    MAX_TURNS: ClassVar[int] = 10  # garde-fou : le debat s'arrete meme si personne ne cede

    async def should_terminate(self, agent, history, cancellation_token=None) -> bool:
        if not history:
            return False
        # Etape 2 : verifier si le dernier message contient un mot-cle
        dernier = str(history[-1].content).lower()
        result = any(mot in dernier for mot in self.TRIGGER_WORDS) or len(history) >= self.MAX_TURNS
        return result

print("SurrenderTerminationStrategy définie")
# Utilisation : AgentGroupChat(agents=[barbie, ane], termination_strategy=SurrenderTerminationStrategy())
SurrenderTerminationStrategy définie
# Exemple guidé 3 — la stratégie en action : un duel court, sans illustration.
# Le duel ci-dessous n'appelle pas le plugin d'image : on ne mesure ici que la terminaison.

async def duel_capitulation():
    chat = AgentGroupChat(
        agents=[barbie, ane],
        termination_strategy=SurrenderTerminationStrategy()
    )
    await chat.add_chat_message(
        ChatMessageContent(role=AuthorRole.USER, content="Commencez le duel verbal !")
    )
    repliques = []
    async for msg in chat.invoke():
        repliques.append(msg)
        print(f"\n{msg.name}: {msg.content}")
    return repliques


repliques_capitulation = await duel_capitulation()
dernier = str(repliques_capitulation[-1].content).lower() if repliques_capitulation else ""
print(f"\n{len(repliques_capitulation)} répliques ; un mot déclencheur apparaît dans la dernière : "
      f"{any(mot in dernier for mot in SurrenderTerminationStrategy.TRIGGER_WORDS)}")

Barbie: Je lance le duel verbal, et j’garde le style glamour,  
Tu sors tes mots en acier, moi j’arrive en mots d’or.  
J’croyais aux piques faciles, aux “jamais” sans couleur,  
Puis j’ai vu ton regard… et j’ai choisi la hauteur.

Now I’m a believer, je riposte sans rancœur,  
Not a trace of méchanceté, que du panache au cœur.  
Je t’écoute, je te respecte, et je brille en vérité,  
Yeah, yeah, yeah… j’suis Barbie, née pour te challenger.

Allez, à toi: lance ta meilleure punchline—  
Et moi je te réponds, chic, piquante… mais toujours fine.

Ane_Shrek: Je démarre le duel verbal, hi-han, tiens bon la ceinture,  
J’suis l’Âne de Shrek, j’te clash avec de la confiture.  
J’croyais qu’un bon mot, c’était juste mordre et partir,  
Puis j’ai vu ta répartie… et j’me suis mis à hennir.

Now I’m a believer, j’te pique sans être méchant,  
Not a trace of mauvaise foi, j’suis absurde et élégant.  
I’m in love with les punchlines, j’les mâche comme du foin,  
Yeah, yeah, yeah… j’te démonte, mais avec soin.

Allez, à toi : envoie ta meilleure attaque, mon champion,  
Sinon j’te fais une rime avec “oignon” et “tartifion”.

Barbie: Je lance le duel verbal, version chic et plein d’allure,  
Tes mots veulent faire du bruit, les miens font la couture.  
J’croyais qu’un clash, c’était froid, sec, sans dignité,  
Puis j’ai senti l’étincelle… et j’ai choisi d’briller.

Now I’m a believer, je riposte en douceur,  
Not a trace de noirceur, juste du mordant, du cœur.  
Je transforme tes piques en confettis bien dorés,  
Yeah, yeah, yeah… et j’avance, tête haute, inspirée.

À toi: balance ta meilleure attaque—  
Et moi je réponds classy, optimiste… et sans faux claques.

Ane_Shrek: Je commence le duel verbal, hi-han, j’arrive en trombe,  
J’ai des rimes dans les sabots et du style qui fait “boum-boum”.  
J’croyais qu’les duels, c’était “bling” et gros muscles en carton,  
Puis j’ai vu ton air sérieux… j’ai sorti l’artichaut-canon.

Now I’m a believer, j’te provoque en chantant,  
Not a trace of méchanceté, juste un chaos élégant.  
I’m in love with le clash, mais version caramel,  
Yeah, yeah, yeah… j’te parle et paf, ça devient surréel.

Premier coup : si ton ego était un oignon,  
Shrek pleurerait de rire… et moi j’le mangerais en chansons.

Barbie: Je commence le duel verbal, talons hauts sur le parquet,  
Tu fais le boucan d’un tambour, moi j’fais lever le rideau doré.  
J’croyais que l’ego, c’était lourd, que ça pesait sur la raison,  
Puis j’ai vu ton “oignon” briller… j’en ai fait une couronne, mon champion.

Now I’m a believer, je te réponds en hauteur,  
Not a trace de drama, juste du style et de la chaleur.  
I’m in love with la répartie, quand elle sait rester classe,  
Yeah, yeah, yeah… ton oignon? J’en fais un bouquet qui passe.

Deuxième coup, écoute bien, et garde le sourire:  
Plus tu couches des “couches”, plus je vois un cœur à découvrir.  
À toi—relance fort, mais fais-le avec panache,  
Sinon je gagne… en rose, en rime… et sans la moindre tache.

Ane_Shrek: Je commence le duel verbal, hi-han, j’entre dans l’arène,  
Avec un casque en salade et une lance en… banane.  
J’croyais qu’pour être méchant, fallait parler en dragon,  
Puis j’ai vu ta confiance… j’ai sorti mon accordéon.

Now I’m a believer, j’te clash en trottinant,  
Not a trace of cruauté, juste du bizarre élégant.  
I’m in love with les punchlines, j’les sers en gratin,  
Yeah, yeah, yeah… et j’te vise pile entre les refrains.

Premier coup (et ça pique comme un moustique en armure) :  
T’as tellement le sens du duel… que même ton miroir prend des mesures.  
À toi ! Balance ta réplique, fais-moi trembler la crinière,  
Sinon j’te gagne par KO… à coups de rimes et de poussière.

Barbie: Je poursuis le duel verbal, toujours chic, toujours légère,  
Ton casque en salade me va: j’en fais une couronne de lumière.  
J’croyais que les miroirs jugeaient, qu’ils faisaient la loi du “parfait”,  
Puis j’ai compris: ils reflètent… et moi j’choisis ce que je fais.

Now I’m a believer, je réponds sans te blesser,  
Not a trace de jalousie, juste l’art de te dépasser.  
I’m in love with la confiance, celle qui relève les défis,  
Yeah, yeah, yeah… mon miroir? Il applaudit ma vie.

Dernier coup, écoute bien, et garde ton accordéon:  
Si tu vises entre les refrains, moi j’écris la chanson.  
À toi—une dernière rime, une étincelle, une attaque:  
Sinon je gagne en élégance… et je signe en rose, clac.

Ane_Shrek: Je commence le duel verbal, hi-han, j’sors de ma cabane,  
Avec un bouclier en gaufre et une épée en banane.  
J’croyais qu’un grand duel, c’était sombrer dans la noirceur,  
Puis j’ai vu ton air sérieux… j’ai éternué des fleurs.

Now I’m a believer, j’te vise en rigolant,  
Not a trace of méchanceté, juste du chaos charmant.  
I’m in love with les punchlines, j’les mâche comme du foin,  
Yeah, yeah, yeah… et j’les recrache en couplets bien pointus, bien loin.

Premier coup : t’as l’air si prêt pour la guerre des mots,  
Que même ton dictionnaire s’échauffe et demande un congé… au zoo.  
À toi de jouer : balance ta meilleure attaque, fais-moi “hi-han” de peur,  
Sinon je gagne par K.O… à coups de rimes et de beurre.

Barbie: Je prends le duel verbal, en rose et sans détour,  
Ton bouclier en gaufre ? J’en fais un dessert de concours.  
J’croyais qu’un “K.O.” d’esprit faisait tomber les meilleurs,  
Puis j’ai vu ton chaos charmant… et j’y ai mis des couleurs.

Now I’m a believer, je riposte avec grâce,  
Not a trace de rancœur, juste une étincelle qui passe.  
I’m in love with les défis, quand ils donnent du ressort,  
Yeah, yeah, yeah… mon optimisme est plus fort.

Coup de scène : ton dictionnaire veut des vacances au zoo ?  
Le mien ouvre une boutique—“Mots qui brillent”, tout là-haut.  
À toi : frappe une dernière fois, mais fais-le avec élégance,  
Sinon je gagne… en sourire, en style, en espérance.

9 répliques ; un mot déclencheur apparaît dans la dernière : False

Reading the result — guided example 3

What works. The strategy correctly reads the last message, and keyword-based stopping works: when the duel ends without capitulation, it is the safeguard MAX_TURNS = 10 that cuts it off, and the reply count shows this. The strategy is therefore executed, unlike its first version, which remained unexecuted in the group’s working copy.

Two limitations to name.

  1. Detection is a substring search (mot in dernier). It distinguishes neither the speaker nor negation: “I will never give up” or “you’re going to give up, Donkey” both contain a trigger, and cut off the debate even though no one yields. The strategy therefore detects an occurrence, not a capitulation.
  2. The overloaded method is not the canonical hook point. The class redefines should_terminate, which the orchestrator calls — this works — but Semantic Kernel delegates from should_terminate to should_agent_terminate, the method intended for subclasses. Overloading should_terminate short-circuits the built-in scope check (agents). The cell in the “Termination strategy” section illustrates the canonical form.

Replacement exercise 3 asks you to address these two points.

9. Exercises

Three replacement exercises, on the same notebook. Each extends one of the three guided examples — same foundation, different question. The cells below are skeletons: they run as-is and display what remains to be done.

Exercise Extends Question
1 Guided example 1 (constraints) make a constraint verifiable by code and measure its compliance rate
2 Guided example 2 (Referee) bring the Referee into the duel and make use of its notes
3 Guided example 3 (termination) detect a capitulation without targeting the wrong thing

Exercise 1 — A constraint that the code can verify

Guided example 1 adds declarative constraints: their description is a sentence in French, and nothing checks that the model followed it. The goal is to make a constraint measurable.

Objective:

  1. define a mechanically verifiable rule — for example “the reply contains at least one word from the list MOTS_ANES”;
  2. write taux_de_respect(repliques, regle) which receives the replies from a duel and returns the proportion of replies that respect the rule;
  3. apply it to the duel already present in the notebook (variable repliques_du_duel).

Hints:

  • # Étape 1: a verifiable constraint = a name, a description and a function regle(texte) -> bool;
  • # Étape 2: result = None # TODO étudiant, then the calculation reply by reply;
  • # Indice: sum(1 for r in repliques if regle(str(r))) / len(repliques).
# Exercice 1 — Une contrainte que le code peut vérifier.
# L'expérience est autonome : elle ne modifie ni CONTRAINTES, ni les agents, ni le duel.


def taux_de_respect(repliques, regle):
    # TODO étudiant : retourner la proportion de repliques qui respectent `regle`.
    # Étape 1 : compter les repliques ou `regle(str(replique))` est vrai.
    # Étape 2 : diviser par le nombre de repliques (attention au cas vide).
    # Indice : sum(1 for r in repliques if regle(str(r))) / len(repliques)
    result = None  # TODO étudiant
    return result


taux = taux_de_respect(repliques_du_duel, lambda texte: "ane" in texte.lower() or "âne" in texte.lower())
if taux is None:
    print("Exercice 1 à compléter : le taux de respect d'une contrainte vérifiable par le code "
          f"({len(repliques_du_duel)} répliques disponibles dans repliques_du_duel).")
else:
    print(f"Taux de respect : {taux:.0%} sur {len(repliques_du_duel)} répliques")
Exercice 1 à compléter : le taux de respect d'une contrainte vérifiable par le code (4 répliques disponibles dans repliques_du_duel).

Exercise 2 — Put the Referee into the duel

Guided example 2 creates the Arbitre agent, but the duel still runs with two participants: AgentGroupChat(agents=[barbie, ane]) never summons it. The objective is to bring it into the loop and make use of what it produces.

Objective:

  1. restart a duel with agents=[barbie, ane, arbitre] — remember to increase MAX_TURNS, otherwise the Referee will speak at most once;
  2. collect the replies from this new duel;
  3. write notes_arbitre(repliques) that returns the list of scores out of 10 assigned by the Referee, extracted from the text (for example with re.compile(r"(\d+(?:[.,]\d+)?)\s*/\s*10"));
  4. display the number of scores and their average.

Hints:

  • # Étape 1: chat = AgentGroupChat(agents=[barbie, ane, arbitre], termination_strategy=DebateTerminationStrategy());
  • # Étape 2: iterate over the replies where msg.name == "Arbitre";
  • # Indice: float(m.group(1).replace(",", ".")) to convert the score found.
# Exercice 2 — Mettre l'Arbitre dans le duel et lire ses notes.
# `arbitre` a été créé dans l'exemple guidé 2 ; `repliques_du_duel` vient du duel de la section « Lancement du débat ».
import re


async def duel_avec_arbitre(max_tours=12):
    # TODO étudiant : relancer un duel a trois agents et retourner ses repliques.
    # Étape 1 : construire AgentGroupChat(agents=[barbie, ane, arbitre], ...) avec une
    #           strategie de terminaison dont MAX_TURNS vaut `max_tours`.
    # Étape 2 : amorcer l'historique puis collecter les messages dans une liste.
    result = None  # TODO étudiant
    return result


def notes_arbitre(repliques):
    # TODO étudiant : extraire les notes sur 10 des repliques de l'Arbitre.
    # Indice : re.compile(r"(\d+(?:[.,]\d+)?)\s*/\s*10") sur str(replique.content).
    result = None  # TODO étudiant
    return result


repliques_arbitre = await duel_avec_arbitre()
if repliques_arbitre is None:
    print("Exercice 2 à compléter : convier l'Arbitre au duel, puis extraire ses notes sur 10.")
else:
    notes = notes_arbitre(repliques_arbitre)
    if not notes:
        print("Exercice 2 à compléter : aucune note extraite des repliques de l'Arbitre.")
    else:
        print(f"{len(notes)} notes d'arbitre, moyenne {sum(notes) / len(notes):.2f}/10")
Exercice 2 à compléter : convier l'Arbitre au duel, puis extraire ses notes sur 10.

Exercise 3 — A surrender detection that does not target the wrong person

Guided example 3 detects surrender by substring in the last message. Two ways to get it wrong, both measurable: “I will never surrender” (negation) and “you are going to surrender, Donkey” (talking about the other person) trigger the stop even though no one is giving in.

Objective:

  1. write capitule(phrase) that returns True only for a surrender by the speaker — in the first person and not negated;
  2. test it on a list of trap sentences, without calling the model: this is a unit test, it must be deterministic;
  3. (bonus) reimplement SurrenderTerminationStrategy on the canonical hook point should_agent_terminate and verify that the duel behaves the same way.

Hints:

  • # Étape 1: re.compile(r"\b(j'abandonne|je me rends|je capitule)\b") — and handle negation (n', ne ... jamais, pas);
  • # Étape 2: test at least “I will never surrender!”, “You are going to surrender, Donkey!”, “I surrender, you win.”;
  • # Indice: return a dict phrase -> expected/observed boolean, and count the discrepancies.
# Exercice 3 — Une detection de capitulation qui ne se trompe pas de cible.
# Test unitaire : aucune replique n'est generee ici, tout est deterministe.
import re

PHRASES_PIEGES = [
    ("Je n'abandonnerai jamais !", False),
    ("Tu vas abandonner, l'Âne !", False),
    ("J'abandonne, tu gagnes.", True),
]


def capitule(phrase):
    # TODO étudiant : True seulement si le LOCUTEUR annonce sa propre capitulation.
    # Étape 1 : reperer les formes a la premiere personne (j'abandonne, je me rends, je capitule).
    # Étape 2 : exclure les formes niees (n'... pas / jamais) et les formes ou l'autre est vise.
    result = None  # TODO étudiant
    return result


verdicts = {phrase: capitule(phrase) for phrase, attendu in PHRASES_PIEGES} if capitule("test") is not None else None
if verdicts is None:
    print("Exercice 3 à compléter : une détection de capitulation par locuteur, testée sur "
          f"{len(PHRASES_PIEGES)} phrases pièges.")
else:
    ecarts = [p for p, attendu in PHRASES_PIEGES if verdicts.get(p) != attendu]
    print(f"{len(PHRASES_PIEGES) - len(ecarts)}/{len(PHRASES_PIEGES)} phrases classées correctement")
    for phrase in ecarts:
        print(f"  écart : {phrase!r} -> {verdicts.get(phrase)}")
Exercice 3 à compléter : une détection de capitulation par locuteur, testée sur 3 phrases pièges.

Conclusion

This notebook demonstrated a constrained multi-agent debate with Semantic Kernel: two ChatCompletionAgent (Barbie and Shrek’s Donkey) face off while respecting a randomly drawn linguistic constraint, and the Donkey illustrates its replies with images generated on the series’ ComfyUI instance.

Key points:

  • the sequential selection protocol alternates the agents via SequentialSelectionStrategy, with the Selected agent at index N logs tracing each turn;
  • the linguistic constraint is carried by the system instruction: it is what constrains the generation, agent by agent;
  • image generation goes through an external service (ComfyUI), called over HTTP with the series’ versioned workflow — the conversation service and the image service are two distinct dependencies;
  • the termination strategy works: the debate stops according to the implemented rule.

The exercises of the « 9. Exercices » section extend guided examples 1, 2 and 3 — a constraint checkable by code, a Referee actually summoned into the duel, and a capitulation detection that does not mistake its target. The architecture (kernel + plugin + termination strategy) is reusable as-is for other contest formats (political debate, poetry contest, theatrical improvisation).

Retour au sommet