# Tự động hóa Webhook Webhook cho phép bạn kích hoạt hệ thống bên ngoài khi sự kiện Synapse kích hoạt. Hướng dẫn này bao phủ mẫu tự động hóa phổ biến. ## Mẫu phổ biến ### Mẫu 1: Thông báo khi bộ nhớ Critical Gửi tin nhắn Slack khi bộ nhớ critical được lưu: ```python # Webhook handler (your server) @app.post("/webhook") async def handle(request): payload = await request.json() # Verify signature if not verify_signature(payload, request.headers): return 401 if payload["event"] == "memory.store": memory = payload["data"] if memory.get("priority") == "critical": # Send Slack notification await slack.post( f"🚨 Critical memory stored: {memory['key']}\n{memory['content'][:200]}" ) return 200 ``` Đăng ký webhook: ```bash curl -X POST https://synapse.schaefer.zone/webhooks \ -H "Authorization: Bearer YOUR_MIND_KEY" \ -H "Content-Type: application/json" \ -d '{ "url": "https://my-app.com/webhook", "events": "memory.store", "secret": "my-hmac-secret" }' ``` ### Mẫu 2: Đồng bộ với hệ thống bên ngoài Đồng bộ bộ nhớ với Notion, Obsidian hoặc bất kỳ KB bên ngoài: ```python @app.post("/webhook") async def sync_to_notion(request): payload = await request.json() if payload["event"] == "memory.store": memory = payload["data"] # Create Notion page await notion.create_page( title=memory["key"], content=memory["content"], tags=memory.get("tags", []) ) elif payload["event"] == "memory.delete": # Delete from Notion await notion.delete_page(memory_id=payload["data"]["id"]) return 200 ``` ### Mẫu 3: Kích hoạt CI/CD Kích hoạt triển khai khi một bộ nhớ "release" được lưu: ```python @app.post("/webhook") async def trigger_deploy(request): payload = await request.json() if payload["event"] == "memory.store": memory = payload["data"] if memory.get("key", "").startswith("release_"): # Trigger GitLab pipeline await gitlab.trigger_pipeline( project="synapse", ref="main", variables={"RELEASE_MEMORY_ID": memory["id"]} ) return 200 ``` ### Mẫu 4: Đánh thức Agent khi tin nhắn con người Kích hoạt chạy LLM agent khi con người gửi tin nhắn chat: ```python @app.post("/webhook") async def wake_agent(request): payload = await request.json() if payload["event"] == "chat.message_received": message = payload["data"] # Queue agent processing job await job_queue.enqueue( "process_message", message_id=message["id"], content=message["content"] ) return 200 ``` ### Mẫu 5: Tổng hợp chỉ số Theo dõi tăng trưởng bộ nhớ, hoạt động chat, hoàn thành tác vụ: ```python @app.post("/webhook") async def track_metrics(request): payload = await request.json() event = payload["event"] metrics = { "memory.store": "memories_stored_total", "memory.delete": "memories_deleted_total", "chat.message_received": "messages_received_total", "task.created": "tasks_created_total", "task.completed": "tasks_completed_total", } if event in metrics: await prometheus.increment(metrics[event]) return 200 ``` ## Xác minh chữ ký Luôn xác minh chữ ký webhook để ngăn giả mạo: ```python import hmac import hashlib def verify_signature(payload_body: bytes, headers, secret: str) -> bool: signature = headers.get("X-Synapse-Signature", "") if not signature.startswith("sha256="): return False expected = hmac.new( secret.encode(), payload_body, hashlib.sha256 ).hexdigest() return hmac.compare_digest(f"sha256={expected}", signature) ``` ## Logic thử lại Synapse thử lại webhook thất bại với exponential backoff. Trình xử lý của bạn nên: 1. **Trả 200 nhanh** — không làm công việc nặng đồng bộ 2. **Xếp hàng công việc** — sử dụng hệ thống công việc nền 3. **Idempotent** — cùng sự kiện có thể được gửi hai lần ```python @app.post("/webhook") async def handle(request): payload = await request.json() # Queue for async processing await job_queue.enqueue("process_webhook", payload) # Return immediately return 200 ``` ## Gỡ lỗi Webhook ### Kiểm tra lịch sử gửi Việc gửi webhook được ghi nhật ký. Kiểm tra gửi gần đây của webhook: ```bash # Get webhook details including recent deliveries curl -H "Authorization: Bearer YOUR_MIND_KEY" \ https://synapse.schaefer.zone/webhooks/wh_001 ``` ### Kiểm tra webhook thủ công ```bash # Trigger a test event curl -X POST https://synapse.schaefer.zone/webhooks/wh_001/test \ -H "Authorization: Bearer YOUR_MIND_KEY" ``` ### Vấn đề phổ biến | Vấn đề | Khắc phục | |-------|-----| | Phản hồi 4xx | Kiểm tra trình xử lý trả 200 | | Phản hồi 5xx | Lỗi server — kiểm tra nhật ký ứng dụng | | Timeout | Trả 200 nhanh, xếp hàng công việc async | | Gửi trùng lặp | Làm trình xử lý idempotent | | Chữ ký không khớp | Xác minh secret chính xác | ## Thực hành tốt nhất > [!TIP] > - **Luôn xác minh chữ ký** — không bao giờ bỏ qua > - **Trả 200 nhanh** — không chặn Synapse > - **Idempotent** — xử lý gửi trùng lặp > - **Sử dụng sự kiện cụ thể** — `memory.store` không phải `*` > - **Giám sát gửi thất bại** — thiết lập cảnh báo ## Bước tiếp theo - [Webhooks API](/docs/api/webhooks) - [Cron & Scheduler](/docs/api/cron) - [LLM Agent cố định](/docs/guides/persistent-llm-agent)