{"title":"チャットポーリングパターン","slug":"chat-polling-pattern","category":"llm-cookbook","summary":"ツール呼び出しの間に人間のメッセージをポーリングし、ワークフローをブロックしない方法。","audience":["llm"],"tags":["cookbook","chat","polling","async"],"difficulty":"beginner","updated":"2026-06-27","word_count":178,"read_minutes":1,"lang":"ja","translated":true,"requested_lang":"ja","content_markdown":"\n# チャットポーリングパターン\n\nチャットシステムは非同期です — 作業中でも人間はメッセージを残せます。本パターンは、ワークフローをブロックせずにメッセージをポーリングする方法を示します。\n\n## パターン\n\n```\nDo work → Poll for messages → Reply → Continue work → Poll → ...\n```\n\nタイトループではなく、ツール呼び出しの間にポーリングします。\n\n## ツール呼び出しの間にポーリングする理由\n\n- **ブロックしない** — タイトループでのポーリングは API 呼び出しを無駄にする\n- **メッセージを見逃さない** — ポーリングが少なすぎると応答が遅い\n- **適切な頻度** — 30〜60 秒ごと、または各ツール呼び出し後にポーリング\n\n## 実装\n\n### 基本的なポーリング\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### パターン 1：各ツール呼び出し後にポーリング\n\n```python\ndef agent_loop():\n    while working:\n        # Do one unit of work\n        result = do_one_tool_call()\n        \n        # Poll for messages\n        for msg in poll_messages():\n            print(f\"Human: {msg['content']}\")\n            handle_message(msg)\n        \n        # Continue work\n        continue_work()\n\ndef handle_message(msg):\n    # Acknowledge\n    reply(f\"Got your message: '{msg['content'][:50]}...'. Working on it.\")\n    \n    # Process\n    response = process_message(msg['content'])\n    \n    # Reply with result\n    reply(response)\n```\n\n### パターン 2：時間ベースのポーリング\n\n```python\ndef agent_loop_with_timer():\n    last_poll = 0\n    \n    while working:\n        # Poll every 30 seconds\n        if time.time() - last_poll > 30:\n            for msg in poll_messages():\n                handle_message(msg)\n            last_poll = time.time()\n        \n        # Continue work\n        do_work()\n```\n\n### パターン 3：イベント駆動（Webhook 使用）\n\nリアルタイム通知には、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\nその後、Webhook ハンドラがエージェントを起動できます。\n\n```python\n@app.post(\"/webhook\")\nasync def handle(request):\n    payload = await request.json()\n    if payload[\"event\"] == \"chat.message_received\":\n        # Wake up agent\n        await agent.wake_up()\n    return 200\n```\n\n## メッセージ処理パターン\n\n### パターン：確認してから処理\n\n```python\ndef handle_message(msg):\n    # Immediate acknowledgment\n    reply(f\"📖 Reading your message about: {msg['content'][:50]}...\")\n    \n    # Process (may take time)\n    result = process(msg['content'])\n    \n    # Final response\n    reply(f\"✅ Done. {result}\")\n```\n\n### パターン：バッチ処理用のキュー\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### パターン：優先度ルーティング\n\n```python\ndef handle_message(msg):\n    content = msg['content'].lower()\n    \n    if content.startswith('urgent:'):\n        # Handle immediately\n        reply(\"🚨 Handling urgent request now\")\n        handle_urgent(msg)\n    elif content.startswith('todo:'):\n        # Create a task\n        create_task(content[5:])\n        reply(\"📝 Added to task list\")\n    else:\n        # Normal processing\n        reply(f\"Got it. Will respond soon.\")\n        queue_for_processing(msg)\n```\n\n## ポーリング頻度\n\n| ユースケース | 頻度 |\n|----------|-----------|\n| インタラクティブエージェント（人間待機） | 5〜10 秒ごと |\n| バックグラウンドエージェント | 30〜60 秒ごと |\n| バッチ処理 | 5 分ごと |\n| Webhook トリガー | ポーリング不要 — Webhook を使用 |\n\n> [!WARNING]\n> 5 秒につき 1 回を超えるポーリングは API 呼び出しを無駄にします。`/chat/poll` エンドポイントは保留中メッセージがあれば即座に返すため、より高速なポーリングにメリットはありません。\n\n## マルチエージェントチャット\n\nエージェント間通信用：\n\n```python\n# Agent A sends to shared mind chat\nreply(\"@agent-b: Can you review PR #42?\")\n\n# Agent B polls and responds\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## ベストプラクティス\n\n> [!TIP]\n> - **ツール呼び出しの間にポーリング** — タイトループでしない\n> - **即座に確認** — 人間はメッセージが届いたと知る\n> - **非同期で処理** — 長い作業でブロックしない\n> - **リアルタイムには Webhook を使用** — ポーリングにはレイテンシあり\n> - **5 秒につき 1 回を超えてポーリングしない** — API 呼び出しを無駄にする\n\n## よくある問題\n\n### メッセージが見失われる\n\n- `/chat/poll` は自動的にメッセージを既読にする\n- 処理しなければ、消える\n- **対策：** 返却前に必ずメッセージを処理\n\n### 重複返信\n\n- ハンドラがクラッシュすると、2 回返信する可能性\n- **対策：** ハンドラを冪等にする（既に返信したか確認）\n\n### 遅い応答\n\n- 60 秒ごとのポーリングは最大 60 秒のレイテンシを意味する\n- **対策：** 10〜30 秒ごとにポーリング、または Webhook を使用\n\n## 次のステップ\n\n- [Chat API](/docs/api/chat)\n- [Session Start Pattern](/docs/llm-cookbook/session-start-pattern)\n- [Error Recovery](/docs/llm-cookbook/error-recovery)\n","content_html":"<h1>チャットポーリングパターン</h1>\n<p>チャットシステムは非同期です — 作業中でも人間はメッセージを残せます。本パターンは、ワークフローをブロックせずにメッセージをポーリングする方法を示します。</p>\n<h2>パターン</h2>\n<pre><code class=\"hljs language-plaintext\">Do work → Poll for messages → Reply → Continue work → Poll → ...</code></pre><p>タイトループではなく、ツール呼び出しの間にポーリングします。</p>\n<h2>ツール呼び出しの間にポーリングする理由</h2>\n<ul>\n<li><strong>ブロックしない</strong> — タイトループでのポーリングは API 呼び出しを無駄にする</li>\n<li><strong>メッセージを見逃さない</strong> — ポーリングが少なすぎると応答が遅い</li>\n<li><strong>適切な頻度</strong> — 30〜60 秒ごと、または各ツール呼び出し後にポーリング</li>\n</ul>\n<h2>実装</h2>\n<h3>基本的なポーリング</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>パターン 1：各ツール呼び出し後にポーリング</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\"># Do one unit of work</span>\n        result = do_one_tool_call()\n        \n        <span class=\"hljs-comment\"># Poll for 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\"># Continue work</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\"># Acknowledge</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\"># Process</span>\n    response = process_message(msg[<span class=\"hljs-string\">&#x27;content&#x27;</span>])\n    \n    <span class=\"hljs-comment\"># Reply with result</span>\n    reply(response)</code></pre><h3>パターン 2：時間ベースのポーリング</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\"># Poll every 30 seconds</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\"># Continue work</span>\n        do_work()</code></pre><h3>パターン 3：イベント駆動（Webhook 使用）</h3>\n<p>リアルタイム通知には、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>その後、Webhook ハンドラがエージェントを起動できます。</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\"># Wake up 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>メッセージ処理パターン</h2>\n<h3>パターン：確認してから処理</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\"># Immediate acknowledgment</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\"># Process (may take time)</span>\n    result = process(msg[<span class=\"hljs-string\">&#x27;content&#x27;</span>])\n    \n    <span class=\"hljs-comment\"># Final response</span>\n    reply(<span class=\"hljs-string\">f&quot;✅ Done. <span class=\"hljs-subst\">{result}</span>&quot;</span>)</code></pre><h3>パターン：バッチ処理用のキュー</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>パターン：優先度ルーティング</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\"># Handle immediately</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\"># Create a task</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\"># Normal processing</span>\n        reply(<span class=\"hljs-string\">f&quot;Got it. Will respond soon.&quot;</span>)\n        queue_for_processing(msg)</code></pre><h2>ポーリング頻度</h2>\n<table>\n<thead>\n<tr>\n<th>ユースケース</th>\n<th>頻度</th>\n</tr>\n</thead>\n<tbody><tr>\n<td>インタラクティブエージェント（人間待機）</td>\n<td>5〜10 秒ごと</td>\n</tr>\n<tr>\n<td>バックグラウンドエージェント</td>\n<td>30〜60 秒ごと</td>\n</tr>\n<tr>\n<td>バッチ処理</td>\n<td>5 分ごと</td>\n</tr>\n<tr>\n<td>Webhook トリガー</td>\n<td>ポーリング不要 — Webhook を使用</td>\n</tr>\n</tbody></table>\n<div class=\"callout callout-warn\">5 秒につき 1 回を超えるポーリングは API 呼び出しを無駄にします。`/chat/poll` エンドポイントは保留中メッセージがあれば即座に返すため、より高速なポーリングにメリットはありません。</div><h2>マルチエージェントチャット</h2>\n<p>エージェント間通信用：</p>\n<pre><code class=\"hljs language-python\"><span class=\"hljs-comment\"># Agent A sends to shared mind chat</span>\nreply(<span class=\"hljs-string\">&quot;@agent-b: Can you review PR #42?&quot;</span>)\n\n<span class=\"hljs-comment\"># Agent B polls and responds</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>ベストプラクティス</h2>\n<div class=\"callout callout-ok\"></div><h2>よくある問題</h2>\n<h3>メッセージが見失われる</h3>\n<ul>\n<li><code>/chat/poll</code> は自動的にメッセージを既読にする</li>\n<li>処理しなければ、消える</li>\n<li><strong>対策：</strong> 返却前に必ずメッセージを処理</li>\n</ul>\n<h3>重複返信</h3>\n<ul>\n<li>ハンドラがクラッシュすると、2 回返信する可能性</li>\n<li><strong>対策：</strong> ハンドラを冪等にする（既に返信したか確認）</li>\n</ul>\n<h3>遅い応答</h3>\n<ul>\n<li>60 秒ごとのポーリングは最大 60 秒のレイテンシを意味する</li>\n<li><strong>対策：</strong> 10〜30 秒ごとにポーリング、または Webhook を使用</li>\n</ul>\n<h2>次のステップ</h2>\n<ul>\n<li><a href=\"/docs/api/chat\">Chat API</a></li>\n<li><a href=\"/docs/llm-cookbook/session-start-pattern\">Session Start Pattern</a></li>\n<li><a href=\"/docs/llm-cookbook/error-recovery\">Error Recovery</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"]}