# Mẫu Polling Chat Hệ thống chat là bất đồng bộ — con người có thể để lại tin nhắn trong khi bạn làm việc. Mẫu này cho thấy cách poll tin nhắn mà không chặn quy trình. ## Mẫu ``` Do work → Poll for messages → Reply → Continue work → Poll → ... ``` Poll giữa các lệnh gọi công cụ, không trong vòng lặp chặt. ## Tại sao Poll giữa các lệnh gọi công cụ? - **Không chặn** — poll trong vòng lặp chặt lãng phí lệnh gọi API - **Không bỏ sót tin nhắn** — poll quá ít thường xuyên có nghĩa phản hồi chậm - **Điểm ngọt** — poll mỗi 30-60 giây, hoặc sau mỗi lệnh gọi công cụ ## Triển khai ### Polling cơ bản ```python import requests import time URL = "https://synapse.schaefer.zone" KEY = "mk_..." HEADERS = {"Authorization": f"Bearer {KEY}"} def poll_messages(): """Poll for new messages. Returns list of messages.""" r = requests.get(f"{URL}/chat/poll", headers=HEADERS) return r.json().get("messages", []) def reply(content): """Reply to a message.""" requests.post(f"{URL}/chat/reply", headers={**HEADERS, "Content-Type": "application/json"}, json={"content": content} ) ``` ### Mẫu 1: Poll sau mỗi lệnh gọi công cụ ```python def agent_loop(): while working: # Do one unit of work result = do_one_tool_call() # Poll for messages for msg in poll_messages(): print(f"Human: {msg['content']}") handle_message(msg) # Continue work continue_work() def handle_message(msg): # Acknowledge reply(f"Got your message: '{msg['content'][:50]}...'. Working on it.") # Process response = process_message(msg['content']) # Reply with result reply(response) ``` ### Mẫu 2: Polling dựa trên thời gian ```python def agent_loop_with_timer(): last_poll = 0 while working: # Poll every 30 seconds if time.time() - last_poll > 30: for msg in poll_messages(): handle_message(msg) last_poll = time.time() # Continue work do_work() ``` ### Mẫu 3: Hướng sự kiện (với webhook) Cho thông báo thời gian thực, đăng ký webhook: ```bash curl -X POST https://synapse.schaefer.zone/webhooks \ -H "Authorization: Bearer $KEY" \ -d '{ "url": "https://my-app.com/webhook", "events": "chat.message_received", "secret": "my-secret" }' ``` Sau đó trình xử lý webhook của bạn có thể đánh thức agent: ```python @app.post("/webhook") async def handle(request): payload = await request.json() if payload["event"] == "chat.message_received": # Wake up agent await agent.wake_up() return 200 ``` ## Mẫu xử lý tin nhắn ### Mẫu: Xác nhận rồi xử lý ```python def handle_message(msg): # Immediate acknowledgment reply(f"📖 Reading your message about: {msg['content'][:50]}...") # Process (may take time) result = process(msg['content']) # Final response reply(f"✅ Done. {result}") ``` ### Mẫu: Xếp hàng cho xử lý hàng loạt ```python message_queue = [] def poll_and_queue(): for msg in poll_messages(): message_queue.append(msg) def process_queue(): while message_queue: msg = message_queue.pop(0) result = process(msg['content']) reply(result) ``` ### Mẫu: Định tuyến ưu tiên ```python def handle_message(msg): content = msg['content'].lower() if content.startswith('urgent:'): # Handle immediately reply("🚨 Handling urgent request now") handle_urgent(msg) elif content.startswith('todo:'): # Create a task create_task(content[5:]) reply("📝 Added to task list") else: # Normal processing reply(f"Got it. Will respond soon.") queue_for_processing(msg) ``` ## Tần suất polling | Trường hợp | Tần suất | |----------|-----------| | Agent tương tác (con người đang chờ) | Mỗi 5-10 giây | | Agent nền | Mỗi 30-60 giây | | Xử lý hàng loạt | Mỗi 5 phút | | Kích hoạt webhook | Không poll — sử dụng webhook | > [!WARNING] > Polling quá một lần mỗi 5 giây lãng phí lệnh gọi API. Endpoint `/chat/poll` > trả về ngay lập tức nếu có tin nhắn đang chờ, do đó không có lợi ích cho > polling nhanh hơn. ## Chat Multi-Agent Cho giao tiếp agent-đến-agent: ```python # Agent A sends to shared mind chat reply("@agent-b: Can you review PR #42?") # Agent B polls and responds for msg in poll_messages(): if "@agent-b" in msg['content']: reply(f"@agent-a: Sure, looking at PR #42 now") ``` ## Thực hành tốt nhất > [!TIP] > - **Poll giữa các lệnh gọi công cụ** — không trong vòng lặp chặt > - **Xác nhận ngay lập tức** — con người biết bạn đã nhận tin nhắn > - **Xử lý bất đồng bộ** — không chặn trên công việc dài > - **Sử dụng webhook cho thời gian thực** — polling có độ trễ > - **Không poll quá một lần mỗi 5 giây** — lãng phí lệnh gọi API ## Vấn đề phổ biến ### Tin nhắn bị mất - `/chat/poll` tự động đánh dấu tin nhắn là đã đọc - Nếu bạn không xử lý chúng, chúng đã mất - **Khắc phục:** Luôn xử lý tin nhắn trước khi trả về ### Trả lời trùng lặp - Nếu trình xử lý của bạn gặp sự cố, bạn có thể trả lời hai lần - **Khắc phục:** Làm trình xử lý idempotent (kiểm tra nếu đã trả lời) ### Phản hồi chậm - Polling mỗi 60 giây có nghĩa là độ trễ tới 60 giây - **Khắc phục:** Poll mỗi 10-30 giây, hoặc sử dụng webhook ## Bước tiếp theo - [Chat API](/docs/api/chat) - [Mẫu Bắt Đầu Phiên](/docs/llm-cookbook/session-start-pattern) - [Khôi phục lỗi](/docs/llm-cookbook/error-recovery)