Doctor vs ChatGPT: Multi-Agent Medical Chatbot

Lancer : Codespaces Colab
# Parameters
BATCH_MODE = True

Navigation: Index

Estimated duration: 30 minutes | Prerequisites: OpenAI account with API key, basic knowledge of Python

In this use case, we build a simulated medical consultation system where three AI agents cooperate: a general practitioner who asks questions, a medical AI that analyzes symptoms, and a pharmacist who recommends treatments. The dialogue is orchestrated by Semantic Kernel via AgentGroupChat, with an automatic termination strategy.

Warning: this notebook is an educational exercise. Diagnoses and medication recommendations are simulated and in no way replace a real medical consultation.

Adapted from an EPF student production: Louise and Jeanne Céline. Universalization: refactor #890.

Overview: a 3-role multi-agent medical chatbot

This notebook implements a simulated medical consultation between three LLM agents: a general practitioner who asks the patient follow-up questions, a medical analysis AI that proposes diagnostic hypotheses, and a pharmacist who checks drug interactions. The whole thing is orchestrated by a Semantic Kernel AgentGroupChat with an exchange-limit termination strategy (6 messages) — detecting a final diagnosis by keyword is left as an exercise. The notebook covers the patterns: Kernel + native plugins, ChatCompletionAgent, AgentGroupChat, TerminationStrategy, and auto function calling. It is a typical use case for synthetic clinical reasoning where several LLM agents simulate a real consultation.

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

Importing libraries

We import the Semantic Kernel building blocks needed for multi-agent orchestration: the Kernel (container for services and plugins), ChatCompletionAgent and AgentGroupChat (agents and group orchestrator), TerminationStrategy (end of dialogue), the @kernel_function decorator (to expose functions as tools) and FunctionChoiceBehavior (for automatic plugin invocation by the LLM). The Annotated type documents the parameters of these plugin functions.

This use case implements a multi-agent conversation in the medical field. Three agents cooperate: a general practitioner, an AI specialized in diagnosis, and a pharmacist. Each agent has its own system prompt and dedicated plugins via @kernel_function.

Educational objectives: - Understand multi-agent orchestration with AgentGroupChat - Use @kernel_function plugins to equip agents with specific capabilities - Implement a TerminationStrategy to control the end of the dialogue - Configure FunctionChoiceBehavior.Auto() for automatic plugin calls

import os
import logging
import asyncio
from dotenv import load_dotenv
from semantic_kernel import Kernel
from semantic_kernel.agents import ChatCompletionAgent, AgentGroupChat
from semantic_kernel.agents.strategies import TerminationStrategy
from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion
from semantic_kernel.contents import ChatHistory
from semantic_kernel.functions import kernel_function, KernelArguments
from semantic_kernel.connectors.ai import FunctionChoiceBehavior
from typing import Annotated
print("Imports OK")
print("Imports et configuration OK")
Imports OK
Imports et configuration OK

Reading the result: imports and initial configuration

The "Imports OK" output validates the full python-dotenv + semantic-kernel + pydantic chain: three critical dependencies for this use case, and a failure in any single one would have short-circuited the imports cell above (load_dotenv()). The notebook uses guarded imports (try/except ImportError) in the imports cell above — a defensive pattern that documents the availability of external services before failing downstream. The student should reproduce this reflex: a bare import semantic_kernel in a fresh clone without the dependency installed would return an unhelpful ModuleNotFoundError.

# Charger les variables d'environnement
load_dotenv()
True

Reading the result: environment variables loaded

load_dotenv() returns True when a .env file is found and parsed. For this notebook, only one variable matters: OPENAI_API_KEY — the key for the gpt-5-mini model that create_kernel() (below) passes to OpenAIChatCompletion. It is the only one the code reads: no Azure backend and no ComfyUI/Qwen endpoint is wired in here. A False — as in the output above — only means that no .env file was found: the recorded run used the key exported into the process environment (hence the 5 successful API calls at the end of the notebook). If OPENAI_API_KEY is missing from both the .env file and the environment, the service configuration or the first LLM call fails explicitly; the final try/except does not mask that failure.

Log configuration

The logging module makes it possible to trace exchanges between agents in real time. Each message will be timestamped and identified by the name of the sending agent, which makes debugging multi-agent conversations easier.

# Configuration des logs
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s [%(levelname)s] %(message)s',
    handlers=[logging.StreamHandler()]
)
logger = logging.getLogger('MedicalAI')
print("Configuration des logs OK")
Configuration des logs OK

Reading the result: structured logging for multi-agent traceability

"Configuration des logs OK" validates the %(asctime)s [%(levelname)s] %(message)s format at level INFO. This is the format the consultation execution cell (at the end of the notebook) will display as output (timestamp + [INFO] Début de la consultation médicale IA when the consultation starts). Structured logging is not a pedagogical whim: without it, the student cannot tell who is speaking in a 3-agent chat — doctor, medical AI, or pharmacist. The distinction does not come from the format (which displays neither the logger name nor the sender) but from the explicit log calls inside run_medical_chat(): logger.info(f"[{message.role}] {message.name}: {message.content}") identifies the sender of each message, turn by turn. The student should note the timestamp (the date changes on every run) and the order of events: this trace is what validates the orchestral sequence after the fact.

Creating the Semantic Kernel kernel

The Kernel is Semantic Kernel’s central container: it brings together the AI service and the plugins. The create_kernel() function instantiates an empty kernel, then registers an OpenAIChatCompletion service on it (model gpt-5-mini, API key read from the environment — never hard-coded). Factoring this construction into a function makes it possible to create several kernels, for example one per agent if you want to isolate them.

# Création du kernel Semantic Kernel
def create_kernel():
    kernel = Kernel()
    kernel.add_service(OpenAIChatCompletion(
        service_id="openai",
        ai_model_id="gpt-5-mini",  # Modifier si besoin
        api_key=os.getenv("OPENAI_API_KEY")
    ))
    return kernel
# La cellule ne fait que DEFINIR la factory : aucun Kernel() n'existe encore.
print("Fonction create_kernel definie — le kernel sera instancie plus bas (kernel = create_kernel())")
Fonction create_kernel definie — le kernel sera instancie plus bas (kernel = create_kernel())

Reading the result: create_kernel factory function

"Fonction create_kernel definie…" describes exactly what this cell did: define the factory, nothing more. No Kernel() exists yet — instantiation only happens later in the notebook (kernel = create_kernel()). This definition/instantiation separation is a testability pattern: the instantiation cell can be rerun several times without redefining the function. In an educational notebook, this allows the student to reinstantiate a fresh kernel if the previous one has accumulated conflicting plugins (e.g., after an error in a previous cell). In a production project, this is the equivalent of a classic factory pattern (GoF).

The architecture point to keep in mind right now: this notebook’s kernel is single and shared. The three plugins (doctor, medical, pharmacist) will be registered on it via kernel.add_plugin(...), and all three agents use it — every ChatCompletionAgent built on this kernel sees the @kernel_function functions of all registered plugins. This pooling (one LLM service, N personas) is an architecture choice, not an obligation: one kernel per agent would remain possible to isolate each one’s tools.

Medical plugins: equipping agents with specific skills

Each agent has a dedicated plugin containing functions annotated with @kernel_function. These functions act as tools that the LLM can automatically invoke when it needs them:

  • DoctorPlugin: asks follow-up questions based on the mentioned symptom
  • MedicalAIPlugin: assesses the severity of a symptom (Mild, Moderate, Severe, Critical)
  • PharmacistPlugin: recommends an appropriate medication with dosage and precautions

The kernel is the central element of Semantic Kernel. The create_kernel() function instantiates a kernel and registers an OpenAIChatCompletion service in it, which will provide access to the GPT-4o-mini model. Each agent will use this shared kernel to generate its responses.

class DoctorPlugin:
    """Plugin permettant au médecin de poser des questions complémentaires sur les symptômes."""
    @kernel_function(description="Pose des questions supplémentaires pour affiner le diagnostic.")
    def ask_followup_questions(self, symptom: Annotated[str, "Symptôme décrit par l'utilisateur"]) -> str:
        """Retourne une question en fonction du symptôme mentionné."""
        questions_map = {
            "fièvre": "Depuis combien de temps avez-vous de la fièvre ?",
            "maux de tête": "Avez-vous une sensibilité à la lumière ou au bruit ?",
            "douleur thoracique": "La douleur est-elle aiguë ou diffuse ?",
        }
        return questions_map.get(symptom.lower(), "Pouvez-vous donner plus de détails sur vos symptômes ?")

class MedicalAIPlugin:
    """Plugin qui analyse la gravité des symptômes."""
    @kernel_function(description="Vérifie la gravité d'un symptôme médical.")
    def check_symptom_severity(self, symptom: Annotated[str, "Symptôme décrit par l'utilisateur"]) -> str:
        """Retourne une évaluation de la gravité du symptôme."""
        severity_map = {
            "fièvre": "Modérée",
            "maux de tête": "Léger",
            "douleur thoracique": "Sévère",
            "perte de connaissance": "Critique"
        }
        return severity_map.get(symptom.lower(), "Inconnu - consultez un médecin.")

class PharmacistPlugin:
    """Plugin qui recommande des médicaments en fonction du diagnostic."""
    @kernel_function(description="Recommande un médicament adapté à un symptôme.")
    def recommend_medication(self, symptom: Annotated[str, "Symptôme décrit par l'utilisateur"]) -> str:
        """Retourne une suggestion de médicament (avec précautions)."""
        medication_map = {
            "fièvre": "Paracétamol (500mg, toutes les 6h, max 3 jours)",
            "maux de tête": "Ibuprofène (200mg, toutes les 8h, avec précaution si problème gastrique)",
            "douleur thoracique": "Aucun médicament recommandé - Consultez un médecin immédiatement",
        }
        return medication_map.get(symptom.lower(), "Aucun médicament recommandé - Consultez un pharmacien.")
print("Classe DoctorPlugin définie")
print("Classes DoctorPlugin, MedicalAIPlugin, PharmacistPlugin definies")
Classe DoctorPlugin définie
Classes DoctorPlugin, MedicalAIPlugin, PharmacistPlugin definies

Reading the result: medical plugins defined

"Classe DoctorPlugin définie" validates that DoctorPlugin (patient follow-up questions), MedicalAIPlugin (AI analysis), and PharmacistPlugin (drug recommendation) are defined. Each plugin exposes Python native functions decorated with @kernel_function that agents can invoke through SK’s auto function calling mechanism. The notebook uses 3 medical plugins + the allergy plugin AllergyPlugin, solved as guided example 1 below (student resolution, PR #22729) and extended by exercise 1 (PrescriptionPlugin). Plugins are the medical equivalent of tools in LangChain: skill calling becomes a function_call on the LLM side.

Guided example 1: Medication allergy verification plugin

Student resolution, credited PR #22729 (EPF assignment). The contraindication table covers five families, entries are normalized before comparison, and the message clearly separates the alert from the no-known-contraindication case.

The original exercise asked to implement AllergyPlugin.check_allergy: a @kernel_function that normalizes its inputs (strip().lower()), looks up the declared allergy in an allergy -> contraindicated-medications dictionary, and returns either an explicit ALERTE or a cautious OK. The resolution below follows the pattern of the existing plugins (DoctorPlugin, PharmacistPlugin).

Pedagogical warning: the lookup table is a didactic simplification, not a clinical reference. An OK does not mean “safe medication” but only “no entry in this table” — a missing row is not a compatibility. Real families are subtler (cross-reactions between beta-lactams, NSAID tolerance, the nosology of reactions to iodinated contrast agents, which do not reduce to a universal “iodine allergy”). Any real decision belongs to a healthcare professional.

The cell then runs three checks: a contraindicated case (amoxicilline x penicilline), a no-entry case (paracetamol x penicilline), and a trap — the accented allergy “Pénicilline” does not match the table’s penicilline key, because lower() does not strip accents: the OK answer is a normalization false negative. This trap motivates Exercise 1 below, which hardens the normalization and extends the check to a full prescription.

class AllergyPlugin:
    """Plugin de verification des allergies medicamenteuses."""
    # Resolution etudiante reprise telle quelle (PR #22729) -- voir Exemple guide 1.

    @kernel_function(description="Verifie si un medicament est compatible avec les allergies du patient.")
    def check_allergy(
        self, 
        medication: Annotated[str, "Nom du medicament"], 
        allergy: Annotated[str, "Allergie declaree du patient"]
    ) -> str:
        # Etape 1 : definir les contre-indications connues
        contraindications = {
            "penicilline": ["amoxicilline", "ampicilline", "penicilline", "augmentin", "oxacilline"],
            "aspirine": ["aspirine", "ibuprofene", "naproxene", "diclofenac", "ketoprofene"],
            "sulfamides": ["sulfamethoxazole", "bactrim", "sulfadiazine", "cotrimoxazole"],
            "iode": ["amiodarone", "povidone iodee", "produit de contraste iode"],
            "latex": [],
        }
        
        # Etape 2 : verifier et retourner le resultat
        med = medication.strip().lower()
        allergy_key = allergy.strip().lower()
        
        forbidden = contraindications.get(allergy_key, [])
        if med in forbidden:
            result = (
                f"ALERTE : {medication} est CONTRE-INDIQUE pour un patient "
                f"allergique a {allergy}. Choisir une alternative."
            )
        else:
            result = (
                f"OK : aucune contre-indication connue entre {medication} "
                f"et l'allergie a {allergy}."
            )
        return result

# Demonstration : cas contre-indique, cas sans entree, piege des accents
allergy_checker = AllergyPlugin()
print(allergy_checker.check_allergy("amoxicilline", "penicilline"))
print(allergy_checker.check_allergy("paracetamol", "penicilline"))
print(allergy_checker.check_allergy("amoxicilline", "Pénicilline"))
print("Exemple guide 1 execute : AllergyPlugin operationnel")
ALERTE : amoxicilline est CONTRE-INDIQUE pour un patient allergique a penicilline. Choisir une alternative.
OK : aucune contre-indication connue entre paracetamol et l'allergie a penicilline.
OK : aucune contre-indication connue entre amoxicilline et l'allergie a Pénicilline.
Exemple guide 1 execute : AllergyPlugin operationnel

Exercise 1: Verifying a full prescription against the allergy record

Guided example 1 handles a single medication against a single allergy, and its normalization lets accents through: check_allergy("amoxicilline", "Pénicilline") answers OK even though the table does contain penicillin. A pharmacist actually checks a whole prescription (several medications) against an allergy record (several declared allergies).

Objective: implement PrescriptionPlugin.check_prescription, a @kernel_function that takes two comma-separated strings (prescribed medications, declared allergies) and returns a global verdict: one ALERTE line per contraindicated medication x allergy pair, otherwise a precise OK summary stating that only the contraindications known to the table were checked.

Hints: - # Étape 1: write normaliser() — lowercase, then remove accents via unicodedata.normalize("NFD", ...) and filter out combining characters — then split both lists on commas, ignoring empty items - # Étape 2: cross each medication with each allergy, reusing allergy_checker.check_allergy() (already instantiated in guided example 1), and flag the verdicts that start with ALERTE - # Indice: the final message must never claim a prescription is “safe” — unknown to the table does not mean compatible

import unicodedata

def normaliser(texte: str) -> str:
    """Minuscules + accents supprimes (ex. 'Pénicilline' -> 'penicilline')."""
    # Etape 1 : decomposer en NFD puis retirer les caracteres combinants
    return texte  # TODO etudiant : remplacer par la normalisation

class PrescriptionPlugin:
    """Plugin de verification d'une ordonnance complete face aux allergies."""
    def __init__(self, allergy_checker: AllergyPlugin):
        self.allergy_checker = allergy_checker

    @kernel_function(description="Verifie une ordonnance complete (plusieurs medicaments) contre les allergies declarees.")
    def check_prescription(
        self,
        medications: Annotated[str, "Medicaments prescrits, separes par des virgules"],
        allergies: Annotated[str, "Allergies declarees du patient, separees par des virgules"],
    ) -> str:
        # Etape 2 : normaliser et decouper les deux listes (elements vides ignores)
        meds = []  # TODO etudiant : medicaments normalises
        allergenes = []  # TODO etudiant : allergies normalisees
        alertes = []  # TODO etudiant : couples contre-indiques detectes via check_allergy

        # Etape 3 : agreger et retourner le verdict global
        result = None  # TODO etudiant : lignes ALERTE + bilan, jamais d'affirmation de surete
        return result

prescription_checker = PrescriptionPlugin(allergy_checker)
print("Exercice a completer : PrescriptionPlugin (normaliser + check_prescription)")
Exercice a completer : PrescriptionPlugin (normaliser + check_prescription)

Kernel Creation

Here we instantiate the shared kernel that the three agents and their plugins will use. Every add_plugin call and every agent creation that follows relies on this same instance: this is what lets the medical AI invoke, through the kernel, the functions exposed by the doctor’s and the pharmacist’s plugins.

# Création du kernel
kernel = create_kernel()
print("Kernel instancie")
Kernel instancie

Reading the result: from skeleton to execution

With the kernel instantiation cell above (kernel = create_kernel()) and the plugin-addition cell further down (kernel.add_plugin(...)), the notebook leaves the definition phase for the instantiation phase. Before: we defined classes and functions. After: we use them. This demarcation is a classic pedagogical signal in notebooks: the second half of the notebook is executable (the student should see the consultation unfold), while the first half is structural (the student can read it as production code). The print("Kernel instancie") that accompanies the instantiation is the written trace of this transition.

Adding plugins for each agent

kernel.add_plugin() registers a plugin instance under a name. Each plugin exposes its @kernel_function methods to the kernel, which makes them discoverable by the LLM. Here we register the three medical plugins (doctor, medical, pharmacist) on the shared kernel — they will be invocable automatically thanks to the FunctionChoiceBehavior.Auto() configured further down.

# Ajout des plugins pour chaque agent
kernel.add_plugin(DoctorPlugin(), plugin_name="doctor")
kernel.add_plugin(MedicalAIPlugin(), plugin_name="medical")
kernel.add_plugin(PharmacistPlugin(), plugin_name="pharmacist")
print("Kernel configuré avec le plugin médical")
print("Classes plugins medicaux definies")
print("Kernel configure avec le plugin medical")
Kernel configuré avec le plugin médical
Classes plugins medicaux definies
Kernel configure avec le plugin medical

Reading the result: kernel and plugins operational

"Kernel instancie" then "Kernel configuré avec le plugin médical" validate the sequence kernel = create_kernel() → kernel.add_plugin(DoctorPlugin(), plugin_name="doctor"). This second step is what distinguishes Semantic Kernel from a simple OpenAI wrapper: the kernel registers plugins as tools invocable by the LLM via the auto function calling layer. Without add_plugin, the Python native functions of DoctorPlugin would be unreachable by the agents, and the LLM would answer without medical grounding.

System prompts: defining the behavior of each agent

System prompts are the instructions that guide the behavior of each agent. They establish the role, constraints, and expected response style. Good prompt design is essential to avoid undesirable behaviors (premature diagnosis, unfounded recommendation).

DOCTOR_PROMPT = """
Vous êtes un médecin généraliste. Vous posez d'abord des questions pour mieux comprendre les symptômes de l'utilisateur,
puis vous donnez un diagnostic probable basé sur votre expertise médicale. 
Ne donnez jamais de diagnostic sans avoir recueilli assez d'informations.
"""

AI_MEDICAL_PROMPT = """
Vous êtes une IA médicale spécialisée en diagnostic. Analysez les symptômes fournis et proposez un diagnostic basé sur des statistiques et des études médicales. 
Soyez clair et donnez plusieurs hypothèses si nécessaire.
"""

PHARMACIST_PROMPT = """
Vous êtes un pharmacien qualifié. En fonction du diagnostic fourni, vous recommandez les médicaments appropriés. 
Mentionnez toujours les précautions d'utilisation et la nécessité d'une consultation médicale avant la prise de médicaments.
"""
print("Prompt médical configuré")
print("Prompts medicaux configures")
Prompt médical configuré
Prompts medicaux configures

Reading the result: system prompts configured

"Prompts medicaux configures" covers the 3 roles: DOCTOR_PROMPT (general practitioner, follow-up questions), AI_MEDICAL_PROMPT (AI analysis assistant), PHARMACIST_PROMPT (interaction checks). Each prompt structures the persona + expected behavior: professional tone, refusal to prescribe, asking for clarifications. This is an application of the role prompting pattern (cf. OpenAI Best Practices). The prompt exercise (further down) invites the student to write a pediatric prompt — adding a specialized persona is a classic persona engineering exercise.

Exercise 2: Adapt the prompts for a pediatric scenario

The current prompts are configured for an adult. The objective is to adapt the system for a pediatric consultation: the doctor must use language suited to children, the medical AI must take pediatric specifics into account (different dosage, specific vital signs), and the pharmacist must mention precautions for children.

Objective: write the three system prompts adapted to the pediatric context.

Hints: - # Step 1: Modify the doctor’s prompt for language accessible to children - # Step 2: Adapt the medical AI prompt for pediatric dosages and signs - # Hint: add constraints such as “always mention the recommended weight for dosage”

# Exercice 2 : Prompts adaptes au contexte pediatric
# TODO etudiant : rediger les trois prompts pediatric

PEDIATRIC_DOCTOR_PROMPT = ""    # Etape 1 : langage enfantin, questions adaptees
PEDIATRIC_AI_PROMPT = ""        # Etape 2 : dosages enfant, signes specific
PEDIATRIC_PHARMACIST_PROMPT = ""  # TODO etudiant : precautions enfant, posologie poids

print("Exercice a completer : prompts pediatric")
Exercice a completer : prompts pediatric

Creating Agents

The three system prompts define the behavior and constraints of each agent. The doctor must ask questions before diagnosing, the medical AI analyzes symptoms using a statistical approach, and the pharmacist recommends treatments while reminding users of the precautions for use. This separation of roles is fundamental in a multi-agent architecture.

# Création des agents
doctor_agent = ChatCompletionAgent(
    kernel=kernel,
    name="Docteur_Humain",
    instructions=DOCTOR_PROMPT,
)

ai_medical_agent = ChatCompletionAgent(
    kernel=kernel,
    name="IA_Medicale",
    instructions=AI_MEDICAL_PROMPT,
)
print("Agents de conversation créés")
print("Kernel configure avec plugin medical")
print("Agents de conversation crees")
Agents de conversation créés
Kernel configure avec plugin medical
Agents de conversation crees

Reading the result: conversational agents created

"Agents de conversation créés" marks the instantiation of three ChatCompletionAgent (doctor, medical AI, pharmacist) with their respective roles and the kernel’s ServiceId="openai". This is where the group model (AgentGroupChat, instantiated further down in the notebook) takes shape: three personas, one chat orchestrator, one medical termination strategy. The student should observe the agent/kernel distinction: an agent uses a kernel but does not own it. For scalability, adding a 4th agent (e.g. a nurse) does not require re-instantiating the kernel — only a new ChatCompletionAgent sharing the same one.

Configuration so that the medical agent automatically calls the plugins

By default, an agent relies only on its textual instructions. So that it can invoke the plugins registered in the kernel, we enable FunctionChoiceBehavior.Auto() in its KernelArguments: the LLM then decides by itself, depending on the context, to call one @kernel_function or another (severity of a symptom, medication recommendation, and so on). We apply this setting to the IA_Medicale agent, then create the pharmacist on the same model.

settings = kernel.get_prompt_execution_settings_from_service_id("openai")
settings.function_choice_behavior = FunctionChoiceBehavior.Auto()
ai_medical_agent.arguments = KernelArguments(settings=settings)

pharmacist_agent = ChatCompletionAgent(
    kernel=kernel,
    name="Pharmacien",
    instructions=PHARMACIST_PROMPT,
)
print("Paramètres d'exécution configurés")
print("Parametres d execution configures")
Paramètres d'exécution configurés
Parametres d execution configures

Reading the result: LLM execution settings

"Paramètres d'exécution configurés" marks kernel.get_prompt_execution_settings_from_service_id("openai") which configures the temperature, max_tokens, and top_p for the kernel’s LLM calls. These settings are shared by the 3 agents through the kernel — not configured agent by agent. It is an orchestration choice: for a medical consultation, we want reproducible and conservative answers (low temperature, typically 0.2-0.5), not creative ones. The student can observe the effect by changing temperature (from 0.0 = deterministic to 1.0 = exploratory) and re-running the settings cell above.

Definition of a termination strategy

The FunctionChoiceBehavior.Auto() setting allows the IA_Medicale agent to automatically invoke the plugins registered in the kernel (symptom severity, recommendations). Without this configuration, the agent would only have its textual instructions to formulate its responses.

class MedicalTerminationStrategy(TerminationStrategy):
    async def should_terminate(self, agent, history):
        return len(history) >= 6  # On limite à 6 échanges
print("Stratégie de terminaison médicale définie")
print("Strategie de terminaison medicale definie")
Stratégie de terminaison médicale définie
Strategie de terminaison medicale definie

Reading the result: medical termination strategy

"Stratégie de terminaison médicale définie" marks the instantiation of MedicalTerminationStrategy — a subclass of TerminationStrategy that detects the end of the multi-agent chat. In this notebook, the termination criterion is an exchange limit: should_terminate returns True as soon as the history reaches 6 messages (len(history) >= 6) — i.e. 1 patient message + 5 agent replies. Without an explicit strategy, AgentGroupChat loops forever. Detecting a diagnosis by keyword is precisely the exercise left to the student further down (DiagnosticTerminationStrategy). The student should observe this separation between orchestration and business logic: the termination strategy is a behavioral plugin, not a rule hard-coded into the chat.

Exercise 3: Termination strategy based on diagnosis

The current strategy stops after 6 messages. The objective is to implement a smarter strategy that detects when a probable diagnosis has been formulated by the medical AI (presence of words such as “diagnostic”, “hypothese”, “probablement” in the last message).

Objective: create DiagnosticTerminationStrategy that stops the conversation as soon as a diagnosis is issued or after a maximum of 8 exchanges.

Hints: - # Step 1: Define a list of keywords indicative of a diagnosis - # Step 2: Check for their presence in the content of the last message - # Hint: combine the diagnosis condition with a maximum exchange counter

from typing import ClassVar

class DiagnosticTerminationStrategy(TerminationStrategy):
    # TODO etudiant : implementer la detection de diagnostic
    DIAGNOSTIC_KEYWORDS: ClassVar[list] = []  # Etape 1 : mots-cles de diagnostic
    MAX_EXCHANGES: ClassVar[int] = 8
    
    async def should_terminate(self, agent, history):
        # Etape 2 : verifier diagnostic OU limite d'echanges
        result = False  # TODO etudiant : remplacer par la logique
        return result

print("Exercice a completer : DiagnosticTerminationStrategy")
Exercice a completer : DiagnosticTerminationStrategy

Creating the group chat with a termination strategy

The MedicalTerminationStrategy class inherits from TerminationStrategy and implements should_terminate. Here, the condition is simple: after 6 messages in the history, the dialogue stops. This approach avoids infinite loops while allowing enough exchanges for a complete diagnosis.

chat = AgentGroupChat(
    agents=[doctor_agent, ai_medical_agent, pharmacist_agent],
    termination_strategy=MedicalTerminationStrategy()  # Ajout de la stratégie
)
print("Chat de groupe médical configuré")
print("Prompts medicaux configures")
print("Chat de groupe medical configure")
Chat de groupe médical configuré
Prompts medicaux configures
Chat de groupe medical configure

Reading the result: medical group chat configured

"Chat de groupe médical configuré" validates the chain AgentGroupChat(agents=[doctor_agent, ai_medical_agent, pharmacist_agent], termination_strategy=MedicalTerminationStrategy()) — without an explicit selection_strategy: the default selection alternates agents in list order (round-robin, visible in the Selected agent at index 0/1/2 logs of the final consultation), and the termination_strategy detects the end (6-message history limit). This is the heart of the multi-agent pattern: without explicit orchestration, agents would speak in parallel. This notebook is a typical synthetic clinical reasoning use case where 3 LLM agents simulate a real consultation.

At this point, the entire multi-agent machinery is in place: shared kernel, 3 registered medical plugins (doctor/AI/pharmacist — the AllergyPlugin from guided example 1 is not registered: it is checked outside the consultation, and exercise 1 extends it without entering the kernel either), 3 conversational agents with their respective prompts, 1 medical termination strategy, 1 orchestrated group chat; all that remains is to define the execution function run_medical_chat() (below). Key pattern: the complexity of a multi-agent system is hidden in the setup (everything above) and visible in the execution (the last cells) — the student must grasp this distinction to script their own use cases.

Function to run the dialogue

The run_medical_chat function orchestrates the complete dialogue: it seeds the consultation with the patient’s symptoms, passes them to the AgentGroupChat, then iterates over the agents’ responses until the termination strategy declares the consultation complete (limit of 6 exchanges set by MedicalTerminationStrategy).

Two seeding modes:

  • Batch (BATCH_MODE = True, the Papermill/CI mode): a fixed clinical case (SYMPTOMES_DEMO) starts the consultation. Under headless execution stdin does not exist — calling input() raises StdinNotImplementedError before any agent has spoken at all, and the consultation never takes place. This is the same pattern as the two other case studies in this directory: Fort-Boyard seeds with a fixed word to guess, Barbie-Schreck with a randomly drawn style constraint.
  • Interactive (BATCH_MODE = False): the initial symptoms are typed in at the keyboard via input().

The consultation is then agent-driven: the three agents reply to one another without intervention. The try/except in the execution cell now catches only EOFError/KeyboardInterrupt — an orchestration failure (API key, network, quota) must remain visible, not silently absorbed.

from semantic_kernel.contents import ChatMessageContent, AuthorRole

SYMPTOMES_DEMO = ("Depuis trois jours, j'ai une fievre a 38,5 degres avec des maux de tete "
                  "et une legere toux seche. Je n'ai pas de douleur thoracique.")

async def run_medical_chat():
    logger.info("Début de la consultation médicale IA")

    # En mode batch (Papermill/CI), stdin n'existe pas : on amorce la consultation
    # avec un cas clinique fixe -- meme patron que Fort-Boyard et Barbie-Schreck.
    if BATCH_MODE:
        symptoms = SYMPTOMES_DEMO
        print(f"[Batch] Cas clinique démo : {symptoms}")
    else:
        symptoms = input("Décrivez vos symptômes : ")

    # Le message patient amorce l'historique INTERNE de l'AgentGroupChat (via
    # add_chat_message) : sans lui, la premiere invocation n'a aucun message
    # auquel repondre et echoue.
    await chat.add_chat_message(ChatMessageContent(role=AuthorRole.USER, content=symptoms))

    # Consultation agent-driven : les trois agents se repondent jusqu'a la limite
    # de 6 echanges posee par MedicalTerminationStrategy.
    while True:
        async for message in chat.invoke():
            logger.info(f"[{message.role}] {message.name}: {message.content}")
            print(f"{message.name}: {message.content}")

        if chat.is_complete:
            break

    logger.info("Consultation terminée.")

print("Fonction de chat médical prête")
Fonction de chat médical prête

Reading the result: medical chat function ready

"Fonction de chat médical prête" marks the culmination of the skeleton: the async function run_medical_chat() can be called to start the simulated consultation. The logger.info("Début de la consultation médicale IA") that opens run_medical_chat() is the first execution signal when the student runs the consultation execution cell (below). At this point, the notebook has instantiated 3 agents, 1 shared kernel, 3 registered plugins, 1 termination strategy, 1 group chat — the whole multi-agent machinery is in place. The execution cell launches await run_medical_chat() which will loop until MedicalTerminationStrategy.should_terminate() returns True (limit of 6 messages in the group history).

# except resserre : plus d'Exception nue. EOFError/KeyboardInterrupt = session
# interactive interrompue par l'utilisateur ; tout autre echec (API, cle, reseau)
# doit rester VISIBLE dans la sortie, pas etre absorbe.
try:
    await run_medical_chat()
except (EOFError, KeyboardInterrupt) as e:
    print(f"[Session interactive interrompue ({type(e).__name__}) - la consultation n'a pas eu lieu, relancez la cellule.]")
[Batch] Cas clinique démo : Depuis trois jours, j'ai une fievre a 38,5 degres avec des maux de tete et une legere toux seche. Je n'ai pas de douleur thoracique.
Docteur_Humain: Merci — quelques questions rapides pour mieux évaluer et orienter le diagnostic. Répondez autant que possible :

1. Quel âge avez-vous ? Êtes-vous enceinte ou immunodéprimé (prise de corticoïdes, chimiothérapie, VIH non contrôlé…) ?
2. Depuis quand exactement les symptômes ont-ils commencé ? La fièvre est-elle continue ou elle monte/descend au cours de la journée ?
3. Avez-vous pris un antipyrétique (paracétamol, ibuprofène) ? La fièvre baisse‑t‑elle avec le traitement ?
4. La toux est‑elle vraiment sèche (pas de crachats) ? Avez‑vous remarqué du sang dans les crachats ? La toux vous gêne au repos ou surtout la nuit/à l’effort ?
5. Avez‑vous une gêne respiratoire (essoufflement au repos ou à l’effort), une respiration sifflante, ou une sensation d’oppression thoracique ?
6. Avez‑vous perdu l’odorat ou le goût (anosmie/agueusie) ? Avez‑vous mal à la gorge, le nez bouché ou qui coule ?
7. Avez‑vous d’importantes courbatures, fatigue intense, frissons, sueurs nocturnes, maux de gorge, douleurs derrière les yeux ?
8. Avez‑vous des symptômes digestifs (nausées, vomissements, diarrhée) ?
9. Avez‑vous des antécédents médicaux significatifs (asthme, BPCO, diabète, maladie cardiaque, insuffisance rénale, cancer) ou prenez‑vous des médicaments réguliers ?
10. Êtes‑vous vacciné contre la Covid‑19 ? Avez‑vous fait un test Covid récemment (test antigénique ou PCR) ou un test grippe ?
11. Avez‑vous été en contact récent avec une personne malade (Covid, grippe ou autre) ou voyagé récemment ?
12. Fumez‑vous ? Consommez‑vous de l’alcool de façon importante ?
13. Avez‑vous un thermomètre/oxymètre ? Si oui, quelle est la température actuelle et la saturation en oxygène (SpO2) si vous avez un oxymètre ?
14. Avez‑vous d’autres signes inquiétants : confusion, somnolence importante, difficultés à avaler, raideur de la nuque, éruption cutanée étendue ?

Indiquez aussi si l’état s’aggrave rapidement. Une fois que vous aurez répondu, je pourrai proposer un diagnostic probable et des recommandations (examens à faire, traitement symptomatique, signes qui nécessitent une urgence).
IA_Medicale: Merci — avec les informations actuelles (fièvre 38,5 °C depuis 3 jours, céphalées, toux sèche légère, pas de douleur thoracique) voici une synthèse des hypothèses les plus probables, ce qu’il faut surveiller et les actions recommandées.

Hypothèses diagnostiques, par ordre de probabilité
- Infection virale des voies aériennes supérieures / bronchite virale (la plus probable) : fièvre modérée, céphalées et toux sèche sont typiques ; la majorité des bronchites aiguës chez l’adulte sont d’origine virale.
- Covid‑19 : symptômes compatibles (fièvre, céphalées, toux sèche). Fréquent actuellement selon contexte épidémique.
- Grippe (influenza) : possible surtout en période épidémique ; souvent atteinte plus brutale avec courbatures intenses mais peut se présenter ainsi.
- Pneumonie (bactérienne ou atypique, ex. Mycoplasma) : moins probable en l’absence de dyspnée, douleur thoracique, toux productive ou signes de focalisation à l’auscultation, mais doit être envisagée si aggravation ou signes respiratoires.
- Autres (moins probables) : sinusite, mononucléose, etc.

Quelques chiffres utiles (estimation générale)
- Dans les consultations pour toux aiguë, la majorité des cas (environ 60–80 %) sont d’origine virale et s’améliorent sans antibiotiques.
- La probabilité de pneumonie dans le cabinet de ville reste faible si absence de dyspnée, tachycardie importante, fièvre élevée persistante ou signes focaux à l’auscultation.

Que faire maintenant (actions pratiques)
1. Tester pour le SARS‑CoV‑2 : faites un test antigénique ou PCR dès que possible. Si antigénique négatif mais forte suspicion, réaliser un PCR.
2. Traitement symptomatique :
   - Paracétamol 500–1000 mg toutes les 4–6 heures si nécessaire pour fièvre/douleur ; ne pas dépasser 3 g/24 h (adapter selon antécédents hépatiques).
   - Hydratation, repos, inhalations d’air humide/vaisselle chaude, pastilles/honey pour la toux si utile.
   - Éviter les antibiotiques sauf s’il y a preuve d’infection bactérienne (écoulement purulent persistant, aggravation, examen clinique évocateur).
3. Isolement préventif en attendant résultat Covid / amélioration (si test positif, suivre les recommandations locales).
4. Si vous avez des facteurs de risque (âge >65, immunodépression, grossesse, maladies chroniques respiratoires, cardiaques, diabète), contactez votre médecin rapidement — seuil plus bas pour examen et éventuel traitement antiviraux (grippe) ou prise en charge.

Signes d’alerte (consulter en urgence ou appeler le 15/112)
- Essoufflement important, difficulté à respirer, respiration rapide.
- Saturation en oxygène (SpO2) < 92 % si vous avez un oxymètre.
- Douleur thoracique importante ou douleur qui s’aggrave.
- Confusion, somnolence importante, incapacité à boire ou déshydratation, vomissements incoercibles.
- Fièvre très élevée persistante ou aggravation rapide en 24–48 h.

Examens que votre médecin peut demander si persistance/aggravation
- Test PCR/antigénique Covid, test grippe selon saison.
- Radiographie thoracique si suspicion de pneumonie.
- CRP / NFS (pour orienter possible surinfection bactérienne).
- Examen clinique (auscultation) pour rechercher foyer pulmonaire.

Durée attendue
- Si viral/simple bronchite : amélioration sous quelques jours, toux pouvant persister 1–3 semaines.
- Si grippe : souvent nette amélioration après 2–7 jours mais fatigue peut durer plus longtemps.
- Si Covid : cours variable, surveillez évolution.

Pour affiner le diagnostic et les conseils, pouvez‑vous préciser rapidement :
- Votre âge et antécédents (asthme, diabète, immunosuppression, grossesse…) ?
- Avez‑vous fait un test Covid ou grippe ? Vaccinations Covid/grippe à jour ?
- Avez‑vous une saturation (SpO2) et la température actuelle ? La fièvre répond‑elle au paracétamol ?

Si vous voulez, répondez à ces points et je vous donnerai une orientation plus précise. Si vos symptômes s’aggravent ou si vous avez un des signes d’alerte ci‑dessus, consultez sans délai.
Pharmacien: Merci. Avec une fièvre modérée (38,5 °C), céphalées et une toux sèche depuis 3 jours, le plus probable est une infection virale des voies aériennes (bronchite virale, Covid ou grippe selon contexte). Voici les mesures et médicaments que je peux recommander en officine pour soulager les symptômes, avec les précautions. Avant de prendre un médicament, consultez votre médecin ou votre pharmacien si vous avez un doute, des maladies chroniques ou si vous prenez d’autres médicaments.

1) Traitement antipyrétique / antalgique (premier choix)
- Paracétamol (ex. Doliprane, Dafalgan…) : adulte 500–1000 mg toutes les 4–6 h si nécessaire, maximum 3 g/24 h (certaines sources recommandent 3 g ; si insuffisance hépatique, alcoolisme chronique ou faible poids, demander l’avis du médecin et réduire la dose).  
- Précautions : surveiller prise cumulée (produits combinés), éviter en cas d’insuffisance hépatique sévère. Consultez votre médecin si vous devez dépasser plusieurs jours.

2) Anti‑inflammatoire non stéroïdien (si besoin et si pas de contre‑indication)
- Ibuprofène (ex. Advil, Nurofen…) : adulte 200–400 mg par prise, toutes les 6–8 h si besoin ; maximum 1 200 mg/24 h en automédication.  
- Contre‑indications / précautions : antécédent d’ulcère digestif, insuffisance rénale, insuffisance cardiaque, prise d’anticoagulants, grossesse (éviter, surtout 3e trimestre), asthme sensibilisé aux AINS. En cas de doute, privilégier le paracétamol et demandez un avis médical.

3) Pour la toux sèche (soulagement)
- Mesures non médicamenteuses : hydratation, humidifier l’air, inhalations d’eau chaude/menthol, miel (pour adultes et enfants >1 an) le soir pour calmer la toux, pastilles ou pastilles anesthésiantes pour la gorge.  
- Antitussifs oraux (sur avis du pharmacien/médecin) : dextrométhorphane sirop (utilisé chez l’adulte) : posologie habituelle adulte 10–30 mg toutes les 4–8 h selon produit, maximum ≈120 mg/24 h.  
  - Précautions : interaction possible avec antidépresseurs (risque de syndrome sérotoninergique) et contre‑indiqué avec IMAO. Ne pas utiliser chez l’enfant sans avis.  
- Autre option en officine : cloperastine (dans les pays où disponible) — demander conseil au pharmacien.  
- Éviter les expectorants si toux strictement sèche sans mucosités, sauf si indiqué après examen.

4) Mesures complémentaires
- Repos, hydratation, paracétamol pour fièvre.  
- Si congestion nasale : spray/solutions salines pour laver le nez.  
- Si mal de gorge : pastilles, gargarismes d’eau salée.

5) À éviter en automédication
- Antibiotiques : ne sont pas indiqués pour une toux/fièvre d’origine virale. Ils ne doivent être pris que si un médecin diagnostique une surinfection bactérienne.  
- Mélanges multiples sans avis (ex. combiner plusieurs produits contenant du paracétamol).

6) Quand consulter / signes d’urgence
Consultez rapidement ou rendez‑vous aux urgences si : essoufflement important, respiration rapide, douleur thoracique, SpO2 < 92 % (si oxymètre), fièvre qui s’aggrave ou persiste > 72 h malgré traitement, apparition de crachats sanglants, confusion, somnolence importante, incapacité à s’alimenter ou à boire.  
Faites un test antigénique/PCR SARS‑CoV‑2 dès que possible si vous suspectez la Covid, et isolez‑vous en attendant.

7) Informations utiles à me donner (ou au médecin/pharmacien)
- Votre âge, grossesse possible, maladies chroniques (foie, reins, cœur, ulcère, asthme), traitements en cours, allergies médicamenteuses. Ces éléments modifient le choix et la posologie.

En résumé : en première intention paracétamol pour la fièvre et la douleur ; mesures non médicamenteuses pour la toux (miel, pastilles, humidifier l’air) ; antitussifs comme le dextrométhorphane uniquement pour la toux gênante et après vérification d’éventuelles interactions/contre‑indications. Et surtout : consultez votre médecin si vous avez des facteurs de risque, si les symptômes s’aggravent ou persistent, ou avant de commencer tout traitement en cas de doute. Voulez‑vous me dire votre âge et vos antécédents pour adapter les conseils et les doses ?
Docteur_Humain: Merci — avant de poser un diagnostic probable, j’ai besoin de quelques précisions rapides (répondez autant que possible) :

1. Quel âge avez‑vous ? Êtes‑vous enceinte ?  
2. Avez‑vous des maladies chroniques (asthme, BPCO, diabète, maladie cardiaque, insuffisance rénale, maladie du foie, cancer, VIH…) ou prenez‑vous des traitements immunosuppresseurs/corticoïdes/chimiothérapie ?  
3. Les symptômes ont‑ils commencé il y a exactement 3 jours ? La fièvre est‑elle continue ou monte/descend dans la journée ? Température actuelle (si possible) ?  
4. Avez‑vous pris un antipyrétique (paracétamol, ibuprofène) ? La fièvre baisse‑t‑elle avec ce traitement ?  
5. Avez‑vous une gêne respiratoire (essoufflement au repos ou à l’effort), respiration sifflante, ou fatigue importante ? Avez‑vous un oxymètre et une SpO2 ?  
6. La toux est‑elle complètement sèche (pas de crachats) ? Elle est plus gênante le jour ou la nuit ?  
7. Avez‑vous perdu l’odorat ou le goût ? Mal de gorge, nez qui coule ? Courbatures, frissons, nausées, diarrhée ?  
8. Avez‑vous été en contact récent avec une personne Covid+ ou grippée ? Avez‑vous fait un test Covid ou grippe récemment ?  
9. Fumez‑vous ? Consommez‑vous beaucoup d’alcool ?  
10. Avez‑vous d’autres signes inquiétants : douleur thoracique, crachats sanglants, confusion, somnolence marquée, raideur de la nuque, éruption cutanée importante ?

Répondez à ces points et je vous donnerai un diagnostic probable et des recommandations adaptées (examens, traitement symptomatique, signes nécessitant une urgence). Si vous avez une difficulté respiratoire importante, douleur thoracique intense, ou somnolence/confusion, consultez d’urgence (15/112) immédiatement.
IA_Medicale: Merci — avec les seuls éléments fournis (fièvre 38,5 °C depuis 3 jours, maux de tête, toux sèche légère, pas de douleur thoracique) voici une synthèse claire, chiffrée et des recommandations pratiques.

Diagnostic différentiel (par ordre de probabilité)
- Bronchite/ infection virale des voies aériennes supérieures (60–80 % des toux aiguës en ambulatoire) — la plus probable.  
- Covid‑19 — symptômes compatibles ; probabilité dépend du contexte épidémique et des contacts.  
- Grippe (influenza) — possible surtout en saison épidémique ; souvent plus brutale et avec courbatures marquées.  
- Pneumonie (bactérienne ou atypique, ex. Mycoplasma) — moins probable sans dyspnée, douleur thoracique, toux productive ou signes focaux à l’auscultation ; mais à considérer si aggravation.  
- Autres causes moins probables : sinusite, mononucléose, etc.

Éléments chiffrés/évidences (estimation générale)
- 60–80 % des toux aiguës chez l’adulte sont d’origine virale et n’exigent pas d’antibiotiques (recommandations de nombreuses sociétés de pneumologie et d’infectiologie).  
- La pneumonie communautaire est peu fréquente chez un patient sans dyspnée, fièvre très élevée ou signes focaux à l’auscultation ; la décision d’imagerie (radio thorax) se fait sur examen clinique et facteurs de risque.

Que faire maintenant (mesures immédiates)
1. Tester pour SARS‑CoV‑2 (antigénique rapide ou PCR) dès que possible ; isolez‑vous en attendant le résultat.  
2. Traitement symptomatique :
   - Paracétamol 500–1000 mg toutes les 4–6 h si nécessaire (max. ≈3 g/24 h selon contexte).  
   - Hydratation, repos, humidifier l’air, miel le soir (adultes) et pastilles pour la gorge.  
   - Antitussifs (ex. dextrométhorphane) uniquement si la toux est très gênante et après vérification d’éventuelles interactions/contre‑indications.  
   - Éviter les antibiotiques en automédication.
3. Si symptômes grippaux prononcés et vus très tôt (<48 h), un médecin peut proposer un traitement antiviral (oseltamivir) selon facteurs de risque et confirmation/suspicion clinique.

Signes d’urgence — consulter immédiatement (ou appeler secours)
- Essoufflement important, difficulté à respirer, respiration très rapide.  
- SpO2 < 92 % (si vous avez un oxymètre).  
- Douleur thoracique importante, crachats sanglants.  
- Confusion, somnolence anormale, incapacité à boire ou déshydrater.  
- Fièvre qui s’aggrave nettement ou persiste >72 h malgré traitement.

Examens que le médecin pourra demander si persistance/aggravation
- Test PCR/antigénique Covid (et test grippe selon saison), nasopharyngé.  
- Examen clinique (auscultation) → si doute : radiographie thoracique.  
- CRP / NFS pour évaluer surinfection bactérienne éventuelle.

Durée attendue
- Amélioration attendue en quelques jours pour une infection virale ; la toux peut persister 1–3 semaines. Si pas d’amélioration ou aggravation en 48–72 h, recontacter un médecin.

Informations qui me permettraient d’affiner le diagnostic et les conseils
- Votre âge et antécédents (asthme, BPCO, diabète, insuffisance cardiaque, insuffisance rénale, maladie du foie, immunodépression, grossesse).  
- Vaccination Covid/grippe à jour ? Test Covid/grippe déjà réalisé ?  
- Réponse au paracétamol ? Température et saturation si disponibles ?  
- Contact récent avec une personne malade ?

Si vous me donnez ces informations, j’adapterai les recommandations (posologie, besoin d’examens, probabilité de complications). Si vous avez actuellement une difficulté respiratoire ou un des signes d’alerte ci‑dessus, consultez d’urgence.

Reading the result: actual execution of the simulated consultation

The output above is a real consultation (5 gpt-5-mini calls counted in the HTTP logs). The Début de la consultation médicale IA log opens the trace, then the demo clinical case seeds the group history. The student observes:

  1. The round-robin rotation of the agents — the Selected agent at index 0/1/2 logs show the default selection_strategy passing the baton: Docteur_Humain → IA_Medicale → Pharmacien → Docteur_Humain → IA_Medicale (5 agent turns).
  2. Auto function calling in action — from its very first turn, the doctor invokes 2 plugins in parallel (doctor-ask_followup_questions + medical-check_symptom_severity): FunctionChoiceBehavior.Auto() really executes, it is not a description.
  3. Termination by exchange limit — 1 patient message + 5 agent replies = 6 messages: MedicalTerminationStrategy ends the consultation (Consultation terminée.). Detecting a final diagnosis by keyword did not happen: that is the exercise left to the student (DiagnosticTerminationStrategy, stub above).

This replayable trace is what makes the notebook pedagogical: the student can re-read the async sequence to understand the agent-selection mechanism, instead of reading a black box.

What we built

This use case illustrates several advanced Semantic Kernel concepts:

Concept Implementation
Specialized agents Three distinct roles (Doctor, Medical AI, Pharmacist) with dedicated system instructions
Plugins @kernel_function Each agent has a plugin with specific functions (follow-up questions, severity assessment, medication recommendations)
AgentGroupChat Multi-agent orchestration with automatic handoff between the three participants
Termination strategy MedicalTerminationStrategy stops the dialogue after 6 exchanges to avoid infinite loops
FunctionChoiceBehavior.Auto() The Medical AI agent can automatically call kernel plugins to enrich its responses

Key points to remember

  1. Separation of responsibilities: each agent has a specific role, its own instructions, and its own tools. This modularity makes it easier to debug and evolve the system.

  2. Plugins as tools: @kernel_function exposes capabilities that agents can invoke via FunctionChoiceBehavior.Auto(). The LLM decides when and which plugin to call based on the context.

  3. Control strategies: the TerminationStrategy is essential in an AgentGroupChat to prevent agents from conversing indefinitely. Other strategies exist (agent selection, message filtering).

Going further

  • Add a simulated Patient agent that describes symptoms realistically
  • Implement a persistent consultation history (storage in a database)
  • Use a vector model to search for similar medical cases in a knowledge base
  • Add ethical guardrails (refusal to diagnose certain conditions, systematic referral to a healthcare professional)
Retour au sommet