Tự động hóa Webhook
Kích hoạt hệ thống bên ngoài khi bộ nhớ thay đổi — đồng bộ, thông báo, tự động hóa.
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:
# 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:
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:
@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 200Mẫu 3: Kích hoạt CI/CD
Kích hoạt triển khai khi một bộ nhớ "release" được lưu:
@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 200Mẫ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:
@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 200Mẫ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ụ:
@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 200Xác minh chữ ký
Luôn xác minh chữ ký webhook để ngăn giả mạo:
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:
- Trả 200 nhanh — không làm công việc nặng đồng bộ
- Xếp hàng công việc — sử dụng hệ thống công việc nền
- Idempotent — cùng sự kiện có thể được gửi hai lần
@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 200Gỡ 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:
# Get webhook details including recent deliveries
curl -H "Authorization: Bearer YOUR_MIND_KEY" \
https://synapse.schaefer.zone/webhooks/wh_001Kiểm tra webhook thủ công
# 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 |