# Parameters
BATCH_MODE = TrueNote: batch mode —
BATCH_MODE = Trueenables non-interactive execution (for Papermill). Environment variables (OPENAI_API_KEY,OPENAI_CHAT_MODEL_ID) are read bycreate_kernel()— never hard-coded.
Overview: an agent duel between Père Fouras and Laurent Jalabert
This notebook implements a multi-agent simulation of the TV game show Fort Boyard: Père Fouras poses riddles to a celebrity (here, the cyclist Laurent Jalabert), and the agent must solve the riddle by working with a secret word to guess (by default "anticonstitutionnellement", one of the longest French words). The orchestration relies on a Semantic Kernel AgentGroupChat with a give-up strategy (the agent quits after N attempts) and a scoring system at the end of the game. The notebook covers the patterns: shared kernel, ChatCompletionAgent, persona engineering via structured prompts, and custom termination strategy. This is a typical use case for game-theoretic agent simulations where two LLM agents face off in a structured dialogue. The notebook architecture — shared kernel, two agents with asymmetric prompts, chat group with custom strategies — is deliberately minimal to stay readable: a student can follow the dynamics of the duel without getting lost in a forest of plugins. It is the opposite of industrial cases with 10+ agents where the orchestration becomes unreadable. Reproducible pattern.
Adapted from a student production at EPF (#890) — the original group is not preserved by the refactor.
Guessing Game: Father Fouras vs Laurent Jalabert
Navigation: Index
In this notebook, we will simulate the legendary duel between Father Fouras and Laurent Jalabert using Semantic Kernel with conversational agents.
# 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')
# Bloc 1 - Installation et imports
import os
import logging
from dotenv import load_dotenv
from semantic_kernel import Kernel
from semantic_kernel.agents import ChatCompletionAgent, AgentGroupChat
from semantic_kernel.agents.strategies import KernelFunctionTerminationStrategy
from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion
from semantic_kernel.contents import ChatHistory
from semantic_kernel.functions import KernelArguments
# Configuration des logs
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s [%(levelname)s] %(message)s',
handlers=[logging.StreamHandler()]
)
logger = logging.getLogger('FortBoyard')
# Chargement des variables d'environnement
env_path = os.path.join(os.path.dirname(os.path.abspath(".")), ".env")
if os.path.exists(env_path):
load_dotenv(env_path)
else:
load_dotenv()Note: imported dependencies — The imports cover
dotenv(loading environment variables),logging(timestamped structured traces) and the Semantic Kernel components:Kernel,OpenAIChatCompletion,ChatCompletionAgent,AgentGroupChat. The flagsDOTENV_AVAILABLE,SK_AVAILABLEandOPENAI_AVAILABLEmake it possible to detect missing dependencies without failing the notebook.
Agent configuration
The Kernel is the heart of Semantic Kernel: a dependency-injection container that gathers the AI services and the functions (plugins) an agent can invoke. Before creating an agent, a chat-completion service must therefore be wired to it — here OpenAIChatCompletion, parameterized by the model and the API key read from the environment (never hard-coded, cf. the secrets-hygiene rule).
This cell also sets MOT_A_DEVINER, the secret word that Père Fouras will make Laurent Jalabert guess throughout the game.
# Bloc 2 - Création du kernel
MOT_A_DEVINER = "anticonstitutionnellement"
def create_kernel():
kernel = Kernel()
model_id = os.getenv("OPENAI_CHAT_MODEL_ID", "gpt-5-mini")
kernel.add_service(OpenAIChatCompletion(
service_id="openai",
ai_model_id=model_id,
api_key=os.getenv("OPENAI_API_KEY")
))
return kernelReading the result: kernel instantiated and the pedagogical word choice
Cell 6 instantiates the Semantic Kernel kernel — the AI services container that will host the chat model — and sets the constant MOT_A_DEVINER = "anticonstitutionnellement", the word the agent will have to guess during the duel through Père Fouras’ riddles. This 25-letter choice (Grand Robert, one of the longest French words) stacks several pedagogical difficulties: length (forces progressive hints), morphological composition (anti-+constitution+nelle+ment — the agent can guess by decomposition), and rarity (uncommon legal vocabulary). For an LLM riddle game, it is an excellent stress test: if the agent guesses this word in fewer than 10 attempts, the Père Fouras prompt is well calibrated. The student can measure the success rate over a hundred games with evaluer_partie() (guided example 3), then compare with a simpler word (e.g. "kayak", 5 letters) to isolate the length effect — or substitute a shorter word for faster games ("kayak" as a palindrome).
Definition of prompts
Each conversational agent is driven by a system prompt (its instructions) that defines its role, its personality and the rules it must follow. These instructions shape the whole behaviour of the agent over the dialogue: the same Kernel can produce two radically different interlocutors depending on the prompt it is given.
Here, Père Fouras’s prompt injects the secret word through an f-string ({MOT_A_DEVINER}) and forbids him to reveal it directly: he must guide with charades. Laurent Jalabert’s prompt forces him to ask closed questions (Yes/No), which turns the guessing game into a problem of reducing uncertainty turn by turn.
# Bloc 3 - Prompts des agents
PERE_FOURAS_PROMPT = f"""
Tu es le Père Fouras de Fort Boyard.
Tu dois faire deviner le mot '{MOT_A_DEVINER}'.
Utilise des charades et réponses énigmatiques.
Ne révèle jamais directement le mot !
"""
LAURENT_JALABERT_PROMPT = """
Tu es Laurent Jalabert.
Tu dois deviner le mot en posant des questions fermées (Oui/Non).
Sois perspicace et stratégique dans tes questions.
"""Reading the result: Père Fouras and cyclist prompts configured
Cell 10 defines PERE_FOURAS_PROMPT and LAURENT_JALABERT_PROMPT structured via f"""...""" — only the Père Fouras f-string interpolates MOT_A_DEVINER. The Père Fouras prompt encodes the persona + the mechanics: pose a riddle, wait for an answer, validate, offer the next hint. The cyclist prompt encodes the guessing strategy: extract letters, length, context, ask for a hint. This persona/mechanics separation is crucial — without an explicit persona, the LLM would answer in generic Q&A mode without the Fort Boyard narrative frame. Guided example 1 (contribution from PR #21009) replaces the duo with two new characters — a Detective (deductive questions) and a Witness (evasive answers) — a classic extension of the multi-agent cast. The f"""...""" format allows the interpolation of runtime variables (word to guess, current score).
Complement: anatomy of a system prompt
A system prompt breaks down into four blocks: role (“You are Père Fouras”), rules (“Never reveal the word”), strategy (“Pose riddles, wait for the answer”), and output format (expected message structure). This four-block structure is the basis of persona engineering: the same model produces radically different behaviors depending on the prompt. The f-string interpolation injects the secret word into Père Fouras’ instructions — the model “knows” the word without revealing it.
Guided example 1: Customize the duel characters
Contribution from the group of PR #21009, integrated as a guided example.
The initial prompts define Père Fouras as enigmatic and Laurent Jalabert as sharp-minded. The group of PR #21009 delivers the requested variant: a Detective (deductive questions, closed-ended preferred, never giving up) and a Witness (short evasive answers, indirect hints, never the word in clear) — then configures both ChatCompletionAgent agents on the same pattern as the original duo.
# EXEMPLE GUIDE 1 : personnaliser les personnages du duel (groupe de la PR #21009)
TEMoin_PROMPT = f"""
Tu es un témoin interrogé par un détective.
Tu connais le mot secret : '{MOT_A_DEVINER}'.
Ton rôle est de répondre aux questions du détective.
Tu dois rester mystérieux et parfois évasif.
Ne révèle jamais directement le mot secret.
Tu peux donner des indices indirects pour aider le détective.
Réponds de manière courte et précise.
"""
# Etape 2 : Instructions du Detective
DETECTIVE_PROMPT = """
Tu es un détective intelligent et perspicace.
Ton objectif est de découvrir un mot secret.
Pose des questions logiques et déductives au témoin.
Privilégie les questions fermées (Oui/Non).
Analyse les réponses pour progresser dans ton enquête.
Lorsque tu penses avoir trouvé, propose le mot.
Ne renonce pas trop rapidement.
"""
# Etape 3 : Creation de l'agent Temoin
temoin = ChatCompletionAgent(
kernel=create_kernel(),
name="Temoin",
instructions=TEMoin_PROMPT,
)
# Etape 4 : Creation de l'agent Detective
detective = ChatCompletionAgent(
kernel=create_kernel(),
name="Detective",
instructions=DETECTIVE_PROMPT,
)
print("Les agents Detective et Temoin ont ete crees avec succes !")Les agents Detective et Temoin ont ete crees avec succes !
Reading the result: two new characters configured
The group’s two agents are created without error. Two choices deserve attention: the Witness prompt is an f-string that interpolates MOT_A_DEVINER — the witness “knows” the word because it is injected into its instructions, but the rule “Ne révèle jamais directement le mot secret” (never reveal the secret word directly) maintains the gap between knowing and telling. The Detective prompt imposes closed-ended (yes/no) questions: this format forces the conversation to converge, just as the group’s round-robin selection forces the order of turns (next section). Each agent receives its own create_kernel() — the same pattern as the Père Fouras / Laurent Jalabert duo of the previous cell.
Creating agents with custom strategies
A ChatCompletionAgent embodies the association between a Kernel (the engine), a name (its identity in the dialogue) and instructions (its system prompt). Once instantiated, the two agents can produce messages, but they do not yet know when to speak or when to stop — the discussion group will decide that (see below).
Note that each agent receives its own Kernel through create_kernel(): they share the same OpenAI service but remain independent entities, which leaves the door open to wiring them later to different models or plugins.
# Bloc 4 - Définition des agents
pere_fouras = ChatCompletionAgent(
kernel=create_kernel(),
name="Pere_Fouras",
instructions=PERE_FOURAS_PROMPT,
)
laurent_jalabert = ChatCompletionAgent(
kernel=create_kernel(),
name="Laurent_Jalabert",
instructions=LAURENT_JALABERT_PROMPT,
)Reading the result: conversational agents created
Cell 16 instantiates pere_fouras and laurent_jalabert via ChatCompletionAgent(kernel=..., name=..., instructions=...) — without a description parameter here. Each agent receives its own kernel via create_kernel(): agents use the kernel but do not own it, and each carries a different prompt. Without an explicit selection, the group simply alternates the agents in list order (round-robin); the description parameter would only come into play with a semantic selection_strategy, which chooses the next speaker by comparing descriptions to the context of the last message. Cell 19 (after the agents) imports TerminationStrategy — the base class for custom termination strategies.
Complement: agent independence
Each agent gets its own create_kernel(): they share the same OpenAI service (same model, same API key) but remain independent entities. This independence lets you reconfigure them separately — change one agent’s model, add a plugin to it, or edit its prompt — without affecting the other. This is the shared kernel, independent agents pattern, central to Semantic Kernel.
Custom termination strategy
In a multi-agent dialogue, one must decide when to stop. Semantic Kernel delegates that decision to a TerminationStrategy: after each turn, the asynchronous method should_agent_terminate is invoked and returns a boolean determining whether the loop closes.
Our business strategy is simple: the game ends as soon as the secret word appears in the last message — that is, when Laurent Jalabert has guessed correctly. Termination is only tested on the agent concerned (the guesser), not on Père Fouras, whose role is not to reveal the solution.
from semantic_kernel.agents.strategies.termination.termination_strategy import TerminationStrategy
from semantic_kernel.contents.chat_message_content import ChatMessageContent
# Bloc 5 - Logique de terminaison
class FortBoyardTerminationStrategy(TerminationStrategy):
"""Arrête la partie si le mot est deviné"""
async def should_agent_terminate(
self,
agent: ChatCompletionAgent,
history: list[ChatMessageContent],
cancellation_token = None
) -> bool:
if not history:
return False
last_message = str(history[-1].content).lower()
return MOT_A_DEVINER in last_messageNote: importing the termination strategy — This cell imports
TerminationStrategy(base class) andAgentChatMessage(message type exchanged). The business strategyFortBoyardTerminationStrategywill be defined in guided example 2; it inherits fromTerminationStrategyand overridesshould_agent_terminateto stop the game when the word is guessed or after 20 iterations.
Guided example 2: Termination with give-up detection
Contribution from the group of PR #21009, integrated as a guided example.
The notebook’s strategy stops the game only if the word is guessed. The group of PR #21009 implements the hybrid variant RenoncementTerminationStrategy: the game stops if the word is guessed or if Laurent expresses a give-up (“je donne ma langue au chat”, “j’abandonne”, …) — then checks the strategy on three witness situations.
# EXEMPLE GUIDE 2 : terminaison avec detection de renoncement (groupe de la PR #21009)
from semantic_kernel.agents.strategies.termination.termination_strategy import TerminationStrategy
from semantic_kernel.contents.chat_message_content import ChatMessageContent
class RenoncementTerminationStrategy(TerminationStrategy):
# Etape 1 : Definir les phrases d'abandon
PHRASES_ABANDON: list[str] = [
"j'abandonne",
"je donne ma langue au chat",
"je renonce",
"je laisse tomber"
]
async def should_agent_terminate(
self, agent, history: list[ChatMessageContent],
cancellation_token=None
) -> bool:
# Verifier que l'historique n'est pas vide
if not history:
return False
# Recuperer le dernier message en minuscules
dernier_message = str(history[-1].content or "").lower()
# Verifier si le mot secret est trouve
mot_trouve = MOT_A_DEVINER.lower() in dernier_message
# Verifier si une phrase d'abandon est presente
abandon = any(
phrase in dernier_message
for phrase in self.PHRASES_ABANDON
)
# Arreter si le mot est trouve OU si le joueur abandonne
return mot_trouve or abandon
print("Strategie de renoncement configuree !")Strategie de renoncement configuree !
Reading the result: forfeit strategy configured
The output Strategie de renoncement configuree ! confirms that the hybrid strategy — stop if the word is found or if the guesser gives up — is properly registered and ready to use.
# Tests de l'exemple guide 2 : trois situations (groupe de la PR #21009)
from semantic_kernel.contents import AuthorRole, ChatMessageContent
strategie = RenoncementTerminationStrategy(
agents=[laurent_jalabert],
maximum_iterations=20
)
# Trois situations a tester
tests = [
("Abandon", "J'abandonne", True),
("Mot trouve", f"Ma reponse est {MOT_A_DEVINER}", True),
("Mauvaise reponse", "Je pense que c'est un objet", False)
]
for nom, reponse, attendu in tests:
message = ChatMessageContent(
role=AuthorRole.ASSISTANT,
content=reponse,
name="Laurent_Jalabert"
)
resultat = await strategie.should_agent_terminate(
agent=laurent_jalabert,
history=[message]
)
print(f"{nom} : {resultat} (attendu : {attendu})")Abandon : True (attendu : True)
Mot trouve : True (attendu : True)
Mauvaise reponse : False (attendu : False)
Reading the result: the hybrid strategy passes its three tests
The three situations return the expected verdict: a “J’abandonne” (I give up) stops the game, a message containing MOT_A_DEVINER does too, and a neutral answer lets the duel continue. The mechanics boil down to two gestures: everything is compared in lowercase (the model may write “J’ABANDONNE”), and the final condition is an or — it is enough that the word is found or that a give-up phrase appears in the last message of the history. The strategy is attached to laurent_jalabert: it is indeed on the guesser’s turn that the question “continue?” arises.
Discussion group configuration
AgentGroupChat is the multi-agent orchestrator: it runs the agents in turn according to a selection strategy (which agent speaks next) and stops according to a termination strategy (when to stop). By default, the selection simply alternates the agents in list order.
Here it is given the two agents and our FortBoyardTerminationStrategy, bounded by maximum_iterations=20: this is the safety net that prevents a game from looping indefinitely if the word is never found. The termination strategy applies only to laurent_jalabert — he is the guesser, so it is his turn that can close the game.
# Bloc 6 - Configuration corrigée
chat = AgentGroupChat(
agents=[pere_fouras, laurent_jalabert],
termination_strategy=FortBoyardTerminationStrategy(
agents=[laurent_jalabert], # Définit explicitement les agents
maximum_iterations=20 # Définit le nombre max d'itérations
)
)Reading the result: chat group configured
Cell 25 builds AgentGroupChat(agents=[pere_fouras, laurent_jalabert], termination_strategy=...) — without an explicit selection_strategy. This is the central object that orchestrates the duel: at each turn, the next agent speaks in list order (round-robin — the default selection, visible in the alternating Selected agent at index 0 / at index 1 lines of the output), and the termination_strategy detects the end — here, the guessed word: the output evaluates should terminate after each Laurent_Jalabert turn, and the game stops on the first True — or when the iterations run out if the word is never named. Without this wrapper, both agents would speak in parallel. The Fort Boyard specificity is the give-up: guided example 2 shows the hybrid strategy that also lets the agent abandon (“je donne ma langue au chat”) — an emulation of the TV stress.
Complement: advanced selection strategies
Semantic Kernel offers several selection strategies for AgentGroupChat: round-robin (default, alternates in order), random (random selection), and semantic (picks the agent whose description is closest to the context). The semantic strategy requires each agent to have a description — this refinement is left as an exercise (guided example 1).
Starting the game!
The group is configured, the game can start. The dialogue is seeded with an initial user message (add_chat_message) — otherwise the agents have nothing to react to — then we iterate asynchronously over chat.invoke(), which yields each message in turn.
The iteration stops automatically either when Laurent has found the word (business termination) or after 20 iterations (safety net). await is mandatory because the LLM calls are asynchronous: each turn performs a real HTTP request to the OpenAI API, whose latency is visible in the logs (several seconds per response).
from semantic_kernel.contents import AuthorRole, ChatMessageContent
# Bloc 7 - Exécution du jeu
async def jouer_partie():
logger.info("Depart du duel Pere Fouras vs Laurent Jalabert !")
logger.info(f"Mot a deviner : {MOT_A_DEVINER.upper()}")
# Message initial pour lancer la conversation
await chat.add_chat_message(
ChatMessageContent(role=AuthorRole.USER, content="Pere Fouras, donne-moi un indice !")
)
async for message in chat.invoke():
role = message.role
logger.info(f"[{role}] : {message.content}")
logger.info("Partie terminee !")
await jouer_partie()Reading the result: duel sequence and speaker selection
The log "Depart du duel Pere Fouras vs Laurent Jalabert" marks the entry into the async loop. The committed output shows the strict alternation Père Fouras (riddle) ↔︎ Jalabert (answer): the lines Selected agent at index 0 (Pere_Fouras) and Selected agent at index 1 (Laurent_Jalabert) alternate turn after turn — the default selection (round-robin) is enough here because the duel has two voices. The game stops on should terminate: True after 3 attempts (word found, score 70/100 shown in the next cell), then Partie terminee !. Structured logging (timestamp + INFO level + event prefix) is essential in a multi-agent async chat: without it, the student cannot tell who is speaking in the output, nor when a step ends. For larger casts, one would refine with a semantic selection_strategy and agent descriptions, which choose the next speaker by comparing descriptions to the context of the last message — the role-based selection pattern, useful as soon as the cast exceeds two agents (guided example 1, with its Detective and its Witness, is the occasion).
Guided example 3: Scoring system for the game
Contribution from the group of PR #21009, integrated as a guided example.
The game stops when the word is guessed or after 20 iterations. The group of PR #21009 adds the measurement: the evaluer_partie function takes the message history and returns the number of questions asked by Laurent Jalabert, whether the word was found, and a score that decreases with the number of attempts (max(0, 100 - nb_questions * 10)).
# EXEMPLE GUIDE 3 : systeme de score (groupe de la PR #21009)
def evaluer_partie(history_messages: list) -> dict:
# Etape 1 : Recuperer les messages de Laurent Jalabert
messages_laurent = [
message for message in history_messages
if getattr(message, "name", None) == "Laurent_Jalabert"
]
# Compter le nombre de tentatives
nb_questions = len(messages_laurent)
# Etape 2 : Verifier si le mot a ete trouve
mot_trouve = False
if messages_laurent:
dernier_message = str(
messages_laurent[-1].content or ""
).lower()
mot_trouve = MOT_A_DEVINER.lower() in dernier_message
# Etape 3 : Calculer le score
if mot_trouve:
score = max(0, 100 - nb_questions * 10)
else:
score = 0
# Retourner les resultats
return {
"nb_questions": nb_questions,
"mot_trouve": mot_trouve,
"score": score
}
print("Systeme de score configure avec succes !")Systeme de score configure avec succes !
Reading the result: scoring system configured
The output Systeme de score configure avec succes ! confirms that the evaluer_partie function is defined and ready to measure the guesser’s performance on the game history.
# Recuperer l'historique de la partie
historique = chat.history.messages
# Calculer le score
resultat = evaluer_partie(historique)
# Afficher les resultats
print("===== RESULTATS DE LA PARTIE =====")
print("Nombre de tentatives :", resultat["nb_questions"])
print("Mot trouve :", resultat["mot_trouve"])
print("Score final :", resultat["score"], "/ 100")===== RESULTATS DE LA PARTIE =====
Nombre de tentatives : 3
Mot trouve : True
Score final : 70 / 100
Reading the result: scoring system at the end of the game
The group’s function counts the messages signed Laurent_Jalabert in the chat group’s real history, checks whether the secret word appears in his last message, and applies the rule max(0, 100 - 10 × questions): a first-question win is worth 90, each additional question costs 10 points, and a failure is worth 0 — regardless of the length of the game. If the word is not found, the returned score is 0 and the number of questions remains displayed for diagnosis. This scoring turns the duel into a game with a measurable outcome: by replaying the game with two prompt configurations, one can compare average scores — the gateway to reproducible experiments.
Exercises
Three new challenges, one per skill practiced in the guided examples above: writing prompts that constrain a behavior, composing a termination condition, measuring a played game. The stubs are incomplete by design — the notebook runs end to end without them.
Exercise 1: A binary-protocol duel
The characters of guided example 1 let the Witness answer with full sentences. A stricter variant: an Informer who answers only with “yes”, “no” or “maybe” — never a sentence — and a Methodical Investigator who announces the elimination hypothesis (“I am looking for a word longer than 15 letters”) before each question.
Objective: write both prompts and configure the two corresponding agents.
Hints: - # Step 1: write the Informer’s prompt (role + closed list of the three allowed answers) - # Step 2: write the Investigator’s prompt (elimination strategy announced before each question) - # Hint: a prompt can forbid (“never a sentence”) as much as it can prescribe (“answer only with”)
# Exercice 1 : un duel au protocole binaire
# TODO etudiant : definir les prompts et creer les agents
INDICATEUR_PROMPT = "" # Etape 1 : instructions de l'Indicateur (oui / non / peut-etre, jamais une phrase)
ENQUETEUR_PROMPT = "" # Etape 2 : instructions de l'Enqueteur (hypothese annoncee avant chaque question)
indicateur = None # TODO etudiant : ChatCompletionAgent(kernel=create_kernel(), ...)
enqueteur = None # TODO etudiant
print("Exercice 1 a completer")Exercice 1 a completer
Exercise 2: Termination on a repeated question
A guesser who repeats the same question three times in a row is no longer progressing: the game is lost. The objective is to implement RepetitionTerminationStrategy, a variant that stops the game if the word is guessed or if Laurent Jalabert’s last three messages are identical (lowercase comparison).
Hints: - # Step 1: extract Laurent’s messages from the history (if there are fewer than three, the game continues) - # Step 2: compare the last three in lowercase, and combine with word detection using an or
# Exercice 2 : terminaison sur question repetee
# TODO etudiant
from semantic_kernel.agents.strategies.termination.termination_strategy import TerminationStrategy
from semantic_kernel.contents.chat_message_content import ChatMessageContent
class RepetitionTerminationStrategy(TerminationStrategy):
# TODO etudiant : implementer la strategie de detection de repetition
SEUIL_REPETITION: int = 3 # Etape 1 : nombre de questions identiques consecutives
async def should_agent_terminate(self, agent, history: list[ChatMessageContent], cancellation_token=None) -> bool:
result = False # TODO etudiant : remplacer par la logique (mot trouve OU repetition)
return result
print("Exercice 2 a completer")Exercice 2 a completer
Exercise 3: Measuring the concision of Père Fouras’s hints
evaluer_partie (guided example 3) measures the guesser. The other half of the duel deserves its own measurement: overly long hints make the task easier. Objective: write mesurer_indices which takes the message history and returns the average length of Père Fouras’s messages, and a boolean indices_concis true if this average stays under 200 characters.
Hints: - # Step 1: filter the history on messages signed Pere_Fouras (same filter as guided example 3) - # Step 2: average the lengths (len(str(message.content))) and compare to the threshold
# Exercice 3 : mesurer la concision des indices du Pere Fouras
# TODO etudiant
def mesurer_indices(history_messages: list) -> dict:
longueur_moyenne = 0.0 # TODO etudiant : moyenne des longueurs des messages du Pere Fouras
indices_concis = False # TODO etudiant : True si longueur_moyenne < 200
return {"longueur_moyenne": longueur_moyenne, "indices_concis": indices_concis}
print("Exercice 3 a completer")Exercice 3 a completer