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
+32
View File
@@ -0,0 +1,32 @@
import sharp from "sharp";
function escapeXml(value: string) {
return value.replace(/[&<>"']/g, (char) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&apos;" })[char]!);
}
function headlineLines(value: string, max = 24): string[] {
const words = value.trim().replace(/\s+/g, " ").split(" ");
const lines: string[] = [];
let line = "";
for (const word of words) {
const candidate = line ? `${line} ${word}` : word;
if (candidate.length > max && line) { lines.push(line); line = word; }
else line = candidate;
}
if (line) lines.push(line);
return lines.slice(0, 3);
}
/** Adds a reliable Thai editorial headline after image generation; image models do not typeset Thai safely. */
export async function addArticleHeadline(image: Buffer, headline: string, accent = "#0077B6"): Promise<Buffer> {
const lines = headlineLines(headline);
if (!lines.length) return image;
const svg = `<svg width="1024" height="1024" xmlns="http://www.w3.org/2000/svg">
<defs><linearGradient id="shade" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#101820" stop-opacity="0"/><stop offset="0.28" stop-color="#101820" stop-opacity="0.82"/><stop offset="1" stop-color="#101820" stop-opacity="0.97"/></linearGradient></defs>
<rect x="0" y="500" width="1024" height="524" fill="url(#shade)"/>
<rect x="64" y="590" width="112" height="9" rx="4" fill="${escapeXml(accent)}"/>
<text x="64" y="650" fill="#FFFFFF" font-family="Noto Sans Thai, sans-serif" font-size="29" font-weight="600">AI UPDATE</text>
${lines.map((line, index) => `<text x="64" y="${735 + index * 88}" fill="#FFFFFF" font-family="Noto Sans Thai, sans-serif" font-size="64" font-weight="700">${escapeXml(line)}</text>`).join("")}
</svg>`;
return sharp(image, { limitInputPixels: 40_000_000 }).resize(1024, 1024, { fit: "cover" }).composite([{ input: Buffer.from(svg) }]).jpeg({ quality: 90 }).toBuffer();
}
+38
View File
@@ -0,0 +1,38 @@
import { searchNews } from "./news";
import { websitePrompt } from "./website";
export type ArticleSource = { title: string; url: string; source: string; publishedAt: string | null };
/** Collects current English-language AI reporting before the text model writes an automatic article. */
export async function researchAiArticle(): Promise<{ prompt: string; sources: ArticleSource[] }> {
const results = await searchNews("artificial intelligence OpenAI Anthropic Claude Gemini Copilot", { language: "en-US", market: "US" });
const topicPattern = /\b(AI|artificial intelligence|OpenAI|Anthropic|Claude|Gemini|Copilot|ChatGPT|machine learning)\b/i;
const trustedPattern = /Reuters|Associated Press|Bloomberg|Financial Times|BBC|The Verge|TechCrunch|Ars Technica|Wired|VentureBeat|MIT Technology Review|Microsoft|Google|OpenAI|Anthropic/i;
const ranked = results
.filter((article) => topicPattern.test(`${article.title} ${article.description}`))
.sort((a, b) => Number(trustedPattern.test(b.source)) - Number(trustedPattern.test(a.source)));
const selected = [] as typeof results;
const hosts = new Set<string>();
for (const article of ranked) {
try {
const host = new URL(article.url).hostname.replace(/^www\./, "");
if (/\.th$|tha/i.test(host) || hosts.has(host)) continue;
hosts.add(host);
selected.push(article);
if (selected.length === 3) break;
} catch { /* Ignore malformed search results. */ }
}
const read = await Promise.all(selected.map(async (article) => ({ article, text: await websitePrompt(article.url) })));
const usable = read.filter(({ article, text }) => text || article.description);
if (!usable.length) throw new Error("No readable international AI articles");
const sources = usable.map(({ article }) => ({ title: article.title, url: article.url, source: article.source, publishedAt: article.publishedAt }));
const prompt = usable.map(({ article, text }, index) => `<foreign_source index="${index + 1}">
Publisher: ${article.source}
Published: ${article.publishedAt ?? "unknown"}
Title: ${article.title}
Search excerpt: ${article.description || "none"}
Article text:
${text || "Page could not be read; use only the title and search excerpt cautiously."}
</foreign_source>`).join("\n\n");
return { prompt, sources };
}
+3 -2
View File
@@ -28,11 +28,12 @@ function field(item: string, name: string): string {
}
/** Search current public news through Bing's RSS endpoint; no credentials or page data leave the server. */
export async function searchNews(query: string): Promise<NewsArticle[]> {
export async function searchNews(query: string, options: { language?: string; market?: string } = {}): Promise<NewsArticle[]> {
const url = new URL("https://www.bing.com/news/search");
url.searchParams.set("q", query);
url.searchParams.set("format", "rss");
url.searchParams.set("setlang", "th-TH");
url.searchParams.set("setlang", options.language ?? "th-TH");
if (options.market) url.searchParams.set("cc", options.market);
const response = await fetch(url, {
cache: "no-store",
signal: AbortSignal.timeout(SEARCH_TIMEOUT_MS),
+2 -1
View File
@@ -8,6 +8,7 @@ export const POST_JOB_STATUS = {
export const POST_JOB_STAGE: Record<string, string> = {
queued: "รอเริ่มสร้างโพสต์",
research: "กำลังค้นและอ่านข่าว AI จากต่างประเทศ",
content: "Codex กำลังเขียนเนื้อหาและพรอมต์ภาพ",
image: "ChatGPT กำลังสร้างภาพ",
saving: "กำลังบันทึกฉบับร่าง",
@@ -29,5 +30,5 @@ export interface PostJobView {
export function postJobProgress(job: Pick<PostJobView, "status" | "stage">): number {
if (job.status === "COMPLETED") return 100;
if (job.status === "QUEUED" || job.status === "CANCELLED") return 0;
return ({ content: 10, image: 50, saving: 90 } as Record<string, number>)[job.stage] ?? 0;
return ({ research: 10, content: 25, image: 55, saving: 90 } as Record<string, number>)[job.stage] ?? 0;
}
+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) {