Prompt Chaining: Tạo Workflow AI Phức Tạp Trong Frontend App
AAdmin
11 tháng 3, 2026
6 phút đọc
0 lượt xem
Tìm hiểu prompt chaining pattern để xây dựng AI workflows nhiều bước trong frontend. Từ content generation pipeline đến multi-step data processing.
Một prompt đơn lẻ thường không đủ cho complex tasks. Prompt chaining — nối nhiều AI calls lại thành pipeline — cho phép bạn break down complex problems thành manageable steps. Mỗi step nhận output từ step trước, tạo thành workflow mạnh mẽ.
Prompt Chaining là gì?
Thay vì 1 prompt "Viết blog post hoàn chỉnh về React Server Components", bạn chain:
- Generate outline từ topic
- Expand mỗi section từ outline
- Review và improve quality
- Generate meta (title, summary, tags)
Kết quả consistently tốt hơn single-shot approach.
Implementation: Content Generation Pipeline
// lib/ai-pipeline.ts
import { generateText, generateObject } from "ai";
import { openai } from "@ai-sdk/openai";
import { z } from "zod";
interface PipelineResult {
title: string;
outline: string[];
content: string;
summary: string;
tags: string[];
}
export async function contentPipeline(topic: string): Promise<PipelineResult> {
// Step 1: Generate outline
const { object: outline } = await generateObject({
model: openai("gpt-4o"),
schema: z.object({
title: z.string(),
sections: z.array(z.object({
heading: z.string(),
keyPoints: z.array(z.string()),
})),
}),
prompt: `Tạo outline cho blog post về: ${topic}. Target: Vietnamese frontend developers. 4-6 sections.`,
});
// Step 2: Expand each section
const sections = await Promise.all(
outline.sections.map(async (section) => {
const { text } = await generateText({
model: openai("gpt-4o-mini"),
prompt: `Viết section "${section.heading}" cho blog post "${outline.title}".
Key points: ${section.keyPoints.join(", ")}.
Style: technical nhưng dễ hiểu, 100-150 words. Vietnamese với English tech terms.`,
});
return { heading: section.heading, content: text };
})
);
// Step 3: Generate metadata
const fullContent = sections.map(s => `## ${s.heading}
${s.content}`).join("
");
const { object: meta } = await generateObject({
model: openai("gpt-4o-mini"),
schema: z.object({
summary: z.string().max(200),
tags: z.array(z.string()).max(5),
}),
prompt: `Generate summary (1-2 câu) và tags cho bài viết:
${fullContent}`,
});
return {
title: outline.title,
outline: outline.sections.map(s => s.heading),
content: fullContent,
...meta,
};
}
Frontend: Pipeline UI với Progress
// components/content-pipeline.tsx
"use client";
import { useState } from "react";
import { Loader2, Check } from "lucide-react";
type Step = "outline" | "content" | "metadata" | "done";
export function ContentPipeline() {
const [topic, setTopic] = useState("");
const [currentStep, setCurrentStep] = useState<Step | null>(null);
const [result, setResult] = useState<Record<string, unknown> | null>(null);
const steps: { key: Step; label: string }[] = [
{ key: "outline", label: "Tạo outline" },
{ key: "content", label: "Viết nội dung" },
{ key: "metadata", label: "Generate metadata" },
{ key: "done", label: "Hoàn thành" },
];
async function handleGenerate() {
setCurrentStep("outline");
const res = await fetch("/api/generate-content", {
method: "POST",
body: JSON.stringify({ topic }),
});
const data = await res.json();
setResult(data);
setCurrentStep("done");
}
return (
<div className="max-w-2xl mx-auto space-y-6">
<div className="flex gap-4">
{steps.map((step, i) => (
<div key={step.key} className="flex items-center gap-2">
{currentStep === step.key ? (
<Loader2 className="w-4 h-4 animate-spin text-blue-600" />
) : steps.indexOf(steps.find(s => s.key === currentStep)!) > i ? (
<Check className="w-4 h-4 text-green-600" />
) : (
<div className="w-4 h-4 rounded-full border-2" />
)}
<span className="text-sm">{step.label}</span>
</div>
))}
</div>
</div>
);
}
Patterns Hữu Ích
- Parallel chains: Dùng
Promise.allcho independent steps — nhanh hơn nhiều so với sequential - Validation gate: Thêm validation step giữa chains để catch errors sớm
- Fallback chain: Nếu step fail, retry với simpler prompt hoặc different model
- Cost optimization: Dùng gpt-4o cho critical steps (outline), gpt-4o-mini cho expansion
Prompt chaining biến AI từ single-shot tool thành powerful workflow engine. Key takeaway: break complex tasks thành small, focused steps — giống cách bạn decompose React components vậy.
A
Admin
Bình luận (0)
Đăng nhập để bình luận
Chưa có bình luận nào. Hãy là người đầu tiên!