名称: replicate-handler 描述: 与Replicate AI集成,用于运行模型(图像生成、大语言模型等)。
Replicate处理器
设置
- 安装:
npm install replicate - 环境变量: 在
.env(以及.env.local)文件中添加REPLICATE_API_TOKEN。
使用模式
1. 快速运行(短任务)
对于快速完成(几秒钟)的模型,使用 replicate.run。
import Replicate from "replicate";
const replicate = new Replicate({
auth: process.env.REPLICATE_API_TOKEN,
});
// 运行一个模型
const output = await replicate.run(
"所有者/模型:版本",
{
input: {
prompt: "..."
}
}
);
2. 长时间运行任务(使用Inngest)
对于可能超时的任务(视频生成、大型模型),使用Inngest的 step.sleep 来轮询完成状态。
// 在一个Inngest函数中
export const generateVideo = inngest.createFunction(
{ id: "generate-video" },
{ event: "video.generate" },
async ({ event, step }) => {
// 1. 创建预测
const prediction = await step.run("create-prediction", async () => {
return await replicate.predictions.create({
version: "模型版本哈希",
input: { prompt: event.data.prompt }
});
});
let status = prediction.status;
let result = prediction;
// 2. 轮询完成状态
while (status !== "succeeded" && status !== "failed" && status !== "canceled") {
// 休眠5秒(Inngest处理此操作,不消耗服务器时间)
await step.sleep("wait-for-model", "5s");
// 检查状态
result = await step.run("check-status", async () => {
return await replicate.predictions.get(prediction.id);
});
status = result.status;
}
// 3. 处理结果
if (status === "failed") {
throw new Error(`Replicate失败: ${result.error}`);
}
return result.output;
}
);
类型参考
完整Replicate SDK的类型定义请参见 reference.md。