### Setup Script / Makefile for Environment Initialization Source: https://github.com/sadivo/taiwan-law-rag-mcp/blob/main/plan/phase13_ux_optimization.md This script or Makefile automates the environment setup process. It ensures the virtual environment is present, installs dependencies, copies the example environment file, and performs a health check. ```bash # 1. 確認 .venv 存在,否則執行 uv venv # 2. 執行 uv sync # 3. 若 .env 不存在,從 .env.example 複製並提示填寫 # 4. 執行 uv run main.py check 驗證設定 ``` -------------------------------- ### Install and Initialize Environment Source: https://context7.com/sadivo/taiwan-law-rag-mcp/llms.txt Steps to set up the development environment, including installing dependencies and configuring API keys. ```APIDOC ## Install and Initialize Environment ### Environment Setup and Service Startup Use `uv` to manage dependencies and execute all operations through a unified CLI entry point. ```bash # Install uv (if not already installed) curl -LsSf https://astral.sh/uv/install.sh | sh # Clone the repository and navigate to the directory git clone cd taiwan-law-rag # Initialize environment (create venv, install dependencies, create .env) uv run scripts/setup.py # Edit .env, set provider (recommended configuration without GPU) cat > .env << 'EOF' EMBEDDING_PROVIDER=voyageai RERANKING_PROVIDER=local PROVIDER_API_KEY=pa-yourVoyageAIkey GENERATION_PROVIDER=openai GENERATION_API_KEY=sk-... GENERATION_MODEL_NAME=gpt-4o-mini API_HOST=127.0.0.1 API_PORT=8073 EOF # First-time use: create FAISS vector index and BM25 index uv run main.py index # Output: # [1/3] Loading legal data... # [2/3] Creating vector index (FAISS)... # [3/3] Creating keyword index (BM25)... # Index rebuild complete, processed 12345 chunks. # Start FastAPI service (default http://127.0.0.1:8073) uv run main.py serve # Output: # Taiwan Law RAG — http://127.0.0.1:8073 # ✓ Embedding : voyageai:voyage-3.5-lite # ✓ Reranking : local:Qwen3-Reranker-4B # ✓ Generation : openai:gpt-4o-mini ``` ``` -------------------------------- ### Install uv and Setup Environment Source: https://context7.com/sadivo/taiwan-law-rag-mcp/llms.txt Installs the uv dependency manager and sets up the project environment, including creating a virtual environment and installing dependencies. It also configures environment variables for AI providers. ```bash # 安裝 uv(若尚未安裝) curl -LsSf https://astral.sh/uv/install.sh | sh # 複製程式碼並進入目錄 git clone cd taiwan-law-rag # 初始化環境(建立 venv、安裝依賴、建立 .env) uv run scripts/setup.py # 編輯 .env,設定 provider(無 GPU 推薦配置) cat > .env << 'EOF' EMBEDDING_PROVIDER=voyageai RERANKING_PROVIDER=local PROVIDER_API_KEY=pa-你的VoyageAI金鑰 GENERATION_PROVIDER=openai GENERATION_API_KEY=sk-... GENERATION_MODEL_NAME=gpt-4o-mini API_HOST=127.0.0.1 API_PORT=8073 EOF ``` -------------------------------- ### Node.js Environment Setup (Bash) Source: https://github.com/sadivo/taiwan-law-rag-mcp/blob/main/plan/VIBE_CODING_PROMPT.md Initializes a new Node.js project, installs necessary packages including the MCP SDK and node-fetch, and configures TypeScript compilation. ```bash cd ../mcp-server npm init -y npm install @modelcontextprotocol/sdk node-fetch npm install -D typescript @types/node npx tsc --init ``` -------------------------------- ### Windows Setup Script Source: https://github.com/sadivo/taiwan-law-rag-mcp/blob/main/plan/VIBE_CODING_PROMPT.md Batch script for initializing the project on Windows, including environment checks and setup procedures. ```batch # scripts/setup.bat # Windows 初始化 # 環境檢查 ``` -------------------------------- ### Service Startup Output Example Source: https://github.com/sadivo/taiwan-law-rag-mcp/blob/main/plan/log/phase13_ux_optimization.md This example demonstrates the expected output upon successful service startup, including the RAG service URL and the status of its components (Embedding, Reranking, Generation). ```text Taiwan Law RAG — http://127.0.0.1:8073 ✓ Embedding : local:Qwen3-Embedding-4B ✓ Reranking : local:Qwen3-Reranker-4B ✗ Generation : ollama:qwen3:8b (unreachable at http://localhost:11434) ``` -------------------------------- ### Copy Environment Example Source: https://github.com/sadivo/taiwan-law-rag-mcp/blob/main/docs/INSTALLATION.md Copies the example environment file to a new file named .env. This file will store your project's configuration settings. ```bash cp .env.example .env ``` -------------------------------- ### Start FastAPI Service (Default Configuration) Source: https://context7.com/sadivo/taiwan-law-rag-mcp/llms.txt Starts the FastAPI service using the configured providers in the .env file. The service listens on the specified host and port, initializing all providers. ```bash # 啟動 FastAPI 服務(預設 http://127.0.0.1:8073) uv run main.py serve # 輸出: # Taiwan Law RAG — http://127.0.0.1:8073 # ✓ Embedding : voyageai:voyage-3.5-lite # ✓ Reranking : local:Qwen3-Reranker-4B # ✓ Generation : openai:gpt-4o-mini # API_HOST=127.0.0.1 # API_PORT=8073 ``` -------------------------------- ### MCP Server Main Entry Point (TypeScript) Source: https://github.com/sadivo/taiwan-law-rag-mcp/blob/main/plan/VIBE_CODING_PROMPT.md Main TypeScript file for the MCP server, responsible for registering tools and starting the server. It handles application setup and configuration. ```typescript // mcp-server/src/index.ts // MCP Server 主程式 // 工具註冊 ``` -------------------------------- ### Install Ollama and Download Model Source: https://github.com/sadivo/taiwan-law-rag-mcp/blob/main/docs/INSTALLATION.md Installs Ollama for local LLM usage and downloads the default Qwen3:8b model. This is only required if using Ollama as the generation provider. ```bash # macOS / Linux curl -fsSL https://ollama.com/install.sh | sh # Download default model ollama pull qwen3:8b ``` -------------------------------- ### Start the Service Source: https://github.com/sadivo/taiwan-law-rag-mcp/blob/main/plan/log/phase13_ux_optimization.md Use this command to launch the FastAPI application for serving RAG functionalities. ```bash uv run main.py serve ``` -------------------------------- ### Start FastAPI Server (Bash) Source: https://github.com/sadivo/taiwan-law-rag-mcp/blob/main/plan/VIBE_CODING_PROMPT.md Command to start the FastAPI web server using uvicorn. It specifies the host and port for the application. ```bash uvicorn main:app --host 0.0.0.0 --port 8000 ``` -------------------------------- ### Environment Configuration Example Source: https://github.com/sadivo/taiwan-law-rag-mcp/blob/main/plan/log/phase8_langchain_provider_and_mcp_integration.md Configure your environment variables to specify the embedding and reranking providers, model names, and API keys. This setup is crucial for the RAG system's operation. ```dotenv EMBEDDING_PROVIDER=voyageai EMBEDDING_MODEL_NAME=voyage-3.5-lite RERANKING_PROVIDER=local PROVIDER_API_KEY= ``` -------------------------------- ### Semantic Search API Example Source: https://github.com/sadivo/taiwan-law-rag-mcp/blob/main/docs/USAGE.md This example demonstrates how to perform a semantic search using the API. The query 'overtime pay regulations' will be automatically translated to '加班費規定' internally before searching. ```bash curl -X POST http://127.0.0.1:8073/search/semantic \ -H "Content-Type: application/json" \ -d '{"query": "overtime pay regulations", "top_k": 3}' # 內部自動翻譯為「加班費規定」再進行搜尋 ``` -------------------------------- ### Start Service Directly with uv Source: https://github.com/sadivo/taiwan-law-rag-mcp/blob/main/docs/INSTALLATION.md Starts the FastAPI application directly using uv. This is an alternative method to launch the service. ```bash uv run python-rag/main.py ``` -------------------------------- ### Start FastAPI Service (Local GPU Mode) Source: https://context7.com/sadivo/taiwan-law-rag-mcp/llms.txt Starts the FastAPI service with local providers for embedding and reranking, suitable for systems with a GPU. The generation provider can be configured for local Ollama models. ```bash # 有 GPU 的本地模式(不需要任何 API 金鑰) EMBEDDING_PROVIDER=local \ RERANKING_PROVIDER=local \ GENERATION_PROVIDER=ollama \ GENERATION_MODEL_NAME=qwen3:8b \ uv run main.py serve # 預期輸出(Generation 無法連線時仍啟動): # Taiwan Law RAG — http://127.0.0.1:8073 # ✓ Embedding : local:Qwen3-Embedding-4B # ✓ Reranking : local:Qwen3-Reranker-4B # ✗ Generation : ollama:qwen3:8b (unreachable at http://localhost:11434) # INFO: Uvicorn running on http://127.0.0.1:8073 (Press CTRL+C to quit) ``` -------------------------------- ### CLI: serve Source: https://github.com/sadivo/taiwan-law-rag-mcp/blob/main/docs/USAGE.md Starts the FastAPI service with uvicorn, listening on http://127.0.0.1:8073 by default. ```APIDOC ## CLI: serve — Start FastAPI service ### Description Starts the FastAPI service with uvicorn, listening on http://127.0.0.1:8073 by default. ### Command `uv run main.py serve` ### Expected Output (All providers normal) ``` Taiwan Law RAG — http://127.0.0.1:8073 ✓ Embedding : local:Qwen3-Embedding-4B ✓ Reranking : local:Qwen3-Reranker-4B ✓ Generation : ollama:qwen3:8b INFO: Uvicorn running on http://127.0.0.1:8073 (Press CTRL+C to quit) ``` ### Expected Output (Generation provider unreachable) ``` Taiwan Law RAG — http://127.0.0.1:8073 ✓ Embedding : local:Qwen3-Embedding-4B ✓ Reranking : local:Qwen3-Reranker-4B ✗ Generation : ollama:qwen3:8b (unreachable at http://localhost:11434) INFO: Uvicorn running on http://127.0.0.1:8073 (Press CTRL+C to quit) ``` ``` -------------------------------- ### Startup Summary Example Source: https://github.com/sadivo/taiwan-law-rag-mcp/blob/main/plan/phase13_ux_optimization.md This output provides a quick overview of the RAG system's status upon startup, indicating the health of different providers like Embedding, Reranking, and Generation. ```bash Taiwan Law RAG — http://127.0.0.1:8073 ✓ Embedding : local:bge-m3 ✓ Reranking : local:bge-reranker ✗ Generation : ollama (unreachable at http://localhost:11434) ``` -------------------------------- ### Create and Sync Virtual Environment Source: https://github.com/sadivo/taiwan-law-rag-mcp/blob/main/docs/INSTALLATION.md Creates a new virtual environment using uv and installs all project dependencies listed in the environment. ```bash # Create virtual environment uv venv # Install all dependencies uv sync ``` -------------------------------- ### Install uv Package Manager Source: https://github.com/sadivo/taiwan-law-rag-mcp/blob/main/docs/INSTALLATION.md Installs the uv package and virtual environment manager. This is a prerequisite for managing Python dependencies. ```bash curl -LsSf https://astral.sh/uv/install.sh | sh ``` -------------------------------- ### Build MCP Server Source: https://context7.com/sadivo/taiwan-law-rag-mcp/llms.txt Navigate to the mcp-server directory and run these commands to install dependencies and build the server, generating the dist/index.js file. ```bash cd mcp-server npm install npm run build ``` -------------------------------- ### Query Rewriting Examples Source: https://github.com/sadivo/taiwan-law-rag-mcp/blob/main/plan/OPTIMIZATION_PLAN.md Examples of rewriting user queries to be more suitable for retrieval, transforming vague questions into specific search terms. ```text - "How to calculate overtime pay?" → "Overtime pay calculation method Extended working hours wage standards" - "What to do if fired by the boss?" → "Employer termination of labor contract Severance pay Notice period" ``` -------------------------------- ### Phase 2 Test Script Output Example Source: https://github.com/sadivo/taiwan-law-rag-mcp/blob/main/plan/log/phase2_walkthrough.md Example output from the Phase 2 testing script, showing test progression, mock data creation, and successful chunk generation with metadata. It confirms the correct parsing and enrichment of law data. ```bash Testing normalize_law_name... Testing normalize_article_no... Creating mock law data... Testing loader... Testing chunker... Generated 3 chunks. ID: 勞動基準法_第 1 條 Metadata: {'law_name': '勞動基準法', 'law_level': '法律', 'law_category': '行政>勞動部', 'law_url': 'https://law.moj.gov.tw/123', 'article_no': '第 1 條', 'chapter': '第一章 總則', 'modified_date': '20231201', 'is_abolished': False, 'has_english': True, 'aliases': ['勞基法']} ... ✅ ALL TESTS PASSED! ``` -------------------------------- ### Install PyTorch with CUDA Support Source: https://github.com/sadivo/taiwan-law-rag-mcp/blob/main/plan/log/phase7_gpu_issue.md Use this command to install a specific version of PyTorch with CUDA 12.1 support. Ensure your environment is clean to avoid caching issues. ```bash uv pip install torch==2.1.2+cu121 --extra-index-url https://download.pytorch.org/whl/cu121 ``` -------------------------------- ### Example Claude Desktop Usage with MCP Tool Source: https://github.com/sadivo/taiwan-law-rag-mcp/blob/main/plan/VIBE_CODING_PROMPT.md Demonstrates how a user query triggers the semantic_search MCP tool with specified parameters. ```typescript semantic_search({ query: "加班費計算規定", top_k: 10 }) ``` -------------------------------- ### Configure Environment Variables for Providers Source: https://github.com/sadivo/taiwan-law-rag-mcp/blob/main/README.md Set up your API keys and provider preferences in the .env file. The example shows configuration for VoyageAI embeddings and OpenAI generation without a GPU. ```env EMBEDDING_PROVIDER=voyageai RERANKING_PROVIDER=local PROVIDER_API_KEY=你的 VoyageAI 金鑰 GENERATION_PROVIDER=openai GENERATION_API_KEY=sk-... ``` -------------------------------- ### Ensure Ollama Service is Running Source: https://github.com/sadivo/taiwan-law-rag-mcp/blob/main/docs/INSTALLATION.md Starts the Ollama service in the background. This is a troubleshooting step if the Generation provider shows as 'unreachable' when using Ollama. ```bash ollama serve ``` -------------------------------- ### Configure Local GPU Providers Source: https://github.com/sadivo/taiwan-law-rag-mcp/blob/main/README.md Example .env configuration for using local embedding and generation providers when a GPU is available. Note that local embedding can be time-consuming. ```env EMBEDDING_PROVIDER=local RERANKING_PROVIDER=local GENERATION_PROVIDER=ollama GENERATION_MODEL_NAME=qwen3:8b ``` -------------------------------- ### Verify Environment (without starting FastAPI) Source: https://github.com/sadivo/taiwan-law-rag-mcp/blob/main/plan/log/phase13_ux_optimization.md Use this command to check the environment's health and configuration without launching the main FastAPI service. ```bash uv run main.py check ``` -------------------------------- ### FastAPI Application Setup (Python) Source: https://github.com/sadivo/taiwan-law-rag-mcp/blob/main/plan/VIBE_CODING_PROMPT.md Main Python script for the FastAPI application, including CORS configuration and startup logic. It defines Pydantic models for requests/responses and implements caching. ```python # python-rag/main.py # FastAPI app # CORS 配置 # 啟動邏輯 ``` -------------------------------- ### Test FastAPI Endpoint (Bash) Source: https://github.com/sadivo/taiwan-law-rag-mcp/blob/main/plan/VIBE_CODING_PROMPT.md Example command to test the semantic search endpoint of the FastAPI service using curl. ```bash curl http://localhost:8000/search/semantic ``` -------------------------------- ### Enable Query Rewriting Temporarily Source: https://github.com/sadivo/taiwan-law-rag-mcp/blob/main/docs/USAGE.md You can temporarily enable the query understanding module by setting the ENABLE_QUERY_REWRITING environment variable when starting the serve command. ```bash ENABLE_QUERY_REWRITING=true uv run main.py serve ``` -------------------------------- ### One-Click Environment Initialization Source: https://github.com/sadivo/taiwan-law-rag-mcp/blob/main/plan/log/phase13_ux_optimization.md Execute this script to set up the development environment, including virtual environment creation, dependency synchronization, .env file configuration, and initial health checks. ```bash uv run scripts/setup.py ``` -------------------------------- ### Initialize and Add Dependencies with uv (Bash) Source: https://github.com/sadivo/taiwan-law-rag-mcp/blob/main/plan/VIBE_CODING_PROMPT.md Initializes a new uv environment and adds dependencies from a requirements file. Ensure you are in the project root directory. ```bash # 在專案根目錄 (taiwan-law-rag-mcp) 下執行 uv init uv add -r python-rag/requirements.txt ``` -------------------------------- ### Create Project Structure (Bash) Source: https://github.com/sadivo/taiwan-law-rag-mcp/blob/main/plan/VIBE_CODING_PROMPT.md Command to create the initial directory structure for the project. Navigate to the project root before executing. ```bash mkdir taiwan-law-rag-mcp cd taiwan-law-rag-mcp mkdir -p data python-rag mcp-server scripts docs ``` -------------------------------- ### Clone Repository and Navigate Source: https://github.com/sadivo/taiwan-law-rag-mcp/blob/main/docs/INSTALLATION.md Clones the Taiwan Law RAG repository and changes the current directory to the project root. ```bash git clone cd taiwan-law-rag ``` -------------------------------- ### Get Full Law Text Source: https://github.com/sadivo/taiwan-law-rag-mcp/blob/main/plan/VIBE_CODING_PROMPT.md Retrieves the complete text of a specific law, including all its articles. ```APIDOC ## POST /law/full ### Description Retrieves the complete text of a specific law, including all its articles. ### Method POST ### Endpoint /law/full ### Parameters #### Request Body - **law_name** (str) - Required - The name of the law to retrieve. ### Response #### Success Response (200) - **law** (Law) - An object containing information about the law. - **articles** (list[Article]) - A list of articles belonging to the law. ``` -------------------------------- ### Unified CLI Entry Point Commands Source: https://github.com/sadivo/taiwan-law-rag-mcp/blob/main/plan/phase13_ux_optimization.md Use these commands with `uv run main.py` to manage the RAG system. They provide a single entry point for various operations like serving the API, rebuilding the index, running evaluations, and checking environment health. ```bash uv run main.py serve # 啟動 FastAPI(等同 uv run python-rag/main.py) uv run main.py index # 重建索引 uv run main.py eval # 執行評估 uv run main.py check # 環境健康檢查(不啟動服務) ``` -------------------------------- ### Server Build and Run Test Source: https://github.com/sadivo/taiwan-law-rag-mcp/blob/main/plan/log/phase6_mcp_server.md Verification of the build process and server startup for the MCP Server. ```bash npm run build node dist/index.js ``` -------------------------------- ### Get Full Law Endpoint Source: https://github.com/sadivo/taiwan-law-rag-mcp/blob/main/plan/log/phase5_fastapi_service.md Tests the /law/full endpoint to retrieve the complete content of a specific law. ```APIDOC ## POST /law/full ### Description Retrieves the full content of a specified law. ### Method POST ### Endpoint /law/full ### Parameters #### Request Body - **law_name** (string) - Required - The name of the law to retrieve. ### Response #### Success Response (200) - **law** (object) - An object containing the full details of the law, including articles, chapters, and content. - **query_time** (number) - The time taken to execute the query in seconds. ``` -------------------------------- ### Semantic Search Test Output Source: https://github.com/sadivo/taiwan-law-rag-mcp/blob/main/plan/log/phase6_mcp_server.md Example output from a semantic search query for '加班費計算' (overtime pay calculation). ```text 找到 1 條相關法條: 【1】勞動基準法 第 38 條 (第四章) 這是關於 加班費計算 的模擬條文... 🔗 https://law.moj.gov.tw/ 相關度: 0.95 ``` -------------------------------- ### Execution Order Recommendation Source: https://github.com/sadivo/taiwan-law-rag-mcp/blob/main/plan/OPTIMIZATION_PLAN.md Recommended order for executing development phases, prioritizing evaluation framework, then RAG generation, and finally query understanding for iterative improvement. ```text Phase 10 (Evaluation Framework) → Establish quantitative benchmarks first for data-driven optimization. Phase 11 (Question Generation) → Complete RAG loop for the strongest demo effect. Phase 12 (Query Understanding) → Validate improvements using the Phase 10 framework. ``` -------------------------------- ### Get Full Law Content Source: https://github.com/sadivo/taiwan-law-rag-mcp/blob/main/docs/API.md Retrieves the complete text of a specified law, including its basic information and all articles. ```APIDOC ## POST /law/full ### Description Retrieves the complete text of a specified law. ### Method POST ### Endpoint /law/full ### Parameters #### Request Body - **law_name** (string) - Required - The full name of the law, e.g., `勞動基準法` ### Request Example ```json { "law_name": "勞動基準法" } ``` ### Response #### Success Response (200) - **law** (Law) - Basic information about the law. - **articles** (Article[]) - A list of all articles in the law. **Law Object** - **law_name** (string) - Name of the law. - **law_level** (string) - Level of the law. - **law_category** (string) - Category of the law. - **law_url** (string) - Official link to the law. - **modified_date** (string) - Date of modification. - **is_abolished** (boolean) - Whether the law has been abolished. **Article Object** - **article_no** (string) - Article number. - **content** (string) - Content of the article. - **chapter** (string) - Chapter the article belongs to. ### Response Example ```json { "law": { "law_name": "勞動基準法", "law_level": "法律", "law_category": "勞動", "law_url": "https://law.moj.gov.tw/LawClass/LawAll.aspx?pcode=N0030001", "modified_date": "2023-06-28", "is_abolished": false }, "articles": [ { "article_no": "第 1 條", "content": "為規定勞動條件最低標準,保障勞工權益,加強勞雇關係,促進社會與經濟發展,特制定本法...", "chapter": "第一章 總則" } ] } ``` ``` -------------------------------- ### RAG Chain Implementation Source: https://github.com/sadivo/taiwan-law-rag-mcp/blob/main/plan/OPTIMIZATION_PLAN.md Illustrates the RAG chain process from user query to LLM-generated answer with streaming output. ```text User question → Retrieval (existing hybrid retrieval) → Context assembly (relevant articles + citation info) → Prompt construction (system prompt + context + question) → LLM generates answer → Streaming output (SSE) ``` -------------------------------- ### MCP Tool: Get Law Full Text Source: https://github.com/sadivo/taiwan-law-rag-mcp/blob/main/docs/USAGE.md Use to retrieve the complete text of a specified law. Requires 'law_name'. ```json { "tool": "get_law_full_text", "arguments": { "law_name": "勞動基準法" } } ``` -------------------------------- ### Run Phase 2 Tests with uv Source: https://github.com/sadivo/taiwan-law-rag-mcp/blob/main/plan/log/phase2_walkthrough.md Execute the Phase 2 testing script using the 'uv run' command. This script simulates importing a small national law database and verifies the output of the implemented data processing tools. ```bash $ uv run python scripts/test_phase2.py ``` -------------------------------- ### API Endpoint for Full Chat Response Source: https://github.com/sadivo/taiwan-law-rag-mcp/blob/main/plan/log/phase11_rag_generation.md Use this endpoint to get a complete answer to a question. Specify the number of top results to retrieve. ```bash curl -X POST http://localhost:8073/chat \ -H "Content-Type: application/json" \ -d '{"question": "勞工加班費如何計算?", "top_k": 5}' ``` -------------------------------- ### Build Index Script Source: https://github.com/sadivo/taiwan-law-rag-mcp/blob/main/plan/log/phase8_langchain_provider_and_mcp_integration.md Run this script to build or rebuild the index, especially after changing providers or configurations. This is a prerequisite for querying. ```bash uv run scripts/build_index.py ``` -------------------------------- ### Health Check Endpoint Test Source: https://github.com/sadivo/taiwan-law-rag-mcp/blob/main/plan/log/phase5_fastapi_service.md Tests the GET /health endpoint to verify the service status. Expected to return a JSON object with service status. ```bash curl.exe -X GET http://localhost:8000/health ``` ```json {"status":"ok","service":"Taiwan Law RAG API"} ``` -------------------------------- ### Dry Run Evaluation Command Source: https://github.com/sadivo/taiwan-law-rag-mcp/blob/main/plan/log/phase10_evaluation_pipeline.md Executes the evaluation pipeline in a dry-run mode without requiring any external providers. This is useful for validating the setup and data loading. ```bash uv run scripts/run_evaluation.py --dry-run ``` -------------------------------- ### TypeScript MCP Server Main Program Source: https://github.com/sadivo/taiwan-law-rag-mcp/blob/main/plan/VIBE_CODING_PROMPT.md The main program for the MCP Server, written in TypeScript. It initializes configuration, registers tools, and starts the stdio transport. ```typescript """ MCP Server 主程式 初始化: 1. 載入配置 (RAG API URL) 2. 註冊 5 個 Tools 3. 啟動 stdio transport Tools: - semantic_search: 語義搜尋 - exact_search: 精確條文查詢 - search_law_by_name: 法律名稱搜尋 - get_law_full_text: 取得完整法律 - compare_laws: 法律比較 錯誤處理: - RAG API 連線失敗 → 友善錯誤訊息 - 超時處理 (30秒) - 重試機制 (3次) 日誌: - 記錄所有工具呼叫 - 性能監控 """ ``` -------------------------------- ### POST /law/full — Get Full Law Text Source: https://context7.com/sadivo/taiwan-law-rag-mcp/llms.txt Retrieves the complete text of a specified law, including basic law information and a list of all articles. ```APIDOC ## POST /law/full — Get Full Law Text ### Description Retrieves the complete text of a specified law, including basic law information and a list of all articles. ### Method POST ### Endpoint `/law/full` ### Parameters #### Request Body - **law_name** (string) - Required - The name of the law to retrieve. ### Request Example ```json { "law_name": "勞動基準法" } ``` ### Response #### Success Response (200) - **law** (object) - Basic information about the law. - **law_name** (string) - Name of the law. - **law_level** (string) - Level of the law. - **law_category** (string) - Category of the law. - **law_url** (string) - URL to the law. - **modified_date** (string) - Date the law was last modified. - **is_abolished** (boolean) - Indicates if the law is abolished. - **articles** (array) - List of all articles in the law. - **article_no** (string) - Article number. - **content** (string) - Content of the article. - **chapter** (string) - Chapter the article belongs to. ### Response Example ```json { "law": { "law_name": "勞動基準法", "law_level": "法律", "law_category": "勞動", "law_url": "https://law.moj.gov.tw/LawClass/LawAll.aspx?pcode=N0030001", "modified_date": "2023-06-28", "is_abolished": false }, "articles": [ { "article_no": "第 1 條", "content": "為規定勞動條件最低標準,保障勞工權益...", "chapter": "第一章 總則" }, { "article_no": "第 38 條", "content": "勞工在同一雇主或事業單位,繼續工作滿一定期間者...", "chapter": "第四章 工作時間、休息、休假" } ] } ``` ``` -------------------------------- ### Configure Claude Desktop for MCP Server Source: https://github.com/sadivo/taiwan-law-rag-mcp/blob/main/plan/VIBE_CODING_PROMPT.md Configure the `claude_desktop_config.json` file to register the local MCP server, specifying the command, arguments, and environment variables. ```json { "mcpServers": { "taiwan-law": { "command": "node", "args": [ "C:\\path\\to\\taiwan-law-rag-mcp\\mcp-server\\dist\\index.js" ], "env": { "RAG_API_URL": "http://localhost:8000" } } } } ``` -------------------------------- ### FastAPI: Get Law Full Text Endpoint Source: https://github.com/sadivo/taiwan-law-rag-mcp/blob/main/docs/USAGE.md Use the POST /law/full endpoint to retrieve the complete text of a law. Requires a JSON payload with 'law_name'. ```bash curl -X POST http://127.0.0.1:8073/law/full \ -H "Content-Type: application/json" \ -d '{ "law_name": "勞動基準法" }' ``` -------------------------------- ### Prompt for Creating Project Structure (Natural Language) Source: https://github.com/sadivo/taiwan-law-rag-mcp/blob/main/plan/VIBE_CODING_PROMPT.md A natural language prompt instructing an AI assistant to create the project directory structure and empty files using a Windows batch script. ```plaintext 請根據上面的專案結構,建立所有目錄和空白檔案。 使用 Windows 批次檔 (setup.bat) 自動建立。 ``` -------------------------------- ### Local Embedding and Reranking Configuration Source: https://github.com/sadivo/taiwan-law-rag-mcp/blob/main/docs/INSTALLATION.md Configures the system to use local models for embedding and reranking. This setup does not require an API key and is suitable for offline or privacy-sensitive scenarios. ```env EMBEDDING_PROVIDER=local RERANKING_PROVIDER=local PROVIDER_API_KEY= ``` -------------------------------- ### Get Law Full Text Tool for MCP Server (TypeScript) Source: https://github.com/sadivo/taiwan-law-rag-mcp/blob/main/plan/VIBE_CODING_PROMPT.md Defines the 'get_law_full_text' tool for the MCP server, allowing retrieval of the complete text of a specific law. ```typescript // mcp-server/src/tools/get_law.ts // get_law_full_text 工具 ``` -------------------------------- ### Provider Configuration Reference (.env) Source: https://context7.com/sadivo/taiwan-law-rag-mcp/llms.txt All provider settings are managed via .env, supporting various cloud and local provider combinations for embedding, reranking, and generation. ```env # -- Embedding Provider ------------------------------------------ # Supports: local | openai | cohere | voyageai | huggingface | google | mistral | bedrock | azure-openai EMBEDDING_PROVIDER=voyageai PROVIDER_API_KEY=pa-你的VoyageAI金鑰 # Embedding + Reranking shared EMBEDDING_API_KEY= # Use if different from Reranking provider EMBEDDING_MODEL_NAME= # Leave empty for provider default EMBEDDING_BATCH_SIZE=100 # -- Reranking Provider ------------------------------------------ # Supports: local | voyageai | cohere | flashrank RERANKING_PROVIDER=local RERANKING_API_KEY= # Use if different from Embedding provider RERANKING_MODEL_NAME= # Leave empty for provider default # -- Generation Provider ----------------------------------------- # Supports: ollama | openai | anthropic GENERATION_PROVIDER=anthropic GENERATION_API_KEY=sk-ant-你的Anthropic金鑰 GENERATION_MODEL_NAME=claude-3-5-haiku-20241022 GENERATION_TOP_K=5 # Default top_k for retrieval GENERATION_MAX_TOKENS=1024 # Max tokens for LLM generation # -- Ollama Settings (used when GENERATION_PROVIDER=ollama) -------- OLLAMA_BASE_URL=http://localhost:11434 # -- Server Settings --------------------------------------------- API_HOST=127.0.0.1 API_PORT=8073 ``` -------------------------------- ### Test Cases for Retrieval System (Python) Source: https://github.com/sadivo/taiwan-law-rag-mcp/blob/main/plan/VIBE_CODING_PROMPT.md Illustrative Python code snippets demonstrating different types of queries and their expected outcomes for the retrieval system, including semantic search, exact query, law alias lookup, and law comparison. ```python # 1. 語義搜尋 "加班費如何計算" → 勞基法第24條 # 2. 精確查詢 "勞基法第38條" → 特別休假 # 3. 法律別名 "勞基法" → 勞動基準法 # 4. 法律比較 ["民法", "公司法"], "股東權利" ``` -------------------------------- ### 專案結構概覽 Source: https://github.com/sadivo/taiwan-law-rag-mcp/blob/main/plan/VIBE_CODING_PROMPT.md 展示了台灣法律 RAG MCP 系統的目錄結構,包括 Python RAG 引擎、MCP Server、資料目錄和腳本等。 ```tree taiwan-law-rag-mcp/ ├── README.md # 專案說明 ├── .env.example # 環境變數範例 ├── .gitignore │ ├── data/ # 資料目錄 │ └── ChLaw.json # 原始法律資料 (25MB, 1343部法律) │ ├── python-rag/ # Python RAG 引擎 │ ├── requirements.txt # Python 依賴 │ ├── config.py # 配置檔 │ ├── main.py # FastAPI 主程式 │ │ │ ├── data_processing/ # 資料處理模組 │ │ ├── __init__.py │ │ ├── loader.py # 載入 ChLaw.json │ │ ├── chunker.py # 條文級切塊 (→ 55k chunks) │ │ ├── metadata_enricher.py # 擴充 metadata │ │ └── law_aliases.py # 法律別名對照表 │ │ │ ├── indexing/ # 索引建立模組 │ │ ├── __init__.py │ │ ├── embedder.py # Qwen3-Embedding-4B 向量化 │ │ ├── faiss_indexer.py # FAISS 索引建立 (HNSW+IVF) │ │ ├── bm25_indexer.py # Whoosh BM25 索引 │ │ └── rebuild_index.py # 重建索引腳本 │ │ │ ├── retrieval/ # 檢索模組 │ │ ├── __init__.py │ │ ├── query_classifier.py # 查詢分類 (精確/語義) │ │ ├── vector_retriever.py # FAISS 向量檢索 │ │ ├── bm25_retriever.py # BM25 檢索 │ │ ├── hybrid_retriever.py # 混合檢索 (RRF 融合) │ │ ├── reranker.py # Qwen3-Reranker-4B 重排序 │ │ └── deduplicator.py # 結果去重 (同法律最多3條) │ │ │ ├── api/ # API 路由 │ │ ├── __init__.py │ │ ├── routes.py # FastAPI 路由定義 │ │ ├── models.py # Pydantic 資料模型 │ │ └── cache.py # LRU Cache 實作 │ │ │ ├── utils/ # 工具函數 │ │ ├── __init__.py │ │ ├── article_parser.py # 條號正規化 │ │ ├── law_name_normalizer.py # 法律名稱正規化 │ │ └── logger.py # 日誌配置 │ │ │ └── tests/ # 測試 │ ├── test_retrieval.py │ └── test_api.py │ ├── mcp-server/ # MCP Server │ ├── package.json │ ├── tsconfig.json │ ├── src/ │ │ ├── index.ts # MCP Server 主程式 │ │ ├── tools/ # MCP Tools 定義 │ │ │ ├── search.ts # 語義搜尋 │ │ │ ├── exact_search.ts # 精確條文查詢 │ │ │ ├── law_search.ts # 法律名稱搜尋 │ │ │ ├── get_law.ts # 取得完整法律 │ │ │ └── compare.ts # 法律比較 │ │ ├── clients/ │ │ │ └── rag_client.ts # 呼叫 Python RAG API │ │ └── utils/ │ │ ├── formatter.ts # 格式化輸出 │ │ └── error_handler.ts # 錯誤處理 │ │ │ └── dist/ # 編譯輸出 │ ├── scripts/ # 腳本工具 │ ├── setup.bat # Windows 初始化腳本 │ ├── build_index.py # 建立索引 │ ├── test_query.py # 測試查詢 │ └── update_data.py # 更新資料 │ └── docs/ # 文檔 ├── INSTALLATION.md # 安裝指南 ├── USAGE.md # 使用說明 └── API.md # API 文檔 ``` -------------------------------- ### Ollama Generation Provider Configuration Source: https://github.com/sadivo/taiwan-law-rag-mcp/blob/main/docs/INSTALLATION.md Configures the system to use Ollama for text generation. This setup does not require an API key and specifies the model name and Ollama service URL. ```env GENERATION_PROVIDER=ollama GENERATION_MODEL_NAME=qwen3:8b OLLAMA_BASE_URL=http://localhost:11434 GENERATION_API_KEY= ``` -------------------------------- ### Check Provider Connectivity Source: https://context7.com/sadivo/taiwan-law-rag-mcp/llms.txt Verifies the connectivity of all configured AI providers without starting the FastAPI service. This is useful for confirming environment settings. It exits with code 1 on failure. ```bash uv run main.py check # 全部正常: # Taiwan Law RAG — 環境檢查 # ✓ Embedding : voyageai:voyage-3.5-lite # ✓ Reranking : local:Qwen3-Reranker-4B # ✓ Generation : openai:gpt-4o-mini # 環境設定正常,可執行 uv run main.py serve 啟動服務。 # Generation 無法連線: # Taiwan Law RAG — 環境檢查 # ✓ Embedding : voyageai:voyage-3.5-lite # ✓ Reranking : local:Qwen3-Reranker-4B # ✗ Generation : ollama:qwen3:8b (unreachable at http://localhost:11434) # 警告:Generation provider 無法連線,/chat 端點將無法使用。 ``` -------------------------------- ### Custom Exception Hierarchy for Evaluation Source: https://github.com/sadivo/taiwan-law-rag-mcp/blob/main/plan/log/phase10_evaluation_pipeline.md Defines a custom exception hierarchy for the evaluation pipeline, starting with a base error and including specific exceptions for dataset-related issues and report writing. ```python EvaluationPipelineError (base) ├── DatasetNotFoundError ├── DatasetFormatError ├── DatasetValidationError └── ReportWriteError ``` -------------------------------- ### Full Evaluation Command with OpenAI Embedding Source: https://github.com/sadivo/taiwan-law-rag-mcp/blob/main/plan/log/phase10_evaluation_pipeline.md Runs the complete evaluation pipeline using OpenAI embeddings. Requires setting the EMBEDDING_PROVIDER and OPENAI_API_KEY environment variables. ```bash # 使用 OpenAI embedding EMBEDDING_PROVIDER=openai OPENAI_API_KEY=sk-xxx uv run scripts/run_evaluation.py ``` -------------------------------- ### Run CLI Commands Source: https://github.com/sadivo/taiwan-law-rag-mcp/blob/main/README.md A list of available command-line interface subcommands for managing the RAG system, including serving, indexing, evaluation, and connection checks. ```bash uv run main.py serve # 啟動 FastAPI 服務 ``` ```bash uv run main.py index # 重建索引 ``` ```bash uv run main.py eval # 執行評估框架 ``` ```bash uv run main.py check # 驗證 provider 連線(不啟動服務) ``` -------------------------------- ### Enable Query Understanding Module Source: https://context7.com/sadivo/taiwan-law-rag-mcp/llms.txt Set ENABLE_QUERY_REWRITING=true in your .env file to activate the query understanding pipeline, which supports language detection, English query translation, intent classification, and LLM query rewriting. Exceptions in sub-modules are caught without affecting service availability. ```bash # Enable in .env echo "ENABLE_QUERY_REWRITING=true" >> .env uv run main.py serve # Or override temporarily (without modifying .env) ENABLE_QUERY_REWRITING=true uv run main.py serve # Search with English query automatically translated to Traditional Chinese curl -X POST http://127.0.0.1:8073/search/semantic \ -H "Content-Type: application/json" \ -d '{"query": "overtime pay regulations", "top_k": 3}' # Internally translates to "加班費規定" for mixed retrieval # Returns the same results as a Chinese query # Query pipeline flow: # query # → Language detection (CJK/ASCII ratio determines zh/en) # → Translation (English → Traditional Chinese, fallback to original query on failure) # → Intent classification (exact / comparison / definition / procedure / semantic) # → Query rewriting (LLM rewrite, exact intent skips) # → Coreference expansion (combines with Session's previous query) # → Sent to RetrievalService (FAISS + BM25 + RRF + Reranker) ``` -------------------------------- ### Develop FastAPI Service for RAG Source: https://github.com/sadivo/taiwan-law-rag-mcp/blob/main/plan/VIBE_CODING_PROMPT.md Implement the FastAPI service with 6 API endpoints, including LRU Cache and CORS support. Start the service using `uvicorn main:app`. ```bash # 啟動服務 cd python-rag uvicorn main:app --reload ```