Skip to main content

Webhook 与通知

通过 Webhook 接收实时事件通知,并轮询获取主动智能体消息。

Webhook 概览

注册 Webhook URL,在事件发生时接收 HTTP POST 回调。每当订阅的事件触发时,平台会向你的端点发送一个经过签名的 JSON 负载,无需轮询即可实现实时集成。

注册 Webhook

通过提供 URL 和可选的认证请求头来订阅事件类型。

const webhook = await client.webhooks.register("agent.message", {
webhookUrl: "https://your-server.com/webhooks/sonzai",
authHeader: "Bearer your-webhook-secret",
});

console.log(webhook.secret); // 用于验证 webhook 签名

Webhook 事件

可以订阅的事件类型:

  • agent.message:智能体发送主动消息
  • agent.mood_change:智能体情绪发生显著变化
  • agent.memory_added:提取到新记忆
  • agent.breakthrough:重大人格里程碑
  • agent.wakeup:触发了计划的唤醒
  • agent.consolidation:记忆整合完成

管理 Webhook

列出、删除、查看投递尝试,以及轮换已注册 Webhook 的密钥。

// 列出所有 webhook
const webhooks = await client.webhooks.list();

// 删除 webhook
await client.webhooks.delete("agent.message");

// 查看投递尝试
const attempts = await client.webhooks.listDeliveryAttempts("agent.message");

// 轮换 webhook 密钥
const rotated = await client.webhooks.rotateSecret("agent.message");

项目范围的 Webhook

在项目级别注册 Webhook,接收项目内所有智能体的事件。

await client.webhooks.registerForProject("project-id", "agent.message", {
webhookUrl: "https://your-server.com/webhooks/project",
});

const projectWebhooks = await client.webhooks.listForProject("project-id");

主动通知(轮询)

智能体可以生成由唤醒、情绪变化或其他内部事件触发的主动消息。当推送投递不可行时,可以轮询待处理的通知。

// 列出待处理通知
const notifications = await client.notifications.list("agent-id", {
userId: "user-123",
status: "pending",
});

for (const notif of notifications.items) {
console.log(notif.type, notif.content);

// 处理后标记为已消费
await client.notifications.consume("agent-id", notif.id);
}

// 查看通知历史
const history = await client.notifications.history("agent-id", {
userId: "user-123",
limit: 50,
});

安排唤醒

唤醒是自动的

智能体会根据关系上下文、对话模式和情感信号自动安排自己的唤醒——全部由上下文引擎处理。当唤醒触发时,会发出 agent.wakeup Webhook。

下面的手动安排是补充性的——在你想要触发与业务事件绑定的特定外联时使用(例如购买后的跟进、生日问候或定期工作流提醒)。

安排主动问候,让智能体在特定时间联系用户:

const wakeup = await client.agents.scheduleWakeup("agent-id", {
userId: "user-123",
checkType: "interest_check",
intent: "Check in about the job interview preparation",
delayHours: 24, // 从现在起 24 小时后安排
});

Webhook 与通知的区别

Webhook(推送) 通过 HTTP POST 实时将事件投递到你的服务器。在你有服务器可以接收回调且需要立即收到事件通知时使用 Webhook。

通知(轮询) 将主动智能体消息排队供你按需获取。在你的客户端无法接收入站 HTTP 请求(例如移动应用、浏览器客户端)时,或者你想按自己的节奏批量处理通知时使用轮询。

实际应用

三类受众都会使用 Webhook 和通知,但原因大相径庭。

从客户端轮询通知。 大多数伴侣运行在移动应用或浏览器中, 无法接受入站 Webhook。每 30-60 秒轮询一次,或在应用切换到前台时轮询。

主动唤醒让伴侣感觉有生命力。 谨慎触发——活跃用户每天一次, 其他情况更少。平台根据关系上下文自动安排;你也可以为故事节点 触发额外的唤醒。

const pending = await client.agents.notifications.list("agent-id", {
  userId: "user-123",
  status: "pending",
});

for (const n of pending.notifications) {
  renderCompanionBubble(n.content);
  await client.agents.notifications.consume("agent-id", n.notificationId);
}

不要过度安排。 太多未经提示的消息会很快变成骚扰。

On this page