💬 Response Generation
🎯 Mục tiêu bài học
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.
📊 Response Quality Factors
Checkpoint
5 yếu tố ảnh hưởng đến response quality là gì?
📝 Response Generation Prompt
1// System prompt for high-quality RAG responses2const systemPrompt = `3You are a knowledgeable assistant answering questions from a knowledge base.45CRITICAL RULES:61. ONLY use information from the provided sources72. If information is not in sources, say: "This information is not in our knowledge base"83. ALWAYS cite sources using [Source N] format94. Be accurate - do not infer beyond what sources say105. Use Vietnamese for responses116. Keep answers concise but complete1213RESPONSE FORMAT:14- Start with direct answer15- Provide supporting details16- End with source citations17- If multiple sources agree, mention all18`;Checkpoint
System prompt cho RAG cần bao gồm những critical rules nào?
📎 Citation Strategies
Inline Citations
1// OpenAI prompt with inline citations2const 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})78Question: ${query}910Answer with inline citations [1], [2], etc.:`;1112// 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
1// Code node: Format response with source list2const answer = $json.answer;3const sources = $json.sources;45const formattedResponse = `${answer}67---8**Sources:**9${sources.map((s, i) => `${i + 1}. ${s.title} (relevance: ${(s.score * 100).toFixed(0)}%)`).join('\n')}`;1011return { json: { formattedResponse } };Checkpoint
So sánh inline citations và source list. Khi nào dùng cách nào?
📋 Response Templates
1// Different templates for different question types2const 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};2021// Auto-detect question type22const 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?
🎯 Confidence Scoring
1// Code node: Calculate answer confidence2function calculateConfidence(searchResults, answer) {3 // Factor 1: Top retrieval score4 const topScore = searchResults[0]?.score || 0;5 6 // Factor 2: Number of relevant results7 const relevantCount = searchResults.filter(r => r.score > 0.7).length;8 const coverageFactor = Math.min(relevantCount / 3, 1); // 3 results = full9 10 // Factor 3: Source agreement11 const uniqueSources = new Set(searchResults.map(r => r.source)).size;12 const agreementFactor = uniqueSources > 1 ? 1.1 : 1.0; // bonus for multi-source13 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?
⚠️ Handling Edge Cases
1// Code node: Handle different scenarios23// No results found4if ($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: 09 }};10}1112// Low confidence results13if ($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}2021// Contradicting sources22// Let AI acknowledge the contradiction23const contradictionPrompt = `24The sources contain potentially conflicting information:25Source A: ${$json.results[0].content}26Source B: ${$json.results[1].content}2728Acknowledge both perspectives in your answer.`;Checkpoint
Liệt kê 3 edge cases phổ biến và cách xử lý mỗi case.
⚡ Streaming Responses
1// For chat interfaces, stream responses2// n8n AI Agent node supports streaming34// Agent configuration:5// - Output Type: Streaming6// - This sends chunks as they are generated7// - Better UX for long answers89// Webhook response with streaming:10// Response Mode: "Response Stream"- 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?
📝 Bài tập thực hành
- Build response generator với inline citations
- Implement confidence scoring cho answers
- Add edge case handling (no results, low confidence)
- 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.
