Skip to content

ntd25022006q/bookmind-socratic-agent

Repository files navigation

VNU BookMind Socratic Agent v42

No Fabrication

VNU BookMind Socratic
Hệ thống gợi ý đọc sách chủ động — 6 tác nhân AI, 4 nguồn VNU LIC xác thực

LangGraph Ollama FastAPI VNU LIC Render Vercel


"AI gợi ý và đặt câu hỏi, con người đọc và trả lời."

BookMind Socratic không phải chatbot. Không tóm tóm sách. Không trả lời sẵn. Mục đích duy nhất — buộc độc giả tư duy sâu khi đọc sách.

Ba nguyên tắc không thỏa hiệp

# Nguyên tắc Ý nghĩa
1 Không bịa sách Mọi tài liệu đều từ 4 nguồn VNU LIC xác thực. Không Google Books, không DOI, không URL giả.
2 Không tóm tóm hộ AI đặt câu hỏi Socrates, độc giả tự tìm câu trả lời trong sách.
3 Không trích dẫn suy nghĩ AI suy nghĩ sâu 1000+ câu, nhưng nhật ký tư duy chỉ hiện trong console. Báo cáo cuối là LaTeX học thuật sạch.

Kiến trúc 6 Tác Nhân

Guardrail → Profiler → Recommender → Questioner → Critic → Reporter
  (Phòng Vệ)   (Hồ Sơ)    (Tìm Kiếm)   (Socrates)   (Phản Biện)   (Báo Cáo)
# Tác Nhân Chức Năng Mô Hình Ollama
1 Lớp Phòng Vệ Kiểm tra câu hỏi có hợp lệ (tư vấn sách) hay không gemma4:31b
2 Phân Tích Hồ Sơ Phân tích chân dung độc giả 5 chiều từ câu hỏi nemotron-3-ultra
3 Tìm Kiếm Thư Viện VNU Tìm kiếm 4 nguồn VNU LIC + RRF Fusion scoring + RAG v5 nemotron-3-ultra
4 Câu Hỏi Socrates 3 câu hỏi phản biện gắn sách cụ thể từ VNU LIC gemma4:31b
5 Phản Biện Phát hiện thiên kiến, 3 checkpoint tư duy gpt-oss:120b
6 Biên Soạn Báo Cáo Báo cáo LaTeX 7 section, sơ đồ Mermaid nemotron-3-ultra

4 Nguồn VNU LIC (API công khai)

Nguồn Loại Mô tả
Bookworm (vnu.edu.vn) Số hóa Kỹ thuật số ⭐ PRIMARY — 9 kết quả, 7 có PDF
Repository DSpace Luận văn, bài báo khoa học Bổ sung thông tin
OPAC Koha Catalog thư viện vật lý Tìm kiếm sách vật lý
LIC Portal / Primo Cổng hợp tìm kiếm Tìm kiếm mở rộng

🚀 Quick Start

1. Clone và cấu hình

git clone <repo-url>
cd bookmind-socratic-agent
cp .env.example .env
# Sửa OLLAMA_API_KEY trong .env
pip install -r requirements.txt

2. Chạy server

python main.py --server
# Server chạy tại http://localhost:8000

3. Sử dụng

Mở trình duy → nhập chủ đề sách → bấm Chạy Phân Tích → xem 6 tác nhân AI chạy tuần tự.


📊 Cấu trúc Project

bookmind-socratic-agent/
├── config.py                    # Model configs, timeouts, fallback chains
├── server.py                   # FastAPI backend + SSE streaming
├── main.py                     # CLI entry point
├── requirements.txt             # Python dependencies
├── render.yaml                  # Render deployment config
├── vercel.json                  # Vercel deployment config
├── frontend/
│   ├── index.html             # Single-page app
│   ├── app.js                # Frontend JS (SSE handling)
│   ├── style.css             # Styles
│   └── lib/                   # Static assets (FontAwesome, marked.js, mermaid.js)
├── src/
│   ├── state.py              # ResearchState TypedDict
│   ├── graph.py              # LangGraph pipeline definitions
│   ├── agents/
│   │   ├── guardrail_agent.py    # Kiểm tra câu hỏi
│   │   ├── profiler_agent.py     # Phân tích hồ sơ
│   │   ├── recommender_agent.py # Tìm kiếm VNU LIC + RRF
│   │   ├── questioner_agent.py  # Câu hỏi Socrates
│   │   ├── critic_agent.py     # Phản biện
│   │   └── reporter_agent.py   # Biên soạn báo cáo LaTeX
│   ├── utils/
│   │   ├── llm_factory.py      # LLM factory + fallback chain
│   │   ├── cleaner.py          # URL whitelist, CJK clean, artifact removal
│   │   ├── display.py          # Rich console display
│   │   ├── link_validator.py   # HTTP link validation
│   │   └── vnu_lic_links.py   # VNU LIC link helpers
│   ├── tools/
│   │   ├── vnu_lic_api.py       # 4-source VNU library API
│   │   └── rag_tools.py         # RAG v5 (15 algorithms)
│   ├── rag/                     # RAG algorithms (BM25, TF-IDF, Dense, MMR, etc.)
│   │   ├── adaptive_retriever.py
│   │   ├── cross_encoder.py
│   │   └── ...
│   ├── middleware/
│   │   ├── error_handler.py     # Structured error responses
│   │   ├── rate_limiter.py      # Rate limiting
│   │   └── request_logger.py     # Request logging
│   └── data/raw/                 # VNU LIC knowledge base (markdown)

🔧 Cấu hình Môi trường

Biến bắt buộc (.env)

Biến Mô tả Giá trị mẫu
OLLAMA_API_KEY API key Ollama Cloud Từ ollama.com
OLLAMA_BASE_URL Base URL API https://ollama.com/v1
DISABLE_SSL_VERIFY Tắt SSL verify (deploy cloud) true
VNU_COOKIE_* Cookies VNU LIC (tuỳ chọn) Xem .env.example

Mô hình AI (Free trên Ollama Cloud)

Agent Mô hình chính Fallback
Guardrail gemma4:31b (1.4s) gpt-oss:120b, nemotron-3-nano:30b
Profiler nemotron-3-ultra (2.8s) gemma4:31b, gpt-oss:120b
Recommender nemotron-3-ultra (2.8s) gemma4:31b, gpt-oss:120b
Questioner gemma4:31b (1.4s) gpt-oss:120b, nemotron-3-nano:30b
Critic gpt-oss:120b (1.8s) gemma4:31b, nemotron-3-nano:30b
Reporter nemotron-3-ultra (2.8s) gemma4:31b, gpt-oss:120b

Tất cả 7 mô hình đã được verify hoạt động (2026-07-19). API key Ollama Cloud miễn phí hỗ trợ nhiều model hơn (minimax-m3, gpt-oss:20b, v.v.).


🛡️ Chống Phòng Chống Lỗi (Anti-Fabrication)

1. URL Whitelist Post-Processing

Mọi URL trong báo cáo được kiểm tra chống domain VNU LIC. URL không hợp lệ → xóa hoặc thay bằng link tìm kiếm an toàn.

2. LLM Hallucination Defense

  • Nhiều class để phát hiện thiên kiến xác nhận
  • Post-hoc URL injection từ dữ liệu API thực (LLM-proof)
  • Safety clean: strip thinking/console leakage, fix malformed URLs, remove forbidden sources

3. Kiểm tra chéo nguồn

  • Citation verifier (RAG) kiểm tra trích dẫn trong báo cáo
  • Table query-title remover: xóa hàng bảng có tiêu đề là câu hỏi
  • CJK character stripping (tiếng Nhật, Trung)

4. Error Classification

Loại Xử lý
Model not found 404 Fallback chain tự động
Timeout 408 Thử model khác
Rate limit 429 Chờ và thử lại
Auth 401/403 Báo lỗi rõ ràng
Network - Báo lỗi thân thiện

🔀 RAG v5 — 15 Thuật Toán

Hệ thống RAG nâng cao với 15 thuật toán:

  1. BM25 — Vietnamese-optimized Okapi BM25
  2. TF-IDF Cosine — Normalized TF với cosine similarity
  3. Dense Semantic — TF-IDF → dense vectors (random projection, JL lemma)
  4. RRF — Weighted multi-signal fusion
  5. Query Expansion — Vietnamese synonym + English cross-lingual
  6. Query Decomposition — Complex query → sub-queries
  7. Intent Classification — Intent-aware strategy routing
  8. Cross-Encoder — Heuristic pair scoring
  9. Contextual Compression — Sentence-level relevance
  10. MMR Reranking — Diversity-aware selection
  11. Relevance Feedback — Rocchio query expansion
  12. Citation Verification — Claim-level source verification
  13. Adaptive Retrieval v4 — Complexity × intent strategy
  14. Smart Chunking — Section-boundary-aware splitting
  15. API-RAG Bridge — Real-time API results → RAG knowledge base

📊 Đánh Giá Hiệu Suất (Tested 2026-07-19)

Pipeline Test (Flash Mode, 5/6 agents, không có Recommender VNU search)

guardrail:   3.8s  ✅  (was 13.2s — 3.5x faster)
profiler:    19.8s ✅  (profile: 751 chars)
questioner:  3.5s  ✅  (was 19.7s — 5.6x faster)
critic:      25.5s ✅  (analysis: 6899 chars)
reporter:    29.7s ✅  (report: 12,081 chars, has \section LaTeX, has VNU links)
────────────────────────
TOTAL:       ~82s  ✅ (was timeout)

API Health Check

{"status": "alive", "version": "42.0", "architecture": "6-agent", "rss_mb": 0}

Ollama Cloud Model Test (All 7 models)

OK  guardrail    model=gemma4:31b          0.8s
OK  profiler     model=nemotron-3-ultra          1.3s
OK  recommender  model=gpt-oss:120b              1.6s
OK  questioner   model=gemma4:31b                0.7s
OK  critic       model=gpt-oss:120b              0.9s
OK  reporter     model=nemotron-3-ultra          1.6s
OK  chat         model=gemma4:31b                0.9s

VNU LIC Bookworm Search

Bookworm: 9 kết quả (public API), 7/9 có PDF link
Repository: timeout (public fallback)
OPAC Koha: 0 kết quả (public)
LIC Portal: timeout (public fallback)

🏗️ API Endpoints

Endpoint Method Mô tả
/ GET Frontend SPA
/api/health GET Health check
/api/run POST Main pipeline — SSE streaming
/api/run_sync POST Pipeline sync (fallback)
/api/chat POST Chat follow-up
/api/unlock POST Force unlock pipeline
/api/logs GET Recent request logs

SSE Event Types (POST /api/run)

Event Mô tả
node_start Agent bắt đầu
agent_thinking Nhật ký tư duy (real-time)
agent_end Agent hoàn thành + stats
pipeline_complete Pipeline hoàn tất + report + books + questions
error Lỗi (thân thiện tiếng Việt)
ping Heartbeat (elapsed time)
done_sentinel Kết thúc stream

🚢 Deployment

Render (Backend)

  1. Kết nối GitHub repo → Render
  2. Build Command: pip install -r requirements.txt
  3. Start Command: python main.py --server
  4. Environment Variables: OLLAMA_API_KEY, OLLAMA_BASE_URL
  5. Health Check: /api/health

Vercel (Frontend)

  1. Kết nối GitHub repo → Vercel
  2. Root Directory: frontend/
  3. Framework Preset: Node.js (static export)
  4. Environment Variables: none needed (frontend calls backend API)

🔄 Cập Nhật Gần Đây (v42 — 2026-07-19)

Performance Optimization

  • Guardrail 3.8s (was 13.2s): Giảm thinking từ 25-35 câu → 3-5 câu (flash mode)
  • Questioner 3.5s (was 19.7s): Tương tự — thinking giảm 10x
  • Reporter hoàn thành (was timeout): Tăng max_tokens 2500→4000
  • Tổng pipeline ~82s (5 agents) — trước đó timeout ở 300s

Bug Fixes

  • ainvoke_with_streaming_fallback: Fix double timeout wrapper
  • QueueCallbackHandler: Fix deprecated get_event_loop()get_running_loop()
  • Reporter parse_agent_json: Fix empty detailed_report fallback
  • VNU API timeouts: Giảm public HTTP timeout 15→10s, futures 20→12s
  • httpx resource management: Document follow_redirects=True for ollama.com
  • AGENT_DISPLAY: Thêm "recommender" (trước chỉ có "retriever")

Code Quality

  • URL whitelist post-processing (anti-fabrication)
  • CJK character stripping
  • Markdown artifact cleaning
  • LLM artifact removal ("As an AI", etc.)
  • Structured error responses (ErrorCode enum)
  • Rate limiting (per-endpoint)
  • Pipeline lock with stale detection
  • Graceful degradation (every agent has fallback)

📄 License

MIT

About

Resources

License

Stars

0 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors