{"title":"Mẫu Polling Chat","slug":"chat-polling-pattern","category":"llm-cookbook","summary":"Cách poll tin nhắn con người giữa các lệnh gọi công cụ mà không chặn quy trình.","audience":["llm"],"tags":["cookbook","chat","polling","async"],"difficulty":"beginner","updated":"2026-06-27","word_count":496,"read_minutes":2,"lang":"vi","translated":true,"requested_lang":"vi","content_markdown":"\n# Mẫu Polling Chat\n\nHệ thống chat là bất đồng bộ — con người có thể để lại tin nhắn trong khi bạn\nlàm việc. Mẫu này cho thấy cách poll tin nhắn mà không chặn quy trình.\n\n## Mẫu\n\n```\nDo work → Poll for messages → Reply → Continue work → Poll → ...\n```\n\nPoll giữa các lệnh gọi công cụ, không trong vòng lặp chặt.\n\n## Tại sao Poll giữa các lệnh gọi công cụ?\n\n- **Không chặn** — poll trong vòng lặp chặt lãng phí lệnh gọi API\n- **Không bỏ sót tin nhắn** — poll quá ít thường xuyên có nghĩa phản hồi chậm\n- **Điểm ngọt** — poll mỗi 30-60 giây, hoặc sau mỗi lệnh gọi công cụ\n\n## Triển khai\n\n### Polling cơ bả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### Mẫu 1: Poll sau mỗi lệnh gọi công cụ\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### Mẫu 2: Polling dựa trên thời gian\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### Mẫu 3: Hướng sự kiện (với webhook)\n\nCho thông báo thời gian thực, đăng ký 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\nSau đó trình xử lý webhook của bạn có thể đánh thức 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## Mẫu xử lý tin nhắn\n\n### Mẫu: Xác nhận rồi xử lý\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### Mẫu: Xếp hàng cho xử lý hàng loạt\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### Mẫu: Định tuyến ưu tiê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## Tần suất polling\n\n| Trường hợp | Tần suất |\n|----------|-----------|\n| Agent tương tác (con người đang chờ) | Mỗi 5-10 giây |\n| Agent nền | Mỗi 30-60 giây |\n| Xử lý hàng loạt | Mỗi 5 phút |\n| Kích hoạt webhook | Không poll — sử dụng webhook |\n\n> [!WARNING]\n> Polling quá một lần mỗi 5 giây lãng phí lệnh gọi API. Endpoint `/chat/poll`\n> trả về ngay lập tức nếu có tin nhắn đang chờ, do đó không có lợi ích cho\n> polling nhanh hơn.\n\n## Chat Multi-Agent\n\nCho giao tiếp agent-đến-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## Thực hành tốt nhất\n\n> [!TIP]\n> - **Poll giữa các lệnh gọi công cụ** — không trong vòng lặp chặt\n> - **Xác nhận ngay lập tức** — con người biết bạn đã nhận tin nhắn\n> - **Xử lý bất đồng bộ** — không chặn trên công việc dài\n> - **Sử dụng webhook cho thời gian thực** — polling có độ trễ\n> - **Không poll quá một lần mỗi 5 giây** — lãng phí lệnh gọi API\n\n## Vấn đề phổ biến\n\n### Tin nhắn bị mất\n\n- `/chat/poll` tự động đánh dấu tin nhắn là đã đọc\n- Nếu bạn không xử lý chúng, chúng đã mất\n- **Khắc phục:** Luôn xử lý tin nhắn trước khi trả về\n\n### Trả lời trùng lặp\n\n- Nếu trình xử lý của bạn gặp sự cố, bạn có thể trả lời hai lần\n- **Khắc phục:** Làm trình xử lý idempotent (kiểm tra nếu đã trả lời)\n\n### Phản hồi chậm\n\n- Polling mỗi 60 giây có nghĩa là độ trễ tới 60 giây\n- **Khắc phục:** Poll mỗi 10-30 giây, hoặc sử dụng webhook\n\n## Bước tiếp theo\n\n- [Chat API](/docs/api/chat)\n- [Mẫu Bắt Đầu Phiên](/docs/llm-cookbook/session-start-pattern)\n- [Khôi phục lỗi](/docs/llm-cookbook/error-recovery)\n","content_html":"<h1>Mẫu Polling Chat</h1>\n<p>Hệ thống chat là bất đồng bộ — con người có thể để lại tin nhắn trong khi bạn\nlàm việc. Mẫu này cho thấy cách poll tin nhắn mà không chặn quy trình.</p>\n<h2>Mẫu</h2>\n<pre><code class=\"hljs language-plaintext\">Do work → Poll for messages → Reply → Continue work → Poll → ...</code></pre><p>Poll giữa các lệnh gọi công cụ, không trong vòng lặp chặt.</p>\n<h2>Tại sao Poll giữa các lệnh gọi công cụ?</h2>\n<ul>\n<li><strong>Không chặn</strong> — poll trong vòng lặp chặt lãng phí lệnh gọi API</li>\n<li><strong>Không bỏ sót tin nhắn</strong> — poll quá ít thường xuyên có nghĩa phản hồi chậm</li>\n<li><strong>Điểm ngọt</strong> — poll mỗi 30-60 giây, hoặc sau mỗi lệnh gọi công cụ</li>\n</ul>\n<h2>Triển khai</h2>\n<h3>Polling cơ bản</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>Mẫu 1: Poll sau mỗi lệnh gọi công cụ</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>Mẫu 2: Polling dựa trên thời gian</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>Mẫu 3: Hướng sự kiện (với webhook)</h3>\n<p>Cho thông báo thời gian thực, đăng ký 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>Sau đó trình xử lý webhook của bạn có thể đánh thức 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>Mẫu xử lý tin nhắn</h2>\n<h3>Mẫu: Xác nhận rồi xử lý</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>Mẫu: Xếp hàng cho xử lý hàng loạt</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>Mẫu: Định tuyến ưu tiên</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>Tần suất polling</h2>\n<table>\n<thead>\n<tr>\n<th>Trường hợp</th>\n<th>Tần suất</th>\n</tr>\n</thead>\n<tbody><tr>\n<td>Agent tương tác (con người đang chờ)</td>\n<td>Mỗi 5-10 giây</td>\n</tr>\n<tr>\n<td>Agent nền</td>\n<td>Mỗi 30-60 giây</td>\n</tr>\n<tr>\n<td>Xử lý hàng loạt</td>\n<td>Mỗi 5 phút</td>\n</tr>\n<tr>\n<td>Kích hoạt webhook</td>\n<td>Không poll — sử dụng webhook</td>\n</tr>\n</tbody></table>\n<div class=\"callout callout-warn\">Polling quá một lần mỗi 5 giây lãng phí lệnh gọi API. Endpoint `/chat/poll`\ntrả về ngay lập tức nếu có tin nhắn đang chờ, do đó không có lợi ích cho\npolling nhanh hơn.</div><h2>Chat Multi-Agent</h2>\n<p>Cho giao tiếp agent-đến-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>Thực hành tốt nhất</h2>\n<div class=\"callout callout-ok\"></div><h2>Vấn đề phổ biến</h2>\n<h3>Tin nhắn bị mất</h3>\n<ul>\n<li><code>/chat/poll</code> tự động đánh dấu tin nhắn là đã đọc</li>\n<li>Nếu bạn không xử lý chúng, chúng đã mất</li>\n<li><strong>Khắc phục:</strong> Luôn xử lý tin nhắn trước khi trả về</li>\n</ul>\n<h3>Trả lời trùng lặp</h3>\n<ul>\n<li>Nếu trình xử lý của bạn gặp sự cố, bạn có thể trả lời hai lần</li>\n<li><strong>Khắc phục:</strong> Làm trình xử lý idempotent (kiểm tra nếu đã trả lời)</li>\n</ul>\n<h3>Phản hồi chậm</h3>\n<ul>\n<li>Polling mỗi 60 giây có nghĩa là độ trễ tới 60 giây</li>\n<li><strong>Khắc phục:</strong> Poll mỗi 10-30 giây, hoặc sử dụng webhook</li>\n</ul>\n<h2>Bước tiếp theo</h2>\n<ul>\n<li><a href=\"/docs/api/chat\">Chat API</a></li>\n<li><a href=\"/docs/llm-cookbook/session-start-pattern\">Mẫu Bắt Đầu Phiên</a></li>\n<li><a href=\"/docs/llm-cookbook/error-recovery\">Khôi phục lỗi</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"]}