简介
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 不会回放。