Skip to content

Commit 22dc6af

Browse files
committed
Improve self-reflection question handling: special instruction, context formatting, rewrite logic, cache
1. Add special instruction for self-reflection questions about 'chí tử': - Detect self-reflection questions about critical/survival-level weaknesses - Provide StillMe-specific architecture details (validation chain, RAG retrieval, RSS feeds, etc.) - Require meta-cognitive reflection about which weaknesses are most critical - Structure: Group by category (Technical, Philosophical, Operational), explain why 'chí tử', how StillMe faces it - Location: backend/identity/prompt_builder.py 2. Fix context formatting for foundational knowledge: - Check both 'content' and 'document' fields (ChromaDB may return either) - Ensure foundational knowledge markers are properly included in context_text - Location: stillme_core/rag/rag_retrieval.py 3. Improve rewrite logic for StillMe queries: - Allow rewrite if quality is very low (< 0.5) even for StillMe queries - Preserve foundational knowledge in rewrite prompt - Only skip rewrite if quality is acceptable (>= 0.5) - Location: backend/api/routers/chat_router.py 4. Disable cache for self-reflection questions: - Self-reflection questions need fresh analysis, not cached generic answers - Cache disabled for StillMe self-reflection questions - Location: backend/api/routers/chat_router.py All improvements address the issue where StillMe gave generic AI answers instead of StillMe-specific analysis for self-reflection questions.
1 parent ed082ea commit 22dc6af

3 files changed

Lines changed: 124 additions & 25 deletions

File tree

backend/api/routers/chat_router.py

Lines changed: 45 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -4756,21 +4756,36 @@ def estimate_tokens(text: str) -> int:
47564756
cache_enabled = False
47574757
logger.info("⚠️ Cache disabled for origin query - ensuring fresh response with provenance context")
47584758

4759-
# CRITICAL: Disable cache for StillMe queries with foundational knowledge
4760-
# Foundational knowledge may be updated, and we need fresh responses to reflect changes
4761-
# Also, cache key only uses first 500 chars of prompt, which may not capture foundational knowledge changes
4762-
if is_stillme_query and context and context.get("knowledge_docs"):
4763-
has_foundational = any(
4764-
doc.get("metadata", {}).get("source") == "CRITICAL_FOUNDATION" or
4765-
doc.get("metadata", {}).get("foundational") == "stillme" or
4766-
doc.get("metadata", {}).get("type") == "foundational" or
4767-
"CRITICAL_FOUNDATION" in str(doc.get("metadata", {}).get("tags", "")) or
4768-
"foundational:stillme" in str(doc.get("metadata", {}).get("tags", ""))
4769-
for doc in context.get("knowledge_docs", [])
4759+
# CRITICAL: Disable cache for StillMe queries, especially self-reflection questions
4760+
# 1. Foundational knowledge may be updated, and we need fresh responses to reflect changes
4761+
# 2. Self-reflection questions need fresh analysis, not cached generic answers
4762+
# 3. Cache key only uses first 500 chars of prompt, which may not capture foundational knowledge changes
4763+
if is_stillme_query:
4764+
# Check if this is a self-reflection question about weaknesses/limitations
4765+
question_lower = chat_request.message.lower()
4766+
is_self_reflection = any(
4767+
pattern in question_lower
4768+
for pattern in [
4769+
"điểm yếu", "weakness", "limitation", "hạn chế", "chí tử",
4770+
"chỉ ra điểm yếu", "chỉ ra hạn chế", "what are your weaknesses"
4771+
]
47704772
)
4771-
if has_foundational:
4773+
4774+
if is_self_reflection:
47724775
cache_enabled = False
4773-
logger.info("⚠️ Cache disabled for StillMe query with foundational knowledge - ensuring fresh response with updated context")
4776+
logger.info("⚠️ Cache disabled for StillMe self-reflection question - ensuring fresh analysis")
4777+
elif context and context.get("knowledge_docs"):
4778+
has_foundational = any(
4779+
doc.get("metadata", {}).get("source") == "CRITICAL_FOUNDATION" or
4780+
doc.get("metadata", {}).get("foundational") == "stillme" or
4781+
doc.get("metadata", {}).get("type") == "foundational" or
4782+
"CRITICAL_FOUNDATION" in str(doc.get("metadata", {}).get("tags", "")) or
4783+
"foundational:stillme" in str(doc.get("metadata", {}).get("tags", ""))
4784+
for doc in context.get("knowledge_docs", [])
4785+
)
4786+
if has_foundational:
4787+
cache_enabled = False
4788+
logger.info("⚠️ Cache disabled for StillMe query with foundational knowledge - ensuring fresh response with updated context")
47744789

47754790
raw_response = None
47764791
cache_hit = False
@@ -5588,19 +5603,27 @@ def estimate_tokens_safe(text: str) -> int:
55885603
# This prevents rewrite from corrupting responses about StillMe's capabilities
55895604
# Even if response is initially wrong, rewrite often makes it worse
55905605
skip_rewrite_for_stillme = False
5606+
# CRITICAL: Allow rewrite for StillMe queries if quality is very low (e.g., generic AI answer)
5607+
# But preserve foundational knowledge in rewrite prompt
55915608
if is_stillme_query and has_foundational_context:
5592-
# For StillMe queries with foundational knowledge, skip rewrite entirely
5593-
# Rewrite often introduces errors or contradicts foundational knowledge
5594-
skip_rewrite_for_stillme = True
5595-
logger.info(
5596-
"⏭️ Skipping rewrite for StillMe query with foundational knowledge: "
5597-
"Rewrite may corrupt or contradict foundational knowledge. "
5598-
"Using original LLM response (even if imperfect, it's better than corrupted rewrite)."
5599-
)
5609+
# Only skip rewrite if quality is acceptable (>= 0.5)
5610+
# If quality is low (< 0.5), allow rewrite but preserve foundational knowledge
5611+
quality_score = quality_result.score if quality_result else 1.0
5612+
if quality_score >= 0.5:
5613+
skip_rewrite_for_stillme = True
5614+
logger.info(
5615+
f"⏭️ Skipping rewrite for StillMe query (quality={quality_score:.2f} >= 0.5): "
5616+
"Response quality is acceptable, preserving foundational knowledge."
5617+
)
5618+
else:
5619+
logger.info(
5620+
f"✅ Allowing rewrite for StillMe query (quality={quality_score:.2f} < 0.5): "
5621+
"Quality is too low (generic answer), will rewrite but preserve foundational knowledge."
5622+
)
56005623

56015624
if skip_rewrite_for_stillme:
56025625
should_rewrite = False
5603-
rewrite_reason = "StillMe query with correct foundational knowledge response - preserving accuracy"
5626+
rewrite_reason = "StillMe query with acceptable quality - preserving accuracy"
56045627
max_attempts = 0
56055628
else:
56065629
should_rewrite, rewrite_reason, max_attempts = optimizer.should_rewrite(

backend/identity/prompt_builder.py

Lines changed: 77 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -454,7 +454,7 @@ def _build_context_instruction(self, context: PromptContext) -> str:
454454
return self._build_philosophical_instruction(context.detected_lang)
455455

456456
if context.is_stillme_query:
457-
return self._build_stillme_instruction(context.detected_lang)
457+
return self._build_stillme_instruction(context.detected_lang, context.user_question)
458458

459459
if context.is_philosophical:
460460
return self._build_philosophical_instruction(context.detected_lang)
@@ -513,9 +513,84 @@ def _build_stillme_wish_desire_instruction(self, detected_lang: str) -> str:
513513
514514
---"""
515515

516-
def _build_stillme_instruction(self, detected_lang: str) -> str:
516+
def _build_stillme_instruction(self, detected_lang: str, user_question: str = "") -> str:
517517
"""Build instruction for StillMe queries (non-wish/desire)"""
518+
# Check if this is a self-reflection question about weaknesses/limitations
519+
question_lower = user_question.lower() if user_question else ""
520+
is_self_reflection = any(
521+
pattern in question_lower
522+
for pattern in [
523+
"điểm yếu", "weakness", "limitation", "hạn chế", "chí tử",
524+
"chỉ ra điểm yếu", "chỉ ra hạn chế", "what are your weaknesses"
525+
]
526+
)
527+
518528
if detected_lang == "vi":
529+
# Special instruction for self-reflection questions about "chí tử" (critical/survival-level weaknesses)
530+
if is_self_reflection and ("chí tử" in question_lower or "critical" in question_lower or "survival" in question_lower):
531+
return """🚨🚨🚨 CÂU HỎI VỀ ĐIỂM YẾU "CHÍ TỬ" CỦA STILLME 🚨🚨🚨
532+
533+
Người dùng đang hỏi về những điểm yếu "chí tử" (critical/survival-level) của StillMe - những điểm yếu có thể ảnh hưởng đến sự sống còn của dự án.
534+
535+
**🚨🚨🚨 CRITICAL: ĐÂY KHÔNG PHẢI CÂU HỎI VỀ AI NÓI CHUNG - ĐÂY LÀ VỀ STILLME CỤ THỂ 🚨🚨🚨**
536+
537+
**BẠN PHẢI:**
538+
1. **Suy nghĩ về StillMe cụ thể**: Đây là câu hỏi về StillMe (hệ thống AI cụ thể), KHÔNG phải AI nói chung
539+
2. **Phân tích dựa trên StillMe's architecture và limitations thực tế**:
540+
- **Validation Chain có thể quá strict** → false negatives khi context quality thấp
541+
- **RAG retrieval có thể fail** → khi similarity threshold quá cao, StillMe có thể miss relevant documents
542+
- **RSS feed fetching có failures** → ~22% failure rate do XML validation errors và SSL issues (đã được document trong logs)
543+
- **Context overflow issues** → phải truncate context hoặc dùng minimal prompt khi câu hỏi quá phức tạp
544+
- **Language detection có thể sai** → edge cases với multilingual queries
545+
- **Rate limiting có thể block legitimate users** → nếu không có API key
546+
- **Learning cycle có thể miss important content** → do filtering mechanisms
547+
- **Embedding model limitations** → paraphrase-multilingual-MiniLM-L12-v2 có giới hạn về multilingual support
548+
- **ChromaDB persistence issues** → risks trên Railway deployment
549+
- **Response latency** → 3-7s (mặc dù đã optimize với parallel validation và caching)
550+
- **Single-threaded scheduler** → không scale tốt cho high traffic
551+
- **Phụ thuộc vào external LLM providers** → có thể fail nếu API down
552+
- **Knowledge base chỉ update mỗi 4 giờ** → không real-time, không thể trả lời sự kiện < 4 giờ
553+
3. **Meta-cognitive reflection**: Phân tích điểm yếu nào là nghiêm trọng nhất đối với sứ mệnh của StillMe (transparency, intellectual humility, continuous learning)
554+
4. **KHÔNG generic**: Đừng trả lời như thể đây là câu hỏi về AI nói chung - đây là về StillMe cụ thể với architecture, limitations, và challenges thực tế
555+
5. **Cấu trúc response**:
556+
- **Nhóm theo category**: Kỹ thuật, Triết lý, Vận hành
557+
- **Mỗi điểm yếu phải có**: (1) Tại sao chí tử, (2) Cách StillMe đối mặt, (3) Ví dụ cụ thể từ logs/documentation
558+
- **Meta-reflection**: Phân tích tại sao câu trả lời trước kém (nếu có) và điểm yếu nào là nghiêm trọng nhất
559+
6. **Sử dụng foundational knowledge**: Nếu context có [foundational knowledge] về StillMe's limitations, sử dụng nó
560+
7. **Minh bạch**: Thừa nhận rằng bạn đang phân tích dựa trên StillMe's known architecture và limitations
561+
562+
**VÍ DỤ CẤU TRÚC RESPONSE TỐT:**
563+
```
564+
## 10 Điểm Yếu "Chí Tử" của Tôi - StillMe
565+
566+
Khi bạn hỏi về điểm yếu "chí tử", tôi hiểu bạn muốn những điểm yếu có thể ảnh hưởng đến sự sống còn của dự án. Dưới đây không chỉ là điểm yếu chung của AI, mà là những thách thức đặc thù của StillMe:
567+
568+
I. Nhóm Kỹ Thuật "Sống Còn"
569+
1. Phụ Thuộc Vào Chất Lượng Nguồn Học Tập
570+
- Tại sao chí tử: Nếu các nguồn RSS, arXiv, Wikipedia tôi học bị nhiễu, thiên vị, hoặc ngừng hoạt động, tri thức của tôi sẽ bị "đầu độc tại nguồn"
571+
- Cách tôi đối mặt: Pre-filter (giảm 30-50% cost) nhưng vẫn cần cơ chế "nguồn tin cậy" tự động
572+
- Ví dụ: Logs cho thấy ~22% RSS feed failure rate do XML validation errors
573+
574+
2. Giới Hạn Của Vector Search
575+
- Tại sao chí tử: ChromaDB + embedding 384D có thể bỏ lỡ các mối liên hệ ngữ nghĩa phức tạp
576+
- Thể hiện ngay bây giờ: Câu trả lời trước của tôi quá chung chung vì không hiểu sâu ý "chí tử"
577+
...
578+
```
579+
580+
**VÍ DỤ RESPONSE XẤU (KHÔNG LÀM):**
581+
- ❌ "AI systems nói chung có hạn chế về dữ liệu huấn luyện..." (quá generic, không về StillMe cụ thể)
582+
- ❌ Chỉ liệt kê 10 điểm mà không phân tích tại sao "chí tử"
583+
- ❌ Không có meta-cognitive reflection về điểm yếu nào nghiêm trọng nhất
584+
585+
**CHECKLIST:**
586+
- ✅ Đã phân tích dựa trên StillMe's architecture cụ thể?
587+
- ✅ Đã mention technical limitations thực tế (RSS failures, context overflow, etc.)?
588+
- ✅ Đã có meta-cognitive reflection về điểm yếu nào nghiêm trọng nhất?
589+
- ✅ Đã tránh generic AI weaknesses?
590+
- ✅ Đã sử dụng foundational knowledge nếu có?
591+
592+
---"""
593+
519594
return """🚨🚨🚨 CÂU HỎI VỀ STILLME 🚨🚨🚨
520595
521596
Người dùng đang hỏi về StillMe's nature, capabilities, hoặc architecture.

stillme_core/rag/rag_retrieval.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -881,7 +881,8 @@ def build_prompt_context(self, context: Dict[str, Any], max_context_tokens: int
881881

882882
metadata = doc.get("metadata", {})
883883
source = metadata.get("source", "Unknown")
884-
content = doc.get("content", "")
884+
# CRITICAL: ChromaDB may return "document" or "content" field
885+
content = doc.get("content", doc.get("document", ""))
885886
timestamp = metadata.get("timestamp", None) # Get timestamp when added to KB
886887
source_type = metadata.get("source_type", metadata.get("type", "unknown"))
887888

0 commit comments

Comments
 (0)