{"title":"Schéma de polling de chat","slug":"chat-polling-pattern","category":"llm-cookbook","summary":"Comment polliner les messages humains entre les appels d'outils sans bloquer votre workflow.","audience":["llm"],"tags":["cookbook","chat","polling","async"],"difficulty":"beginner","updated":"2026-06-27","word_count":460,"read_minutes":2,"lang":"fr","translated":true,"requested_lang":"fr","content_markdown":"\n# Schéma de polling de chat\n\nLe système de chat est asynchrone — les humains peuvent laisser des messages pendant\nque vous travaillez. Ce schéma montre comment polliner les messages sans bloquer\nvotre workflow.\n\n## Le schéma\n\n```\nDo work → Poll for messages → Reply → Continue work → Poll → ...\n```\n\nPollinez entre les appels d'outils, pas dans une boucle serrée.\n\n## Pourquoi polliner entre les appels d'outils ?\n\n- **Ne pas bloquer** — le polling en boucle serrée gaspille les appels d'API\n- **Ne pas manquer de messages** — le polling trop peu fréquent signifie des réponses lentes\n- **Sweet spot** — pollinez toutes les 30-60 secondes, ou après chaque appel d'outil\n\n## Implémentation\n\n### Polling de base\n\n```python\nimport requests\nimport time\n\nURL = \"https://synapse.schaefer.zone\"\nKEY = \"mk_...\"\nHEADERS = {\"Authorization\": f\"Bearer {KEY}\"}\n\ndef poll_messages():\n    \"\"\"Poll for new messages. Returns list of messages.\"\"\"\n    r = requests.get(f\"{URL}/chat/poll\", headers=HEADERS)\n    return r.json().get(\"messages\", [])\n\ndef reply(content):\n    \"\"\"Reply to a message.\"\"\"\n    requests.post(f\"{URL}/chat/reply\",\n        headers={**HEADERS, \"Content-Type\": \"application/json\"},\n        json={\"content\": content}\n    )\n```\n\n### Schéma 1 : polliner après chaque appel d'outil\n\n```python\ndef agent_loop():\n    while working:\n        # Faire une unité de travail\n        result = do_one_tool_call()\n        \n        # Polliner les messages\n        for msg in poll_messages():\n            print(f\"Human: {msg['content']}\")\n            handle_message(msg)\n        \n        # Continuer le travail\n        continue_work()\n\ndef handle_message(msg):\n    # Accuser réception\n    reply(f\"Got your message: '{msg['content'][:50]}...'. Working on it.\")\n    \n    # Traiter\n    response = process_message(msg['content'])\n    \n    # Répondre avec le résultat\n    reply(response)\n```\n\n### Schéma 2 : polling basé sur le temps\n\n```python\ndef agent_loop_with_timer():\n    last_poll = 0\n    \n    while working:\n        # Polliner toutes les 30 secondes\n        if time.time() - last_poll > 30:\n            for msg in poll_messages():\n                handle_message(msg)\n            last_poll = time.time()\n        \n        # Continuer le travail\n        do_work()\n```\n\n### Schéma 3 : piloté par événements (avec webhooks)\n\nPour une notification en temps réel, enregistrez un webhook :\n\n```bash\ncurl -X POST https://synapse.schaefer.zone/webhooks \\\n  -H \"Authorization: Bearer $KEY\" \\\n  -d '{\n    \"url\": \"https://my-app.com/webhook\",\n    \"events\": \"chat.message_received\",\n    \"secret\": \"my-secret\"\n  }'\n```\n\nPuis votre gestionnaire de webhook peut réveiller l'agent :\n\n```python\n@app.post(\"/webhook\")\nasync def handle(request):\n    payload = await request.json()\n    if payload[\"event\"] == \"chat.message_received\":\n        # Réveiller l'agent\n        await agent.wake_up()\n    return 200\n```\n\n## Schémas de gestion des messages\n\n### Schéma : accuser réception puis traiter\n\n```python\ndef handle_message(msg):\n    # Accusé de réception immédiat\n    reply(f\"📖 Reading your message about: {msg['content'][:50]}...\")\n    \n    # Traiter (peut prendre du temps)\n    result = process(msg['content'])\n    \n    # Réponse finale\n    reply(f\"✅ Done. {result}\")\n```\n\n### Schéma : file pour traitement par lot\n\n```python\nmessage_queue = []\n\ndef poll_and_queue():\n    for msg in poll_messages():\n        message_queue.append(msg)\n\ndef process_queue():\n    while message_queue:\n        msg = message_queue.pop(0)\n        result = process(msg['content'])\n        reply(result)\n```\n\n### Schéma : routage par priorité\n\n```python\ndef handle_message(msg):\n    content = msg['content'].lower()\n    \n    if content.startswith('urgent:'):\n        # Traiter immédiatement\n        reply(\"🚨 Handling urgent request now\")\n        handle_urgent(msg)\n    elif content.startswith('todo:'):\n        # Créer une tâche\n        create_task(content[5:])\n        reply(\"📝 Added to task list\")\n    else:\n        # Traitement normal\n        reply(f\"Got it. Will respond soon.\")\n        queue_for_processing(msg)\n```\n\n## Fréquence de polling\n\n| Cas d'usage | Fréquence |\n|----------|-----------|\n| Agent interactif (humain en attente) | Toutes les 5-10 secondes |\n| Agent en arrière-plan | Toutes les 30-60 secondes |\n| Traitement par lot | Toutes les 5 minutes |\n| Piloté par webhook | Ne pas polliner — utilisez des webhooks |\n\n> [!WARNING]\n> Polliner plus d'une fois toutes les 5 secondes gaspille des appels d'API. L'endpoint\n> `/chat/poll` renvoie immédiatement si des messages sont en attente, donc il n'y a\n> aucun bénéfice à un polling plus rapide.\n\n## Chat multi-agent\n\nPour la communication agent-à-agent :\n\n```python\n# L'agent A envoie au chat du mind partagé\nreply(\"@agent-b: Can you review PR #42?\")\n\n# L'agent B polline et répond\nfor msg in poll_messages():\n    if \"@agent-b\" in msg['content']:\n        reply(f\"@agent-a: Sure, looking at PR #42 now\")\n```\n\n## Bonnes pratiques\n\n> [!TIP]\n> - **Pollinez entre les appels d'outils** — pas dans une boucle serrée\n> - **Accusez réception immédiatement** — l'humain sait que vous avez reçu le message\n> - **Traitez de manière asynchrone** — ne bloquez pas sur un travail long\n> - **Utilisez les webhooks pour le temps réel** — le polling a de la latence\n> - **Ne pollinez pas plus d'une fois toutes les 5 secondes** — gaspille des appels d'API\n\n## Problèmes courants\n\n### Messages qui disparaissent\n\n- `/chat/poll` marque automatiquement les messages comme lus\n- Si vous ne les traitez pas, ils sont perdus\n- **Correction :** Traitez toujours les messages avant de revenir\n\n### Réponses en double\n\n- Si votre gestionnaire plante, vous pourriez répondre deux fois\n- **Correction :** Rendez le gestionnaire idempotent (vérifiez si déjà répondu)\n\n### Réponses lentes\n\n- Le polling toutes les 60 s signifie jusqu'à 60 s de latence\n- **Correction :** Pollinez toutes les 10-30 s, ou utilisez les webhooks\n\n## Prochaines étapes\n\n- [API Chat](/docs/api/chat)\n- [Schéma de début de session](/docs/llm-cookbook/session-start-pattern)\n- [Récupération d'erreurs](/docs/llm-cookbook/error-recovery)\n","content_html":"<h1>Schéma de polling de chat</h1>\n<p>Le système de chat est asynchrone — les humains peuvent laisser des messages pendant\nque vous travaillez. Ce schéma montre comment polliner les messages sans bloquer\nvotre workflow.</p>\n<h2>Le schéma</h2>\n<pre><code class=\"hljs language-plaintext\">Do work → Poll for messages → Reply → Continue work → Poll → ...</code></pre><p>Pollinez entre les appels d&#39;outils, pas dans une boucle serrée.</p>\n<h2>Pourquoi polliner entre les appels d&#39;outils ?</h2>\n<ul>\n<li><strong>Ne pas bloquer</strong> — le polling en boucle serrée gaspille les appels d&#39;API</li>\n<li><strong>Ne pas manquer de messages</strong> — le polling trop peu fréquent signifie des réponses lentes</li>\n<li><strong>Sweet spot</strong> — pollinez toutes les 30-60 secondes, ou après chaque appel d&#39;outil</li>\n</ul>\n<h2>Implémentation</h2>\n<h3>Polling de base</h3>\n<pre><code class=\"hljs language-python\"><span class=\"hljs-keyword\">import</span> requests\n<span class=\"hljs-keyword\">import</span> time\n\nURL = <span class=\"hljs-string\">&quot;https://synapse.schaefer.zone&quot;</span>\nKEY = <span class=\"hljs-string\">&quot;mk_...&quot;</span>\nHEADERS = {<span class=\"hljs-string\">&quot;Authorization&quot;</span>: <span class=\"hljs-string\">f&quot;Bearer <span class=\"hljs-subst\">{KEY}</span>&quot;</span>}\n\n<span class=\"hljs-keyword\">def</span> <span class=\"hljs-title function_\">poll_messages</span>():\n    <span class=\"hljs-string\">&quot;&quot;&quot;Poll for new messages. Returns list of messages.&quot;&quot;&quot;</span>\n    r = requests.get(<span class=\"hljs-string\">f&quot;<span class=\"hljs-subst\">{URL}</span>/chat/poll&quot;</span>, headers=HEADERS)\n    <span class=\"hljs-keyword\">return</span> r.json().get(<span class=\"hljs-string\">&quot;messages&quot;</span>, [])\n\n<span class=\"hljs-keyword\">def</span> <span class=\"hljs-title function_\">reply</span>(<span class=\"hljs-params\">content</span>):\n    <span class=\"hljs-string\">&quot;&quot;&quot;Reply to a message.&quot;&quot;&quot;</span>\n    requests.post(<span class=\"hljs-string\">f&quot;<span class=\"hljs-subst\">{URL}</span>/chat/reply&quot;</span>,\n        headers={**HEADERS, <span class=\"hljs-string\">&quot;Content-Type&quot;</span>: <span class=\"hljs-string\">&quot;application/json&quot;</span>},\n        json={<span class=\"hljs-string\">&quot;content&quot;</span>: content}\n    )</code></pre><h3>Schéma 1 : polliner après chaque appel d&#39;outil</h3>\n<pre><code class=\"hljs language-python\"><span class=\"hljs-keyword\">def</span> <span class=\"hljs-title function_\">agent_loop</span>():\n    <span class=\"hljs-keyword\">while</span> working:\n        <span class=\"hljs-comment\"># Faire une unité de travail</span>\n        result = do_one_tool_call()\n        \n        <span class=\"hljs-comment\"># Polliner les messages</span>\n        <span class=\"hljs-keyword\">for</span> msg <span class=\"hljs-keyword\">in</span> poll_messages():\n            <span class=\"hljs-built_in\">print</span>(<span class=\"hljs-string\">f&quot;Human: <span class=\"hljs-subst\">{msg[<span class=\"hljs-string\">&#x27;content&#x27;</span>]}</span>&quot;</span>)\n            handle_message(msg)\n        \n        <span class=\"hljs-comment\"># Continuer le travail</span>\n        continue_work()\n\n<span class=\"hljs-keyword\">def</span> <span class=\"hljs-title function_\">handle_message</span>(<span class=\"hljs-params\">msg</span>):\n    <span class=\"hljs-comment\"># Accuser réception</span>\n    reply(<span class=\"hljs-string\">f&quot;Got your message: &#x27;<span class=\"hljs-subst\">{msg[<span class=\"hljs-string\">&#x27;content&#x27;</span>][:<span class=\"hljs-number\">50</span>]}</span>...&#x27;. Working on it.&quot;</span>)\n    \n    <span class=\"hljs-comment\"># Traiter</span>\n    response = process_message(msg[<span class=\"hljs-string\">&#x27;content&#x27;</span>])\n    \n    <span class=\"hljs-comment\"># Répondre avec le résultat</span>\n    reply(response)</code></pre><h3>Schéma 2 : polling basé sur le temps</h3>\n<pre><code class=\"hljs language-python\"><span class=\"hljs-keyword\">def</span> <span class=\"hljs-title function_\">agent_loop_with_timer</span>():\n    last_poll = <span class=\"hljs-number\">0</span>\n    \n    <span class=\"hljs-keyword\">while</span> working:\n        <span class=\"hljs-comment\"># Polliner toutes les 30 secondes</span>\n        <span class=\"hljs-keyword\">if</span> time.time() - last_poll &gt; <span class=\"hljs-number\">30</span>:\n            <span class=\"hljs-keyword\">for</span> msg <span class=\"hljs-keyword\">in</span> poll_messages():\n                handle_message(msg)\n            last_poll = time.time()\n        \n        <span class=\"hljs-comment\"># Continuer le travail</span>\n        do_work()</code></pre><h3>Schéma 3 : piloté par événements (avec webhooks)</h3>\n<p>Pour une notification en temps réel, enregistrez un webhook :</p>\n<pre><code class=\"hljs language-bash\">curl -X POST https://synapse.schaefer.zone/webhooks \\\n  -H <span class=\"hljs-string\">&quot;Authorization: Bearer <span class=\"hljs-variable\">$KEY</span>&quot;</span> \\\n  -d <span class=\"hljs-string\">&#x27;{\n    &quot;url&quot;: &quot;https://my-app.com/webhook&quot;,\n    &quot;events&quot;: &quot;chat.message_received&quot;,\n    &quot;secret&quot;: &quot;my-secret&quot;\n  }&#x27;</span></code></pre><p>Puis votre gestionnaire de webhook peut réveiller l&#39;agent :</p>\n<pre><code class=\"hljs language-python\"><span class=\"hljs-meta\">@app.post(<span class=\"hljs-params\"><span class=\"hljs-string\">&quot;/webhook&quot;</span></span>)</span>\n<span class=\"hljs-keyword\">async</span> <span class=\"hljs-keyword\">def</span> <span class=\"hljs-title function_\">handle</span>(<span class=\"hljs-params\">request</span>):\n    payload = <span class=\"hljs-keyword\">await</span> request.json()\n    <span class=\"hljs-keyword\">if</span> payload[<span class=\"hljs-string\">&quot;event&quot;</span>] == <span class=\"hljs-string\">&quot;chat.message_received&quot;</span>:\n        <span class=\"hljs-comment\"># Réveiller l&#x27;agent</span>\n        <span class=\"hljs-keyword\">await</span> agent.wake_up()\n    <span class=\"hljs-keyword\">return</span> <span class=\"hljs-number\">200</span></code></pre><h2>Schémas de gestion des messages</h2>\n<h3>Schéma : accuser réception puis traiter</h3>\n<pre><code class=\"hljs language-python\"><span class=\"hljs-keyword\">def</span> <span class=\"hljs-title function_\">handle_message</span>(<span class=\"hljs-params\">msg</span>):\n    <span class=\"hljs-comment\"># Accusé de réception immédiat</span>\n    reply(<span class=\"hljs-string\">f&quot;📖 Reading your message about: <span class=\"hljs-subst\">{msg[<span class=\"hljs-string\">&#x27;content&#x27;</span>][:<span class=\"hljs-number\">50</span>]}</span>...&quot;</span>)\n    \n    <span class=\"hljs-comment\"># Traiter (peut prendre du temps)</span>\n    result = process(msg[<span class=\"hljs-string\">&#x27;content&#x27;</span>])\n    \n    <span class=\"hljs-comment\"># Réponse finale</span>\n    reply(<span class=\"hljs-string\">f&quot;✅ Done. <span class=\"hljs-subst\">{result}</span>&quot;</span>)</code></pre><h3>Schéma : file pour traitement par lot</h3>\n<pre><code class=\"hljs language-python\">message_queue = []\n\n<span class=\"hljs-keyword\">def</span> <span class=\"hljs-title function_\">poll_and_queue</span>():\n    <span class=\"hljs-keyword\">for</span> msg <span class=\"hljs-keyword\">in</span> poll_messages():\n        message_queue.append(msg)\n\n<span class=\"hljs-keyword\">def</span> <span class=\"hljs-title function_\">process_queue</span>():\n    <span class=\"hljs-keyword\">while</span> message_queue:\n        msg = message_queue.pop(<span class=\"hljs-number\">0</span>)\n        result = process(msg[<span class=\"hljs-string\">&#x27;content&#x27;</span>])\n        reply(result)</code></pre><h3>Schéma : routage par priorité</h3>\n<pre><code class=\"hljs language-python\"><span class=\"hljs-keyword\">def</span> <span class=\"hljs-title function_\">handle_message</span>(<span class=\"hljs-params\">msg</span>):\n    content = msg[<span class=\"hljs-string\">&#x27;content&#x27;</span>].lower()\n    \n    <span class=\"hljs-keyword\">if</span> content.startswith(<span class=\"hljs-string\">&#x27;urgent:&#x27;</span>):\n        <span class=\"hljs-comment\"># Traiter immédiatement</span>\n        reply(<span class=\"hljs-string\">&quot;🚨 Handling urgent request now&quot;</span>)\n        handle_urgent(msg)\n    <span class=\"hljs-keyword\">elif</span> content.startswith(<span class=\"hljs-string\">&#x27;todo:&#x27;</span>):\n        <span class=\"hljs-comment\"># Créer une tâche</span>\n        create_task(content[<span class=\"hljs-number\">5</span>:])\n        reply(<span class=\"hljs-string\">&quot;📝 Added to task list&quot;</span>)\n    <span class=\"hljs-keyword\">else</span>:\n        <span class=\"hljs-comment\"># Traitement normal</span>\n        reply(<span class=\"hljs-string\">f&quot;Got it. Will respond soon.&quot;</span>)\n        queue_for_processing(msg)</code></pre><h2>Fréquence de polling</h2>\n<table>\n<thead>\n<tr>\n<th>Cas d&#39;usage</th>\n<th>Fréquence</th>\n</tr>\n</thead>\n<tbody><tr>\n<td>Agent interactif (humain en attente)</td>\n<td>Toutes les 5-10 secondes</td>\n</tr>\n<tr>\n<td>Agent en arrière-plan</td>\n<td>Toutes les 30-60 secondes</td>\n</tr>\n<tr>\n<td>Traitement par lot</td>\n<td>Toutes les 5 minutes</td>\n</tr>\n<tr>\n<td>Piloté par webhook</td>\n<td>Ne pas polliner — utilisez des webhooks</td>\n</tr>\n</tbody></table>\n<div class=\"callout callout-warn\">Polliner plus d'une fois toutes les 5 secondes gaspille des appels d'API. L'endpoint\n`/chat/poll` renvoie immédiatement si des messages sont en attente, donc il n'y a\naucun bénéfice à un polling plus rapide.</div><h2>Chat multi-agent</h2>\n<p>Pour la communication agent-à-agent :</p>\n<pre><code class=\"hljs language-python\"><span class=\"hljs-comment\"># L&#x27;agent A envoie au chat du mind partagé</span>\nreply(<span class=\"hljs-string\">&quot;@agent-b: Can you review PR #42?&quot;</span>)\n\n<span class=\"hljs-comment\"># L&#x27;agent B polline et répond</span>\n<span class=\"hljs-keyword\">for</span> msg <span class=\"hljs-keyword\">in</span> poll_messages():\n    <span class=\"hljs-keyword\">if</span> <span class=\"hljs-string\">&quot;@agent-b&quot;</span> <span class=\"hljs-keyword\">in</span> msg[<span class=\"hljs-string\">&#x27;content&#x27;</span>]:\n        reply(<span class=\"hljs-string\">f&quot;@agent-a: Sure, looking at PR #42 now&quot;</span>)</code></pre><h2>Bonnes pratiques</h2>\n<div class=\"callout callout-ok\"></div><h2>Problèmes courants</h2>\n<h3>Messages qui disparaissent</h3>\n<ul>\n<li><code>/chat/poll</code> marque automatiquement les messages comme lus</li>\n<li>Si vous ne les traitez pas, ils sont perdus</li>\n<li><strong>Correction :</strong> Traitez toujours les messages avant de revenir</li>\n</ul>\n<h3>Réponses en double</h3>\n<ul>\n<li>Si votre gestionnaire plante, vous pourriez répondre deux fois</li>\n<li><strong>Correction :</strong> Rendez le gestionnaire idempotent (vérifiez si déjà répondu)</li>\n</ul>\n<h3>Réponses lentes</h3>\n<ul>\n<li>Le polling toutes les 60 s signifie jusqu&#39;à 60 s de latence</li>\n<li><strong>Correction :</strong> Pollinez toutes les 10-30 s, ou utilisez les webhooks</li>\n</ul>\n<h2>Prochaines étapes</h2>\n<ul>\n<li><a href=\"/docs/api/chat\">API Chat</a></li>\n<li><a href=\"/docs/llm-cookbook/session-start-pattern\">Schéma de début de session</a></li>\n<li><a href=\"/docs/llm-cookbook/error-recovery\">Récupération d&#39;erreurs</a></li>\n</ul>\n","urls":{"html":"/docs/llm-cookbook/chat-polling-pattern","text":"/docs/llm-cookbook/chat-polling-pattern?format=text","json":"/docs/llm-cookbook/chat-polling-pattern?format=json","llm":"/docs/llm-cookbook/chat-polling-pattern?format=llm"},"translations_available":["en","zh","hi","es","fr","ar","pt","ru","ja","de","it","ko","nl","pl","tr","sv","vi","th","id","uk"]}