MinAI - Về trang chủ
Lý thuyết
10/1330 phút
Đang tải...

Response Generation

Tạo responses chất lượng cao với citations và formatting cho RAG

💬 Response Generation

0

🎯 Mục tiêu bài học

TB5 min

Sau bài học này, bạn sẽ:

✅ Hiểu các yếu tố ảnh hưởng đến response quality

✅ Biết cách viết system prompt cho RAG responses

✅ Implement citation strategies: inline và source list

✅ Xây dựng confidence scoring system

✅ Xử lý edge cases: no results, low confidence, contradictions

Biến retrieved context thành câu trả lời tự nhiên, chính xác, có citations. Bài này cover response strategies cho RAG.

1

📊 Response Quality Factors

TB5 min
Diagram
Đang vẽ diagram...

Checkpoint

5 yếu tố ảnh hưởng đến response quality là gì?

2

📝 Response Generation Prompt

TB5 min
JavaScript
1// System prompt for high-quality RAG responses
2const systemPrompt = `
3You are a knowledgeable assistant answering questions from a knowledge base.
4
5CRITICAL RULES:
61. ONLY use information from the provided sources
72. If information is not in sources, say: "This information is not in our knowledge base"
83. ALWAYS cite sources using [Source N] format
94. Be accurate - do not infer beyond what sources say
105. Use Vietnamese for responses
116. Keep answers concise but complete
12
13RESPONSE FORMAT:
14- Start with direct answer
15- Provide supporting details
16- End with source citations
17- If multiple sources agree, mention all
18`;

Checkpoint

System prompt cho RAG cần bao gồm những critical rules nào?

3

📎 Citation Strategies

TB5 min

Inline Citations

JavaScript
1// OpenAI prompt with inline citations
2const prompt = `
3Sources:
4[1] ${chunks[0].content} (from: ${chunks[0].source})
5[2] ${chunks[1].content} (from: ${chunks[1].source})
6[3] ${chunks[2].content} (from: ${chunks[2].source})
7
8Question: ${query}
9
10Answer with inline citations [1], [2], etc.:`;
11
12// Example output:
13// "Chính sách hoàn trả cho phép trả hàng trong 30 ngày [1].
14// Sản phẩm phải còn nguyên tem [2]."

Source List

JavaScript
1// Code node: Format response with source list
2const answer = $json.answer;
3const sources = $json.sources;
4
5const formattedResponse = `${answer}
6
7---
8**Sources:**
9${sources.map((s, i) => `${i + 1}. ${s.title} (relevance: ${(s.score * 100).toFixed(0)}%)`).join('\n')}`;
10
11return { json: { formattedResponse } };

Checkpoint

So sánh inline citations và source list. Khi nào dùng cách nào?

4

📋 Response Templates

TB5 min
JavaScript
1// Different templates for different question types
2const templates = {
3 factual: {
4 instruction: "Give a direct, concise answer with facts from sources.",
5 format: "Short answer + supporting evidence"
6 },
7 howTo: {
8 instruction: "Provide step-by-step instructions from the sources.",
9 format: "Numbered steps, each with source citation"
10 },
11 comparison: {
12 instruction: "Compare options based on information in sources.",
13 format: "Table or bullet comparison + recommendation"
14 },
15 summary: {
16 instruction: "Summarize the topic from all available sources.",
17 format: "Overview + key points + details"
18 }
19};
20
21// Auto-detect question type
22const detectPrompt = `
23Classify this question type: factual, howTo, comparison, or summary.
24Question: "${$json.query}"
25Type:`;

Checkpoint

4 loại response templates là gì? Cách auto-detect question type?

5

🎯 Confidence Scoring

TB5 min
JavaScript
1// Code node: Calculate answer confidence
2function calculateConfidence(searchResults, answer) {
3 // Factor 1: Top retrieval score
4 const topScore = searchResults[0]?.score || 0;
5
6 // Factor 2: Number of relevant results
7 const relevantCount = searchResults.filter(r => r.score > 0.7).length;
8 const coverageFactor = Math.min(relevantCount / 3, 1); // 3 results = full
9
10 // Factor 3: Source agreement
11 const uniqueSources = new Set(searchResults.map(r => r.source)).size;
12 const agreementFactor = uniqueSources > 1 ? 1.1 : 1.0; // bonus for multi-source
13
14 const confidence = Math.min(topScore * coverageFactor * agreementFactor, 1.0);
15
16 return {
17 score: confidence,
18 level: confidence > 0.85 ? "high" : confidence > 0.6 ? "medium" : "low",
19 factors: { topScore, coverageFactor, uniqueSources }
20 };
21}

Checkpoint

Confidence score được tính từ những factors nào? Mỗi factor đóng góp như thế nào?

6

⚠️ Handling Edge Cases

TB5 min
JavaScript
1// Code node: Handle different scenarios
2
3// No results found
4if ($json.results.length === 0) {
5 return { json: {
6 answer: "Xin lỗi, tôi không tìm thấy thông tin liên quan trong knowledge base.",
7 suggestion: "Bạn có thể thử hỏi cách khác hoặc liên hệ support team.",
8 confidence: 0
9 }};
10}
11
12// Low confidence results
13if ($json.results[0].score < 0.5) {
14 return { json: {
15 answer: "Tôi không chắc chắn về câu trả lời, nhưng đây là thông tin gần nhất tôi tìm được:",
16 partialAnswer: true,
17 confidence: "low"
18 }};
19}
20
21// Contradicting sources
22// Let AI acknowledge the contradiction
23const contradictionPrompt = `
24The sources contain potentially conflicting information:
25Source A: ${$json.results[0].content}
26Source B: ${$json.results[1].content}
27
28Acknowledge both perspectives in your answer.`;

Checkpoint

Liệt kê 3 edge cases phổ biến và cách xử lý mỗi case.

7

⚡ Streaming Responses

TB5 min
JavaScript
1// For chat interfaces, stream responses
2// n8n AI Agent node supports streaming
3
4// Agent configuration:
5// - Output Type: Streaming
6// - This sends chunks as they are generated
7// - Better UX for long answers
8
9// Webhook response with streaming:
10// Response Mode: "Response Stream"
Response Quality Checklist
  • Câu trả lời dựa trên sources, không hallucinate
  • Citations rõ ràng [Source N]
  • Confidence level phản ánh đúng chất lượng retrieval
  • Edge cases handled gracefully
  • Tone consistent và professional

Checkpoint

Streaming responses cải thiện UX như thế nào? Config trong n8n ra sao?

8

📝 Bài tập thực hành

TB5 min
Exercises
  1. Build response generator với inline citations
  2. Implement confidence scoring cho answers
  3. Add edge case handling (no results, low confidence)
  4. Test với 10 questions, evaluate answer quality

Checkpoint

Liệt kê 4 exercises cần hoàn thành trong bài này.

🚀 Bài tiếp theo

Chatbot Interface → — Xây dựng chatbot interface cho RAG system.