40 lines
1.7 KiB
TypeScript
40 lines
1.7 KiB
TypeScript
// Compatibility module: all structured content now runs through Codex CLI.
|
|
import * as z from "zod/v4";
|
|
import { prisma } from "@/lib/db";
|
|
import { UserFacingError } from "@/lib/facebook/client";
|
|
import { runAutomation } from "./automation";
|
|
export const AI_DAILY_LIMIT_PER_PAGE = 30;
|
|
|
|
export async function generateStructured<S extends z.ZodType>(req: {
|
|
kind: "caption" | "profile" | "week-plan" | "check" | "reply" | "image-prompt" | "post-generation" | "research";
|
|
pageId: string;
|
|
userId: string;
|
|
system: string;
|
|
prompt: string;
|
|
schema: S;
|
|
effort: "low" | "medium";
|
|
waitForWorker?: boolean;
|
|
}): Promise<z.infer<S>> {
|
|
const since = new Date(Date.now() - 24 * 60 * 60 * 1000);
|
|
// Images have their own, tighter limit (lib/ai/image.ts) and must not eat the text quota.
|
|
const used = await prisma.aiUsage.count({ where: { pageId: req.pageId, kind: { not: "image" }, createdAt: { gte: since } } });
|
|
if (used >= AI_DAILY_LIMIT_PER_PAGE) {
|
|
throw new UserFacingError(`เพจนี้ใช้ AI ครบ ${AI_DAILY_LIMIT_PER_PAGE} ครั้งใน 24 ชั่วโมงแล้ว ลองใหม่ภายหลัง`);
|
|
}
|
|
|
|
const response = await runAutomation({ kind: "text", system: req.system, prompt: req.prompt, schema: z.toJSONSchema(req.schema) }, { waitForWorker: req.waitForWorker });
|
|
const result = req.schema.safeParse(response.result);
|
|
if (!result.success) throw new UserFacingError("Codex ตอบกลับไม่ครบรูปแบบ ลองใหม่อีกครั้ง");
|
|
|
|
await prisma.aiUsage.create({
|
|
data: {
|
|
pageId: req.pageId,
|
|
userId: req.userId,
|
|
kind: req.kind,
|
|
inputTokens: 0,
|
|
outputTokens: 0,
|
|
},
|
|
});
|
|
return result.data;
|
|
}
|