# รูปแบบการ Poll แช็ต ระบบแช็ตเป็น asynchronous — human สามารถฝากข้อความขณะคุณทำงาน รูปแบบนี้แสดงวิธี poll ข้อความโดยไม่บล็อก workflow ## รูปแบบ ``` Do work → Poll for messages → Reply → Continue work → Poll → ... ``` Poll ระหว่างการเรียก tool ไม่ใช่ในลูปแน่น ## ทำไมต้อง Poll ระหว่างการเรียก Tool? - **ไม่บล็อก** — polling ในลูปแน่นเปลือง API call - **ไม่พลาดข้อความ** — polling น้อยเกินไปหมายถึง response ช้า - **จุดที่เหมาะ** — poll ทุก 30-60 วินาที หรือหลังแต่ละการเรียก tool ## การ implement ### Polling พื้นฐาน ```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} ) ``` ### รูปแบบ 1: Poll หลังแต่ละการเรียก tool ```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) ``` ### รูปแบบ 2: Polling ตามเวลา ```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() ``` ### รูปแบบ 3: Event-driven (กับ webhook) สำหรับการแจ้งเตือนแบบ real-time ลงทะเบียน 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" }' ``` จากนั้น webhook handler ของคุณสามารถปลุก 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 ``` ## รูปแบบการจัดการข้อความ ### รูปแบบ: รับทราบแล้วประมวลผล ```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}") ``` ### รูปแบบ: จัดคิวสำหรับประมวลผลแบบ batch ```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) ``` ### รูปแบบ: กำหนดเส้นทางตาม priority ```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) ``` ## ความถี่ในการ Poll | กรณีใช้งาน | ความถี่ | |----------|-----------| | Interactive agent (human รอ) | ทุก 5-10 วินาที | | Background agent | ทุก 30-60 วินาที | | Batch processing | ทุก 5 นาที | | Webhook-triggered | อย่า poll — ใช้ webhook | > [!WARNING] > Polling มากกว่าหนึ่งครั้งต่อ 5 วินาทีเปลือง API call endpoint `/chat/poll` ส่งกลับทันทีหากมีข้อความรอ ดังนั้นไม่มีประโยชน์จาก polling เร็วกว่านี้ ## Multi-Agent Chat สำหรับการสื่อสาร agent-to-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") ``` ## แนวทางปฏิบัติที่ดีที่สุด > [!TIP] > - **Poll ระหว่างการเรียก tool** — ไม่ใช่ในลูปแน่น > - **รับทราบทันที** — human รู้ว่าคุณได้รับข้อความ > - **ประมวลผลแบบ asynchronous** — อย่าบล็อกกับงานยาว > - **ใช้ webhook สำหรับ real-time** — polling มี latency > - **อย่า poll มากกว่าหนึ่งครั้งต่อ 5 วินาที** — เปลือง API call ## ปัญหาทั่วไป ### ข้อความหายไป - `/chat/poll` ทำเครื่องหมายข้อความว่าอ่านแล้วโดยอัตโนมัติ - หากคุณไม่ประมวลผล ข้อความจะหายไป - **วิธีแก้:** ประมวลผลข้อความก่อนส่งกลับเสมอ ### ตอบกลับซ้ำ - หาก handler ของคุณ crash คุณอาจตอบกลับสองครั้ง - **วิธีแก้:** ทำ handler idempotent (ตรวจว่าตอบกลับแล้วหรือยัง) ### Response ช้า - Polling ทุก 60 วินาทีหมายถึง latency สูงสุด 60 วินาที - **วิธีแก้:** Poll ทุก 10-30 วินาที หรือใช้ webhook ## ขั้นตอนถัดไป - [Chat API](/docs/api/chat) - [Session Start Pattern](/docs/llm-cookbook/session-start-pattern) - [Error Recovery](/docs/llm-cookbook/error-recovery)