Metacognition & Self-Correction
Agent tự đánh giá, tự sửa lỗi và cải thiện liên tục
Metacognition Là Gì?
Metacognition = “nghĩ về cách mình nghĩ”. Với AI Agents, đây là khả năng tự đánh giá performance, nhận ra sai sót, và tự sửa mà không cần con người can thiệp.
Tại Sao Cần Metacognition?
Không có metacognition:
User: "Tìm vé máy bay đi Tokyo"
Agent: Tìm → Trả kết quả (có thể sai/thiếu) → Xong
Có metacognition:
User: "Tìm vé máy bay đi Tokyo"
Agent: Tìm → Đánh giá kết quả → "Giá này có hợp lý không?"
→ "Có thiếu hãng nào không?" → Tìm bổ sung → Trả kết quả tốt hơn
Self-Reflection Pattern
Agent tự hỏi bản thân sau mỗi bước:
import { generateObject, generateText, tool } from "ai";
import { openai } from "@ai-sdk/openai";
import { z } from "zod";
const SelfReflectionSchema = z.object({
taskCompleted: z.boolean(),
qualityScore: z.number().min(1).max(10),
issues: z.array(z.object({
type: z.enum(["accuracy", "completeness", "relevance", "format"]),
description: z.string(),
severity: z.enum(["low", "medium", "high"])
})),
shouldRetry: z.boolean(),
improvementPlan: z.string().optional()
});
async function agentWithReflection(task: string) {
// Bước 1: Thực hiện task
const result = await generateText({
model: openai("gpt-4o"),
tools: { /* ... */ },
maxSteps: 5,
prompt: task
});
// Bước 2: Self-reflection
const { object: reflection } = await generateObject({
model: openai("gpt-4o"),
schema: SelfReflectionSchema,
prompt: `Đánh giá kết quả sau:
Task: ${task}
Output: ${result.text}
Tự hỏi:
1. Output có chính xác không?
2. Có thiếu thông tin quan trọng nào không?
3. Output có relevant với câu hỏi không?
4. Format có phù hợp không?`
});
// Bước 3: Retry nếu cần
if (reflection.shouldRetry && reflection.qualityScore < 7) {
console.log(`🔄 Self-correcting: ${reflection.improvementPlan}`);
const improved = await generateText({
model: openai("gpt-4o"),
prompt: `Cải thiện kết quả trước đó:
Output ban đầu: ${result.text}
Vấn đề phát hiện: ${reflection.issues.map(i => i.description).join(", ")}
Kế hoạch cải thiện: ${reflection.improvementPlan}`
});
return improved.text;
}
return result.text;
}
Corrective RAG Với Metacognition
Kết hợp RAG + self-correction:
async function correctiveRAG(question: string, maxAttempts: number = 3) {
let attempts = 0;
let bestAnswer = "";
let bestScore = 0;
while (attempts < maxAttempts) {
attempts++;
// Retrieve
const docs = await searchDocuments(question);
// Generate
const answer = await generateText({
model: openai("gpt-4o"),
system: "Trả lời dựa trên documents. Nếu không đủ thông tin, nói rõ.",
prompt: `Câu hỏi: ${question}\nDocuments: ${docs.map(d => d.content).join("\n")}`
});
// Evaluate (Metacognition)
const { object: eval } = await generateObject({
model: openai("gpt-4o"),
schema: z.object({
relevanceScore: z.number().min(1).max(10),
isGrounded: z.boolean().describe("Câu trả lời có dựa trên documents không?"),
missingInfo: z.array(z.string()),
suggestedQuery: z.string().optional()
}),
prompt: `Đánh giá câu trả lời:
Q: ${question}
A: ${answer.text}
Docs: ${docs.map(d => d.content).join("\n")}`
});
if (eval.relevanceScore > bestScore) {
bestScore = eval.relevanceScore;
bestAnswer = answer.text;
}
// Đủ tốt → dừng
if (eval.relevanceScore >= 8 && eval.isGrounded) break;
// Chưa đủ → refine query
if (eval.suggestedQuery) {
question = eval.suggestedQuery;
console.log(`🔄 Attempt ${attempts}: Refining to "${question}"`);
}
}
return bestAnswer;
}
Experience-Based Learning
Agent học từ kinh nghiệm qua nhiều sessions:
interface Experience {
task: string;
approach: string;
outcome: "success" | "failure";
lesson: string;
timestamp: Date;
}
// Lưu experiences vào Supabase
async function saveExperience(exp: Experience) {
await supabase.from("agent_experiences").insert(exp);
}
// Recall experiences tương tự
async function recallExperiences(currentTask: string): Promise<Experience[]> {
const embedding = await getEmbedding(currentTask);
const { data } = await supabase.rpc("match_experiences", {
query_embedding: embedding,
match_count: 5
});
return data;
}
// Agent dùng experiences cũ
async function agentWithExperience(task: string) {
const pastExperiences = await recallExperiences(task);
const result = await generateText({
model: openai("gpt-4o"),
system: `Bạn là agent có khả năng metacognition.
Kinh nghiệm từ tasks tương tự trước đây:
${pastExperiences.map(e => `- Task: ${e.task}, Outcome: ${e.outcome}, Lesson: ${e.lesson}`).join("\n")}
Sử dụng kinh nghiệm này để tránh lỗi cũ và áp dụng cách tiếp cận hiệu quả.`,
prompt: task
});
// Lưu kinh nghiệm mới
await saveExperience({
task,
approach: "...",
outcome: "success",
lesson: "...",
timestamp: new Date()
});
return result.text;
}
Metacognition Checklist
Agent tốt tự hỏi những câu này:
| Câu hỏi | Mục đích |
|---|---|
| Output có chính xác không? | Accuracy |
| Tôi có bỏ sót gì không? | Completeness |
| Cách tiếp cận có tối ưu không? | Efficiency |
| Tôi có cần thêm tools không? | Tool selection |
| Người dùng sẽ hài lòng không? | User satisfaction |
| Tôi nên dừng hay tiếp tục? | Termination |
Tổng Kết
- Metacognition = agent tự đánh giá và tự sửa
- Self-reflection qua structured evaluation sau mỗi bước
- Corrective RAG: evaluate → refine → retry tự động
- Experience-based learning: lưu và recall kinh nghiệm từ quá khứ
- Agent biết khi nào dừng — tránh infinite improvement loops