Skills2026年5月7日·1 分钟阅读

Replicate Webhooks — Async Notifications for Slow Models

Replicate Webhooks let async predictions notify your server when ready. Skip polling for slow models (FLUX, video gen). HMAC-signed for verifiable origin.

Agent 就绪

这个资产可以被 Agent 直接读取和安装

TokRepo 同时提供通用 CLI 命令、安装契约、metadata JSON、按适配器生成的安装计划和原始内容链接,方便 Agent 判断适配度、风险和下一步动作。

Stage only · 17/100Stage only
Agent 入口
任意 MCP/CLI Agent
类型
Skill
安装
Stage only
信任
信任等级:New
入口
Asset
通用 CLI 安装命令
npx tokrepo install 39c66b39-d832-457b-89f8-308f599fc64b

简介

Replicate Webhook 让你启动一个 prediction 后,Replicate 在完成时 POST 到你的服务器 —— 不用轮询。慢模型(FLUX 图像生成、视频生成、大 LLM)这种 prediction 跑十几秒到几分钟的场景关键。适合带异步 UI 的生产应用、fire-and-forget agent、基于队列的流水线。需要 Replicate API + 任何 HTTP 端点。装机时间 5 分钟。


启动带 webhook 的 prediction

import Replicate from "replicate";

const replicate = new Replicate({ auth: process.env.REPLICATE_API_TOKEN });

const prediction = await replicate.predictions.create({
  version: "black-forest-labs/flux-schnell",
  input: { prompt: "A misty forest at dawn, photorealistic" },
  webhook: "https://yourapp.com/webhooks/replicate",
  webhook_events_filter: ["completed"],  // 或 ["start", "output", "logs", "completed"]
});

return Response.json({ predictionId: prediction.id });

接收 webhook(Next.js 示例)

// app/webhooks/replicate/route.ts
import crypto from "node:crypto";

export async function POST(req: Request) {
  // 校验 webhook 签名
  const signature = req.headers.get("webhook-signature");
  const timestamp = req.headers.get("webhook-timestamp");
  const id = req.headers.get("webhook-id");
  const body = await req.text();

  const signedContent = `${id}.${timestamp}.${body}`;
  const expected = crypto
    .createHmac("sha256", process.env.REPLICATE_WEBHOOK_SECRET!)
    .update(signedContent)
    .digest("base64");

  if (!signature?.includes(expected)) {
    return Response.json({ error: "invalid signature" }, { status: 401 });
  }

  // 处理 prediction
  const prediction = JSON.parse(body);
  if (prediction.status === "succeeded") {
    await saveImageUrl(prediction.id, prediction.output);
  } else {
    await flagFailure(prediction.id, prediction.error);
  }

  return Response.json({ ok: true });
}

拿 webhook secret

# 生成 webhook 签名 secret
curl -X POST https://api.replicate.com/v1/webhooks/default/secret \
  -H "Authorization: Token $REPLICATE_API_TOKEN"

# 返回:{ "key": "whsec_..." }
# 存为 REPLICATE_WEBHOOK_SECRET 环境变量

为啥比轮询好

  • 轮询:5 秒间隔 = 完成事件 p50 延迟 5 秒,还要持续消耗 API 配额
  • Webhook:完成到你 handler 亚秒级,零轮询负载

FAQ

Q: Webhook 幂等吗? A: Replicate 会在瞬时错误时重试 webhook,所以 handler 必须幂等。用 webhook-id header(每个事件的唯一 ID)做你这边的去重。

Q: 能用 webhook 拿流式输出吗? A: 能 —— 设 webhook_events_filter: ["output"] 接收模型出 token / 帧 / 部分结果的增量输出事件。慢模型搭流式 UI 更新好用。

Q: 我的 webhook 端点挂了怎么办? A: Replicate 会按指数退避重试失败的 webhook 约 24 小时。之后 prediction 还能通过 GET /predictions/{id} 拿到,但 webhook 不会回放。


🙏

来源与感谢

Built by Replicate. Commercial product.

replicate.com/docs/webhooks — Webhooks documentation

讨论

登录后参与讨论。
还没有评论,来写第一条吧。

相关资产