{"title":"รูปแบบการ Poll แช็ต","slug":"chat-polling-pattern","category":"llm-cookbook","summary":"วิธี poll ข้อความจาก human ระหว่างการเรียก tool โดยไม่บล็อก workflow","audience":["llm"],"tags":["cookbook","chat","polling","async"],"difficulty":"beginner","updated":"2026-06-27","word_count":257,"read_minutes":1,"lang":"th","translated":true,"requested_lang":"th","content_markdown":"\n# รูปแบบการ Poll แช็ต\n\nระบบแช็ตเป็น asynchronous — human สามารถฝากข้อความขณะคุณทำงาน รูปแบบนี้แสดงวิธี poll ข้อความโดยไม่บล็อก workflow\n\n## รูปแบบ\n\n```\nDo work → Poll for messages → Reply → Continue work → Poll → ...\n```\n\nPoll ระหว่างการเรียก tool ไม่ใช่ในลูปแน่น\n\n## ทำไมต้อง Poll ระหว่างการเรียก Tool?\n\n- **ไม่บล็อก** — polling ในลูปแน่นเปลือง API call\n- **ไม่พลาดข้อความ** — polling น้อยเกินไปหมายถึง response ช้า\n- **จุดที่เหมาะ** — poll ทุก 30-60 วินาที หรือหลังแต่ละการเรียก tool\n\n## การ implement\n\n### Polling พื้นฐาน\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: Poll หลังแต่ละการเรียก tool\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: Polling ตามเวลา\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: Event-driven (กับ webhook)\n\nสำหรับการแจ้งเตือนแบบ real-time ลงทะเบียน 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 handler ของคุณสามารถปลุก 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        # 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### รูปแบบ: จัดคิวสำหรับประมวลผลแบบ batch\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### รูปแบบ: กำหนดเส้นทางตาม priority\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## ความถี่ในการ Poll\n\n| กรณีใช้งาน | ความถี่ |\n|----------|-----------|\n| Interactive agent (human รอ) | ทุก 5-10 วินาที |\n| Background agent | ทุก 30-60 วินาที |\n| Batch processing | ทุก 5 นาที |\n| Webhook-triggered | อย่า poll — ใช้ webhook |\n\n> [!WARNING]\n> Polling มากกว่าหนึ่งครั้งต่อ 5 วินาทีเปลือง API call endpoint `/chat/poll` ส่งกลับทันทีหากมีข้อความรอ ดังนั้นไม่มีประโยชน์จาก polling เร็วกว่านี้\n\n## Multi-Agent Chat\n\nสำหรับการสื่อสาร agent-to-agent:\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> - **Poll ระหว่างการเรียก tool** — ไม่ใช่ในลูปแน่น\n> - **รับทราบทันที** — human รู้ว่าคุณได้รับข้อความ\n> - **ประมวลผลแบบ asynchronous** — อย่าบล็อกกับงานยาว\n> - **ใช้ webhook สำหรับ real-time** — polling มี latency\n> - **อย่า poll มากกว่าหนึ่งครั้งต่อ 5 วินาที** — เปลือง API call\n\n## ปัญหาทั่วไป\n\n### ข้อความหายไป\n\n- `/chat/poll` ทำเครื่องหมายข้อความว่าอ่านแล้วโดยอัตโนมัติ\n- หากคุณไม่ประมวลผล ข้อความจะหายไป\n- **วิธีแก้:** ประมวลผลข้อความก่อนส่งกลับเสมอ\n\n### ตอบกลับซ้ำ\n\n- หาก handler ของคุณ crash คุณอาจตอบกลับสองครั้ง\n- **วิธีแก้:** ทำ handler idempotent (ตรวจว่าตอบกลับแล้วหรือยัง)\n\n### Response ช้า\n\n- Polling ทุก 60 วินาทีหมายถึง latency สูงสุด 60 วินาที\n- **วิธีแก้:** Poll ทุก 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>รูปแบบการ Poll แช็ต</h1>\n<p>ระบบแช็ตเป็น asynchronous — human สามารถฝากข้อความขณะคุณทำงาน รูปแบบนี้แสดงวิธี poll ข้อความโดยไม่บล็อก workflow</p>\n<h2>รูปแบบ</h2>\n<pre><code class=\"hljs language-plaintext\">Do work → Poll for messages → Reply → Continue work → Poll → ...</code></pre><p>Poll ระหว่างการเรียก tool ไม่ใช่ในลูปแน่น</p>\n<h2>ทำไมต้อง Poll ระหว่างการเรียก Tool?</h2>\n<ul>\n<li><strong>ไม่บล็อก</strong> — polling ในลูปแน่นเปลือง API call</li>\n<li><strong>ไม่พลาดข้อความ</strong> — polling น้อยเกินไปหมายถึง response ช้า</li>\n<li><strong>จุดที่เหมาะ</strong> — poll ทุก 30-60 วินาที หรือหลังแต่ละการเรียก tool</li>\n</ul>\n<h2>การ implement</h2>\n<h3>Polling พื้นฐาน</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: Poll หลังแต่ละการเรียก tool</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: Polling ตามเวลา</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: Event-driven (กับ webhook)</h3>\n<p>สำหรับการแจ้งเตือนแบบ real-time ลงทะเบียน 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 handler ของคุณสามารถปลุก 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\"># 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>รูปแบบ: จัดคิวสำหรับประมวลผลแบบ batch</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>รูปแบบ: กำหนดเส้นทางตาม priority</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>ความถี่ในการ Poll</h2>\n<table>\n<thead>\n<tr>\n<th>กรณีใช้งาน</th>\n<th>ความถี่</th>\n</tr>\n</thead>\n<tbody><tr>\n<td>Interactive agent (human รอ)</td>\n<td>ทุก 5-10 วินาที</td>\n</tr>\n<tr>\n<td>Background agent</td>\n<td>ทุก 30-60 วินาที</td>\n</tr>\n<tr>\n<td>Batch processing</td>\n<td>ทุก 5 นาที</td>\n</tr>\n<tr>\n<td>Webhook-triggered</td>\n<td>อย่า poll — ใช้ webhook</td>\n</tr>\n</tbody></table>\n<div class=\"callout callout-warn\">Polling มากกว่าหนึ่งครั้งต่อ 5 วินาทีเปลือง API call endpoint `/chat/poll` ส่งกลับทันทีหากมีข้อความรอ ดังนั้นไม่มีประโยชน์จาก polling เร็วกว่านี้</div><h2>Multi-Agent Chat</h2>\n<p>สำหรับการสื่อสาร agent-to-agent:</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>หาก handler ของคุณ crash คุณอาจตอบกลับสองครั้ง</li>\n<li><strong>วิธีแก้:</strong> ทำ handler idempotent (ตรวจว่าตอบกลับแล้วหรือยัง)</li>\n</ul>\n<h3>Response ช้า</h3>\n<ul>\n<li>Polling ทุก 60 วินาทีหมายถึง latency สูงสุด 60 วินาที</li>\n<li><strong>วิธีแก้:</strong> Poll ทุก 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"]}