Files
PAGIVA/src/app/api/ai/research/route.ts
T
2026-11-23 21:59:02 +07:00

72 lines
3.9 KiB
TypeScript

import { NextResponse } from "next/server";
import * as z from "zod/v4";
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 { searchNews } from "@/lib/ai/news";
import { websitePrompt } from "@/lib/ai/website";
import { profilePrompt } from "@/lib/ai/shared";
import { CAPTION_RULES, platformRule } from "@/lib/ai/prompts";
export const maxDuration = 300;
const ResearchDraft = z.object({
summary: z.string().describe("A concise Thai summary of the source in 2-3 sentences"),
keyPoints: z.array(z.string()).describe("Three useful factual takeaways in Thai"),
postTitle: z.string().describe("A short internal Thai title for the post"),
caption: z.string().describe("A ready-to-edit Thai social caption grounded only in the source"),
});
const SYSTEM = `You turn a recent article into an educational Thai social post for a small business page. The owner reviews the source and edits your draft before it goes through human approval.
Never invent facts, quotes, dates, product capabilities, or statistics. Distinguish confirmed source facts from commentary. If the source text is thin, write a cautious overview and say what should be checked. Do not copy long passages. Mention the source naturally at the end.
${CAPTION_RULES}`;
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 {
const action = str(body.action);
if (action === "search") {
const query = str(body.query).trim();
if (query.length < 2) throw new UserFacingError("พิมพ์หัวข้อที่ต้องการค้นหาอย่างน้อย 2 ตัวอักษร");
if (query.length > 120) throw new UserFacingError("หัวข้อค้นหายาวเกิน 120 ตัวอักษร");
const articles = await searchNews(query);
return NextResponse.json({ articles });
}
if (action !== "summarize") throw new UserFacingError("ไม่รู้จักคำสั่งค้นคว้านี้");
const title = str(body.title).trim();
const url = str(body.url).trim();
const source = str(body.source).trim();
const description = str(body.description).trim().slice(0, 600);
if (!title || !/^https?:\/\//.test(url)) throw new UserFacingError("ข้อมูลบทความไม่ครบ กรุณาค้นหาใหม่");
const page = await prisma.page.findUnique({
where: { id: pageId },
select: { profile: { select: { business: true, audience: true, tone: true, visualStyle: true, avoid: true, cta: true, website: true } } },
});
if (!page) return NextResponse.json({ error: "ไม่พบเพจ" }, { status: 404 });
const articleText = await websitePrompt(url);
const result = await generateStructured({
kind: "research",
pageId,
userId: auth.user.id,
system: SYSTEM,
prompt: `${profilePrompt(page.profile)}\n\n${platformRule(Array.isArray(body.targets) && body.targets.includes("INSTAGRAM"))}\n\nCreate a factual post from this source.\nTitle: ${title}\nPublisher: ${source || "ไม่ระบุ"}\nURL: ${url}\nSearch excerpt: ${description || "ไม่มี"}\n\n${articleText || "The article page could not be read. Use only the title and search excerpt, keep the summary cautious, and explicitly advise the owner to verify the original."}`,
schema: ResearchDraft,
effort: "low",
});
return NextResponse.json({ draft: result, sourceRead: Boolean(articleText) });
} catch (error) {
return errorResponse(error, "ai:research");
}
}