Research international AI news for article posts

This commit is contained in:
Loma Bot Ops
2026-11-27 09:28:29 +07:00
parent abc359de31
commit 9d5bfe7d9d
6 changed files with 104 additions and 8 deletions
+28 -4
View File
@@ -10,6 +10,8 @@ import { CAPTION_RULES, IMAGE_ART_DIRECTION, platformRule } from "./prompts";
import { profilePrompt } from "./shared";
import { putBlob } from "@/lib/storage/blob";
import { logoPalettePrompt } from "./brand-palette";
import { researchAiArticle, type ArticleSource } from "./article-research";
import { addArticleHeadline } from "./article-image";
export const JOB_SELECT = {
id: true, topic: true, status: true, stage: true, postId: true, error: true,
@@ -21,6 +23,7 @@ const Draft = z.object({
title: z.string().min(1).max(120),
caption: z.string().min(1).max(5000),
imagePrompt: z.string().min(20).max(4000),
imageHeadline: z.string().max(100).default(""),
});
const SYSTEM = `Create a complete draft Facebook/Instagram post for a small Thai business. A human will review and approve it before publication.
@@ -74,16 +77,37 @@ export async function processNextPostJob(baseUrl: string) {
await assertImageQuota(job.pageId);
const profile = Profile.parse(job.profileSnapshot);
const logoPalette = await logoPalettePrompt(page.pictureUrl);
const isAutomaticArticle = job.requestKey.startsWith("auto:") && job.topic.includes("ประเภทเนื้อหา: บทความ");
let researchPrompt = "";
let researchSources: ArticleSource[] = [];
if (isAutomaticArticle) {
await prisma.postGenerationJob.update({ where: { id: job.id }, data: { stage: "research" } });
const research = await researchAiArticle();
researchPrompt = research.prompt;
researchSources = research.sources;
await prisma.postGenerationJob.update({ where: { id: job.id }, data: { stage: "content" } });
}
const articleRules = isAutomaticArticle ? `
This automatic slot is a Thai editorial AI-news article grounded only in <foreign_source> material below.
- Select one timely, useful story with enough confirmed detail. Prefer a primary announcement plus corroborating reporting when available.
- Write clear Thai for general business readers: an opening summary followed by 5-8 short paragraphs explaining what happened, how it works, why it matters, and important limits or human oversight. Explain technical terms on first use.
- Paraphrase; never translate long passages or invent facts. If sources disagree or a detail is not confirmed, omit it.
- Do not put publisher names, URLs, a source list, citations, or "อ้างอิง" in the caption. Provenance is retained internally for reviewers.
- imageHeadline must be a compelling factual Thai headline, 45-85 characters, suitable for 2-3 large lines. No clickbait.
- The imagePrompt must request a premium square editorial news visual in the shop's exact brand palette and visual style. Keep the lower half visually quiet for a Thai headline overlay. Do not request any text, logos, UI screenshots, trademarks, or copied news artwork.
` : "\nSet imageHeadline to an empty string.";
const content = await generateStructured({
kind: "post-generation", pageId: job.pageId, userId: job.requestedById,
system: SYSTEM + (job.requestKey.startsWith("auto:") ? "\nThis is an automatic content slot. Choose a fresh, relevant topic from the shop profile and brief data. Avoid repeating the supplied recent topics. Never invent prices, promotions, availability or claims. The slot is creation time, not a publication promise." : ""), effort: "medium", schema: Draft, waitForWorker: true,
prompt: `${profilePrompt(profile)}\n${logoPalette}\n\n${platformRule(job.targets.includes("INSTAGRAM"))}\n\n<topic>\n${job.topic}\n</topic>`,
system: SYSTEM + (job.requestKey.startsWith("auto:") ? "\nThis is an automatic content slot. Choose a fresh, relevant topic from the shop profile and brief data. Avoid repeating the supplied recent topics. Never invent prices, promotions, availability or claims. The slot is creation time, not a publication promise." : "") + articleRules, effort: "medium", schema: Draft, waitForWorker: true,
prompt: `${profilePrompt(profile)}\n${logoPalette}\n\n${platformRule(job.targets.includes("INSTAGRAM"))}\n\n<topic>\n${job.topic}\n</topic>${researchPrompt ? `\n\n<research_material>\n${researchPrompt}\n</research_material>` : ""}`,
});
if (job.targets.includes("INSTAGRAM") && content.caption.length > 2200) throw new UserFacingError("Caption ที่ AI สร้างยาวเกินข้อจำกัด Instagram กรุณาลองใหม่");
await prisma.postGenerationJob.update({ where: { id: job.id }, data: { captionResult: content, imagePrompt: content.imagePrompt, stage: "image" } });
await assertJobAccess(job.pageId, job.requestedById);
const image = await generateImage(content.imagePrompt, "square", true);
const file = new File([new Uint8Array(image.bytes)], "ai-post.jpg", { type: image.contentType });
const accent = logoPalette.match(/#[0-9A-F]{6}/i)?.[0] ?? "#0077B6";
const imageBytes = isAutomaticArticle ? await addArticleHeadline(image.bytes, content.imageHeadline, accent) : image.bytes;
const file = new File([new Uint8Array(imageBytes)], "ai-post.jpg", { type: image.contentType });
const blob = await putBlob(`posts/${job.pageId}/ai-post.jpg`, file, { contentType: image.contentType }, baseUrl);
await prisma.$transaction(async (tx) => {
await tx.postGenerationJob.update({ where: { id: job.id }, data: { imageBlobUrl: blob.url, stage: "saving" } });
@@ -99,7 +123,7 @@ export async function processNextPostJob(baseUrl: string) {
const changed = await tx.postGenerationJob.updateMany({ where: { id: job.id, status: "RUNNING" }, data: { status: "COMPLETED", stage: "completed", postId: post.id, finishedAt: new Date(), error: null } });
if (changed.count !== 1) throw new Error("Queue job no longer owns its execution");
await audit({ action: "POST_CREATED", actorId: user.id, actorLabel: actorLabel(user), pageId: job.pageId, postId: post.id, detail: { aiAssisted: true, jobId: job.id } }, tx);
await audit({ action: "AI_POST_COMPLETED", actorId: user.id, actorLabel: actorLabel(user), pageId: job.pageId, postId: post.id, detail: { jobId: job.id } }, tx);
await audit({ action: "AI_POST_COMPLETED", actorId: user.id, actorLabel: actorLabel(user), pageId: job.pageId, postId: post.id, detail: { jobId: job.id, ...(researchSources.length ? { researchSources } : {}) } }, tx);
});
return { processed: true, jobId: job.id, status: "COMPLETED" };
} catch (error) {