Files
PAGIVA/src/app/api/ai/image/route.ts
T
Loma Bot Ops 6994ba1a4e Move AI to Codex CLI + ChatGPT browser workers with a durable post queue
Text generation now runs through a PM2 automation worker (codex exec) and
images through the ChatGPT Chrome extension, replacing the Anthropic API.
generateStructured keeps its signature; results are Zod-validated on the web
side and the worker is reached with a bearer secret.

- AI image assistant in the post editor: editable prompt step, then image
  (square or 3:2 only, since Instagram rejects 2:3), stored via putBlob
- Full-post queue (PostGenerationJob + migration): enqueue returns 202, FIFO
  claim under an advisory lock, heartbeat, stale-job failure, per-user
  request key, cancel while QUEUED; output is always a DRAFT with audit rows
- Separate 10 images/page/day quota; text quota excludes images
- Worker reports Codex usage-limit as 429 with a clear Thai message
- Docs: AI-AUTOMATION.md, ARCHITECTURE/README/.env.example updated

Known gap: the live FIFO queue check (scripts/check-post-queue.mjs) has not
passed yet; the last run hit the Codex account usage limit.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-22 21:52:09 +07:00

91 lines
4.9 KiB
TypeScript

import { NextResponse } from "next/server";
import * as z from "zod/v4";
import { appUrl } from "@/lib/base-path";
import { prisma } from "@/lib/db";
import { requirePageAction } from "@/lib/auth/user";
import { errorResponse, readJson, str } from "@/lib/http";
import { UserFacingError } from "@/lib/facebook/client";
import { generateStructured } from "@/lib/ai/claude";
import { profilePrompt } from "@/lib/ai/shared";
import { assertImageQuota, generateImage } from "@/lib/ai/image";
import { IMAGE_PROMPT_MAX, IMAGE_SIZES, type ImageSizeKey } from "@/lib/ai/image-shared";
import { putBlob } from "@/lib/storage/blob";
export const maxDuration = 360;
const ImagePrompt = z.object({
prompt: z.string().describe("The finished English prompt for the image model"),
});
const SYSTEM = `You write prompts for an AI image generator. The images illustrate Facebook and Instagram posts for a small Thai business page; a person reads and may edit your prompt before any image is made.
- Output one English prompt of 60-140 words: subject, setting, composition, lighting, colour mood, and photographic or illustration style.
- Show only what the owner described or what <shop_profile> states. Never invent products, packaging, prices or claims.
- Ask for no text, lettering, logos, watermarks or brand names inside the image (image models spell Thai badly; the caption carries the words).
- No identifiable real people, celebrities or copyrighted characters. If people appear, keep them generic.
- No before/after imagery and no exaggerated results (cures, guaranteed outcomes).
- Match the shop's tone and audience through the visual mood.`;
/**
* Two steps, both explicit button presses in the editor:
* - `{ action: "prompt", pageId, description }` → an editable prompt (Codex CLI, nothing saved)
* - `{ action: "generate", pageId, prompt, size }` → the image (ChatGPT browser), stored like an upload → `{ url }`
* The returned URL only fills the editor; the post still goes through normal approval.
*/
export async function POST(req: Request) {
const body = await readJson(req);
const pageId = str(body.pageId);
const auth = await requirePageAction(pageId, "editPost");
if (!auth.ok) return auth.response;
try {
// SUPERADMIN passes the role check for any id, so confirm the page exists.
const page = await prisma.page.findUnique({
where: { id: pageId },
select: { profile: { select: { business: true, audience: true, tone: true, avoid: true, cta: true } } },
});
if (!page) return NextResponse.json({ error: "ไม่พบเพจ" }, { status: 404 });
const action = str(body.action);
if (action === "prompt") {
const description = str(body.description).trim();
if (!description) throw new UserFacingError("บอก AI ว่าอยากได้รูปแบบไหน");
if (description.length > 1000) throw new UserFacingError("คำอธิบายยาวเกิน 1,000 ตัวอักษร");
const result = await generateStructured({
kind: "image-prompt",
pageId,
userId: auth.user.id,
system: SYSTEM,
prompt: `${profilePrompt(page.profile)}\n\nWrite the image prompt for the idea below.\n\n<idea>\n${description}\n</idea>`,
schema: ImagePrompt,
effort: "low",
});
const prompt = result.prompt.trim();
if (!prompt) throw new UserFacingError("AI ตอบกลับไม่ครบ ลองใหม่อีกครั้ง");
return NextResponse.json({ prompt, profileMissing: !page.profile });
}
if (action === "generate") {
const prompt = str(body.prompt).trim();
const size = str(body.size);
if (!prompt) throw new UserFacingError("ใส่คำอธิบายรูปก่อน");
if (prompt.length > IMAGE_PROMPT_MAX) throw new UserFacingError(`คำอธิบายรูปยาวเกิน ${IMAGE_PROMPT_MAX.toLocaleString("th-TH")} ตัวอักษร`);
if (!Object.hasOwn(IMAGE_SIZES, size)) throw new UserFacingError("ไม่รู้จักขนาดรูปนี้");
await assertImageQuota(pageId);
const image = await generateImage(prompt, size as ImageSizeKey);
const file = new File([new Uint8Array(image.bytes)], "ai-image.jpg", { type: image.contentType });
const blob = await putBlob(`posts/${pageId}/ai-image.jpg`, file, { contentType: image.contentType }, appUrl(new URL(req.url).origin));
// Recorded only after the image is stored, so a failed save doesn't spend quota.
await prisma.aiUsage.create({
data: { pageId, userId: auth.user.id, kind: "image", inputTokens: image.inputTokens, outputTokens: image.outputTokens },
});
return NextResponse.json({ url: blob.url });
}
throw new UserFacingError("ไม่รู้จักคำสั่งนี้");
} catch (e) {
return errorResponse(e, "ai:image");
}
}