[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M77SS29GEM86J5GCRQHGXNM9":3,"skill-same:01M77SS29GEM86J5GCRQHGXNM9":47},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":29,"ownerHtmlUrl":30,"ownerBlogUrl":6,"ownerDescription":31,"updatedAt":32,"install":33,"resources":46},"01M77SS29GEM86J5GCRQHGXNM9","rag-system-builder",null,"Build and deploy local RAG (Retrieval-Augmented Generation) systems with offline document processing, embedding models, and vector storage.","Lord1Egypt\u002Fawesome-skill-forge","Lord1Egypt","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F99746359?v=4","01M7592YDNT0XK9WJ0T2MQVPDN","Mohamed Mounir Ali AL Keshita","01M75GRFNHC8VZNWEB8DKDE433",3,"MIT","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fclawhub\u002Fr\u002Frag-system-builder\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: rag-system-builder\ndescription: Build and deploy local RAG (Retrieval-Augmented Generation) systems with offline document processing, embedding models, and vector storage.\n---\n\n# RAG System Builder Skill\n\nBuild complete local RAG systems that work offline with document ingestion, semantic search, and AI-powered Q&A.\n\n## 🎯 What This Skill Does\n\nThis skill guides you through building a complete RAG system that:\n- **Ingests documents** from multiple formats (TXT, PDF, DOCX, MD, HTML, JSON, XML)\n- **Generates embeddings** using sentence-transformers (offline, no API needed)\n- **Stores vectors** locally using FAISS for fast similarity search\n- **Provides Q&A interface** through CLI and web interface\n- **Works completely offline** - no external API calls required\n\n## 📦 Prerequisites\n\n```bash\n# Python 3.8+ required\npython --version\n\n# Install dependencies\npip install sentence-transformers faiss-cpu click flask\n```\n\n## 🚀 Quick Start\n\n### 1. Create Project Structure\n\n```bash\n# Create project directory\nmkdir rag-system\ncd rag-system\n\n# Create main files\ntouch rag.py embeddings.py vector_store.py retriever.py config.py\n```\n\n### 2. Download Embedding Model\n\n```bash\n# Download sentence-transformers model locally\npython -c \"from huggingface_hub import snapshot_download; snapshot_download(repo_id='sentence-transformers\u002Fall-MiniLM-L6-v2', local_dir='.\u002Fmodels\u002Fall-MiniLM-L6-v2')\"\n```\n\n### 3. Configure System\n\nCreate `config.py`:\n\n```python\nimport os\nfrom dataclasses import dataclass\n\n@dataclass\nclass Config:\n    embedding_model: str = \"sentence-transformers\u002Fall-MiniLM-L6-v2\"\n    local_model_path: str = \".\u002Fmodels\u002Fall-MiniLM-L6-v2\"\n    chunk_size: int = 512\n    chunk_overlap: int = 128\n    vector_store_path: str = \"vector_store\"\n    default_top_k: int = 5\n    supported_formats: tuple = (\".txt\", \".pdf\", \".docx\", \".md\", \".html\", \".json\", \".xml\")\n```\n\n### 4. Build Core Components\n\n#### Embeddings Module (`embeddings.py`)\n\n```python\nimport os\nimport numpy as np\nfrom typing import List\nfrom sentence_transformers import SentenceTransformer\nfrom config import config\n\nclass EmbeddingModel:\n    def __init__(self, model_name: str = None):\n        self.model_name = model_name or config.embedding_model\n        self.model = None\n        self._load_model()\n    \n    def _load_model(self):\n        \"\"\"Load embedding model with local fallback\"\"\"\n        print(f\"Loading embedding model: {self.model_name}\")\n        \n        # Try local model first\n        local_path = config.local_model_path\n        if os.path.exists(local_path):\n            print(f\"Using local model: {local_path}\")\n            try:\n                self.model = SentenceTransformer(local_path)\n                print(\"Local model loaded successfully\")\n                return\n            except Exception as e:\n                print(f\"Error loading local model: {e}\")\n        \n        # Fallback to HuggingFace\n        try:\n            self.model = SentenceTransformer(self.model_name)\n            print(\"Model loaded from HuggingFace\")\n        except Exception as e:\n            print(f\"Error: {e}\")\n            raise\n    \n    def encode(self, texts: List[str], batch_size: int = 32) -> np.ndarray:\n        \"\"\"Encode texts into embeddings\"\"\"\n        if not texts:\n            return np.array([])\n        \n        embeddings = []\n        for i in range(0, len(texts), batch_size):\n            batch = texts[i:i + batch_size]\n            batch_embeddings = self.model.encode(batch, convert_to_numpy=True)\n            embeddings.append(batch_embeddings)\n        \n        return np.vstack(embeddings)\n```\n\n#### Vector Store Module (`vector_store.py`)\n\n```python\nimport os\nimport json\nimport faiss\nimport numpy as np\nfrom config import config\n\nclass VectorStore:\n    def __init__(self, base_path: str = \".\"):\n        self.base_path = base_path\n        self.vector_store_path = config.get_vector_store_path(base_path)\n        self.index = None\n        self.metadata = []\n        \n        # Create directory if it doesn't exist\n        os.makedirs(self.vector_store_path, exist_ok=True)\n    \n    def build_index(self, embeddings: np.ndarray, metadata: list):\n        \"\"\"Build FAISS index from embeddings\"\"\"\n        print(f\"Building index with {len(embeddings)} vectors\")\n        \n        # Create FAISS index\n        dimension = embeddings.shape[1]\n        self.index = faiss.IndexFlatIP(dimension)  # Inner Product = Cosine Similarity\n        \n        # Normalize embeddings for cosine similarity\n        faiss.normalize_L2(embeddings)\n        self.index.add(embeddings)\n        \n        self.metadata = metadata\n        print(f\"Built index with {len(embeddings)} vectors\")\n    \n    def save(self):\n        \"\"\"Save index and metadata to disk\"\"\"\n        index_path = os.path.join(self.vector_store_path, config.index_file)\n        metadata_path = os.path.join(self.vector_store_path, config.metadata_file)\n        \n        # Save FAISS index\n        faiss.write_index(self.index, index_path)\n        \n        # Save metadata\n        with open(metadata_path, 'w', encoding='utf-8') as f:\n            json.dump(self.metadata, f, ensure_ascii=False, indent=2)\n        \n        print(f\"Saved index to {index_path}\")\n        print(f\"Saved metadata to {metadata_path}\")\n    \n    def load(self):\n        \"\"\"Load index and metadata from disk\"\"\"\n        index_path = os.path.join(self.vector_store_path, config.index_file)\n        metadata_path = os.path.join(self.vector_store_path, config.metadata_file)\n        \n        if os.path.exists(index_path) and os.path.exists(metadata_path):\n            self.index = faiss.read_index(index_path)\n            with open(metadata_path, 'r', encoding='utf-8') as f:\n                self.metadata = json.load(f)\n            print(f\"Loaded index with {self.index.ntotal} vectors\")\n            return True\n        return False\n```\n\n#### Retriever Module (`retriever.py`)\n\n```python\nimport numpy as np\nfrom config import config\n\nclass Retriever:\n    def __init__(self, vector_store):\n        self.vector_store = vector_store\n    \n    def search(self, query: str, top_k: int = None) -> list:\n        \"\"\"Search for relevant documents\"\"\"\n        if top_k is None:\n            top_k = config.default_top_k\n        \n        if self.vector_store.index is None:\n            print(\"No index loaded. Please ingest documents first.\")\n            return []\n        \n        # Encode query\n        from embeddings import EmbeddingModel\n        embedding_model = EmbeddingModel()\n        query_embedding = embedding_model.encode_single(query)\n        \n        # Normalize for cosine similarity\n        query_embedding = np.expand_dims(query_embedding, axis=0)\n        faiss.normalize_L2(query_embedding)\n        \n        # Search\n        scores, indices = self.vector_store.index.search(query_embedding, top_k)\n        \n        # Return results with metadata\n        results = []\n        for i, idx in enumerate(indices[0]):\n            if idx \u003C len(self.vector_store.metadata):\n                result = self.vector_store.metadata[idx].copy()\n                result[\"score\"] = float(scores[0][i])\n                results.append(result)\n        \n        return results\n```\n\n### 5. Create CLI Interface (`rag.py`)\n\n```python\nimport os\nimport sys\nimport click\nfrom ingestion import IngestionPipeline\nfrom embeddings import EmbeddingModel\nfrom vector_store import VectorStore\nfrom retriever import Retriever\nfrom config import config\n\n@click.group()\ndef cli():\n    \"\"\"OpenClaw RAG System - Local document retrieval\"\"\"\n    pass\n\n@cli.command()\n@click.option('--docs-path', required=True, help='Path to folder containing documents')\n@click.option('--chunk-size', default=512, help='Chunk size for text splitting')\n@click.option('--chunk-overlap', default=128, help='Chunk overlap size')\ndef ingest(docs_path, chunk_size, chunk_overlap):\n    \"\"\"Ingest documents from a folder into the vector store\"\"\"\n    click.echo(f\"Starting ingestion from: {docs_path}\")\n    \n    # Initialize components\n    ingestion = IngestionPipeline(chunk_size=chunk_size, chunk_overlap=chunk_overlap)\n    embedding_model = EmbeddingModel()\n    vector_store = VectorStore()\n    \n    # Ingest documents\n    try:\n        chunks = ingestion.ingest_folder(docs_path)\n        \n        if not chunks:\n            click.echo(\"No documents found or processed.\")\n            return\n        \n        # Extract texts and metadata\n        texts = [chunk[\"text\"] for chunk in chunks]\n        metadata = [{\n            \"text\": chunk[\"text\"],\n            \"source\": chunk[\"source\"],\n            \"doc_type\": chunk[\"doc_type\"],\n            \"doc_id\": chunk[\"doc_id\"]\n        } for chunk in chunks]\n        \n        # Generate embeddings\n        click.echo(\"Generating embeddings...\")\n        embeddings = embedding_model.encode(texts)\n        \n        # Build and save vector store\n        vector_store.build_index(embeddings, metadata)\n        vector_store.save()\n        \n        click.echo(f\"[OK] Ingestion complete! Processed {len(chunks)} chunks.\")\n        \n    except Exception as e:\n        click.echo(f\"[ERROR] Error during ingestion: {e}\")\n        sys.exit(1)\n\n@cli.command()\n@click.option('--query', required=True, help='Search query')\n@click.option('--top-k', default=5, help='Number of results to return')\ndef query(query, top_k):\n    \"\"\"Query the vector store for relevant documents\"\"\"\n    # Load vector store\n    vector_store = VectorStore()\n    if not vector_store.load():\n        click.echo(\"No vector store found. Please ingest documents first.\")\n        return\n    \n    # Search\n    retriever = Retriever(vector_store)\n    results = retriever.search(query, top_k)\n    \n    if not results:\n        click.echo(\"No results found.\")\n        return\n    \n    # Display results\n    click.echo(f\"\\nFound {len(results)} relevant documents:\\n\")\n    for i, result in enumerate(results, 1):\n        click.echo(f\"[{i}] {result['source']}\")\n        click.echo(f\"    Score: {result['score']:.4f}\")\n        click.echo(f\"    Content: {result['text'][:200]}...\")\n        click.echo()\n\n@cli.command()\ndef stats():\n    \"\"\"Show statistics about the vector store\"\"\"\n    vector_store = VectorStore()\n    if vector_store.load():\n        click.echo(f\"Vector store statistics:\")\n        click.echo(f\"  Total vectors: {vector_store.index.ntotal}\")\n        click.echo(f\"  Metadata entries: {len(vector_store.metadata)}\")\n    else:\n        click.echo(\"No vector store found.\")\n\n@cli.command()\ndef clear():\n    \"\"\"Clear the vector store\"\"\"\n    vector_store = VectorStore()\n    vector_store.clear()\n    click.echo(\"Vector store cleared.\")\n\nif __name__ == \"__main__\":\n    cli()\n```\n\n## 📋 Usage Examples\n\n### Basic Workflow\n\n```bash\n# 1. Install dependencies\npip install sentence-transformers faiss-cpu click flask\n\n# 2. Download model (one-time)\npython -c \"from huggingface_hub import snapshot_download; snapshot_download(repo_id='sentence-transformers\u002Fall-MiniLM-L6-v2', local_dir='.\u002Fmodels\u002Fall-MiniLM-L6-v2')\"\n\n# 3. Ingest documents\npython rag.py ingest --docs-path .\u002Fmy-documents\n\n# 4. Query documents\npython rag.py query --query \"What is machine learning?\"\n\n# 5. Check statistics\npython rag.py stats\n```\n\n### Advanced Usage\n\n```bash\n# Custom chunk size\npython rag.py ingest --docs-path .\u002Fdocs --chunk-size 1024 --chunk-overlap 256\n\n# Get top 10 results\npython rag.py query --query \"AI applications\" --top-k 10\n\n# Interactive mode (create your own)\npython rag.py interactive\n```\n\n## 🔧 Troubleshooting\n\n### Model Download Issues\n\n```bash\n# Manual download from HuggingFace\n# Visit: https:\u002F\u002Fhuggingface.co\u002Fsentence-transformers\u002Fall-MiniLM-L6-v2\n# Download all files to .\u002Fmodels\u002Fall-MiniLM-L6-v2\u002F\n```\n\n### Memory Issues\n\n- Reduce chunk size: `--chunk-size 256`\n- Process documents in batches\n- Use smaller embedding model\n\n### Encoding Issues (Windows)\n\n```python\n# Add to rag.py for Windows compatibility\nimport sys\nimport io\nsys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')\n```\n\n## 📁 Project Structure\n\n```\nrag-system\u002F\n├── rag.py                 # CLI interface\n├── embeddings.py          # Embedding generation\n├── vector_store.py        # FAISS storage\n├── retriever.py           # Search functionality\n├── config.py              # Configuration\n├── ingestion.py           # Document processing\n├── models\u002F\n│   └── all-MiniLM-L6-v2\u002F  # Local embedding model\n├── vector_store\u002F          # FAISS index and metadata\n└── documents\u002F             # Your documents folder\n```\n\n## 🎯 Use Cases\n\n1. **Document Q&A System**\n   - Upload document library\n   - Ask questions get relevant answers\n   - Support multiple documents\n\n2. **Knowledge Base Search**\n   - Organize documents in folders\n   - Quick retrieval of relevant information\n   - Generate contextual answers\n\n3. **Research Assistant**\n   - Collect research materials\n   - Fast information lookup\n   - Assist with paper writing\n\n## 📚 References\n\n- **Embedding Model**: sentence-transformers\u002Fall-MiniLM-L6-v2\n- **Vector Database**: FAISS (Facebook AI Similarity Search)\n- **Similarity Metric**: Cosine Similarity\n- **Chunk Size**: 512 tokens (configurable)\n- **Chunk Overlap**: 128 tokens (configurable)\n\n## 🤝 Contributing\n\nThis skill is designed to be extended. You can:\n- Add support for more document formats\n- Implement different embedding models\n- Add web interface features\n- Create specialized RAG systems for specific domains\n\n---\n\n**Skill Version**: 1.0.0  \n**Last Updated**: 2026-03-05  \n**Author**: Wangwang (OpenClaw Personal Assistant)","# RAG System Builder Skill\n\nBuild complete local RAG systems that work offline with document ingestion, semantic search, and AI-powered Q&A.\n\n## 🎯 What This Skill Does\n\nThis skill guides you through building a complete RAG system that:\n- **Ingests documents** from multiple formats (TXT, PDF, DOCX, MD, HTML, JSON, XML)\n- **Generates embeddings** using sentence-transformers (offline, no API needed)\n- **Stores vectors** locally using FAISS for fast similarity search\n- **Provides Q&A interface** through CLI and web interface\n- **Works completely offline** - no external API calls required\n\n## 📦 Prerequisites\n\n```bash\n# Python 3.8+ required\npython --version\n\n# Install dependencies\npip install sentence-transformers faiss-cpu click flask\n```\n\n## 🚀 Quick Start\n\n### 1. Create Project Structure\n\n```bash\n# Create project directory\nmkdir rag-system\ncd rag-system\n\n# Create main files\ntouch rag.py embeddings.py vector_store.py retriever.py config.py\n```\n\n### 2. Download Embedding Model\n\n```bash\n# Download sentence-transformers model locally\npython -c \"from huggingface_hub import snapshot_download; snapshot_download(repo_id='sentence-transformers\u002Fall-MiniLM-L6-v2', local_dir='.\u002Fmodels\u002Fall-MiniLM-L6-v2')\"\n```\n\n### 3. Configure System\n\nCreate `config.py`:\n\n```python\nimport os\nfrom dataclasses import dataclass\n\n@dataclass\nclass Config:\n    embedding_model: str = \"sentence-transformers\u002Fall-MiniLM-L6-v2\"\n    local_model_path: str = \".\u002Fmodels\u002Fall-MiniLM-L6-v2\"\n    chunk_size: int = 512\n    chunk_overlap: int = 128\n    vector_store_path: str = \"vector_store\"\n    default_top_k: int = 5\n    supported_formats: tuple = (\".txt\", \".pdf\", \".docx\", \".md\", \".html\", \".json\", \".xml\")\n```\n\n### 4. Build Core Components\n\n#### Embeddings Module (`embeddings.py`)\n\n```python\nimport os\nimport numpy as np\nfrom typing import List\nfrom sentence_transformers import SentenceTransformer\nfrom config import config\n\nclass EmbeddingModel:\n    def __init__(self, model_name: str = None):\n        self.model_name = model_name or config.embedding_model\n        self.model = None\n        self._load_model()\n    \n    def _load_model(self):\n        \"\"\"Load embedding model with local fallback\"\"\"\n        print(f\"Loading embedding model: {self.model_name}\")\n        \n        # Try local model first\n        local_path = config.local_model_path\n        if os.path.exists(local_path):\n            print(f\"Using local model: {local_path}\")\n            try:\n                self.model = SentenceTransformer(local_path)\n                print(\"Local model loaded successfully\")\n                return\n            except Exception as e:\n                print(f\"Error loading local model: {e}\")\n        \n        # Fallback to HuggingFace\n        try:\n            self.model = SentenceTransformer(self.model_name)\n            print(\"Model loaded from HuggingFace\")\n        except Exception as e:\n            print(f\"Error: {e}\")\n            raise\n    \n    def encode(self, texts: List[str], batch_size: int = 32) -> np.ndarray:\n        \"\"\"Encode texts into embeddings\"\"\"\n        if not texts:\n            return np.array([])\n        \n        embeddings = []\n        for i in range(0, len(texts), batch_size):\n            batch = texts[i:i + batch_size]\n            batch_embeddings = self.model.encode(batch, convert_to_numpy=True)\n            embeddings.append(batch_embeddings)\n        \n        return np.vstack(embeddings)\n```\n\n#### Vector Store Module (`vector_store.py`)\n\n```python\nimport os\nimport json\nimport faiss\nimport numpy as np\nfrom config import config\n\nclass VectorStore:\n    def __init__(self, base_path: str = \".\"):\n        self.base_path = base_path\n        self.vector_store_path = config.get_vector_store_path(base_path)\n        self.index = None\n        self.metadata = []\n        \n        # Create directory if it doesn't exist\n        os.makedirs(self.vector_store_path, exist_ok=True)\n    \n    def build_index(self, embeddings: np.ndarray, metadata: list):\n        \"\"\"Build FAISS index from embeddings\"\"\"\n        print(f\"Building index with {len(embeddings)} vectors\")\n        \n        # Create FAISS index\n        dimension = embeddings.shape[1]\n        self.index = faiss.IndexFlatIP(dimension)  # Inner Product = Cosine Similarity\n        \n        # Normalize embeddings for cosine similarity\n        faiss.normalize_L2(embeddings)\n        self.index.add(embeddings)\n        \n        self.metadata = metadata\n        print(f\"Built index with {len(embeddings)} vectors\")\n    \n    def save(self):\n        \"\"\"Save index and metadata to disk\"\"\"\n        index_path = os.path.join(self.vector_store_path, config.index_file)\n        metadata_path = os.path.join(self.vector_store_path, config.metadata_file)\n        \n        # Save FAISS index\n        faiss.write_index(self.index, index_path)\n        \n        # Save metadata\n        with open(metadata_path, 'w', encoding='utf-8') as f:\n            json.dump(self.metadata, f, ensure_ascii=False, indent=2)\n        \n        print(f\"Saved index to {index_path}\")\n        print(f\"Saved metadata to {metadata_path}\")\n    \n    def load(self):\n        \"\"\"Load index and metadata from disk\"\"\"\n        index_path = os.path.join(self.vector_store_path, config.index_file)\n        metadata_path = os.path.join(self.vector_store_path, config.metadata_file)\n        \n        if os.path.exists(index_path) and os.path.exists(metadata_path):\n            self.index = faiss.read_index(index_path)\n            with open(metadata_path, 'r', encoding='utf-8') as f:\n                self.metadata = json.load(f)\n            print(f\"Loaded index with {self.index.ntotal} vectors\")\n            return True\n        return False\n```\n\n#### Retriever Module (`retriever.py`)\n\n```python\nimport numpy as np\nfrom config import config\n\nclass Retriever:\n    def __init__(self, vector_store):\n        self.vector_store = vector_store\n    \n    def search(self, query: str, top_k: int = None) -> list:\n        \"\"\"Search for relevant documents\"\"\"\n        if top_k is None:\n            top_k = config.default_top_k\n        \n        if self.vector_store.index is None:\n            print(\"No index loaded. Please ingest documents first.\")\n            return []\n        \n        # Encode query\n        from embeddings import EmbeddingModel\n        embedding_model = EmbeddingModel()\n        query_embedding = embedding_model.encode_single(query)\n        \n        # Normalize for cosine similarity\n        query_embedding = np.expand_dims(query_embedding, axis=0)\n        faiss.normalize_L2(query_embedding)\n        \n        # Search\n        scores, indices = self.vector_store.index.search(query_embedding, top_k)\n        \n        # Return results with metadata\n        results = []\n        for i, idx in enumerate(indices[0]):\n            if idx \u003C len(self.vector_store.metadata):\n                result = self.vector_store.metadata[idx].copy()\n                result[\"score\"] = float(scores[0][i])\n                results.append(result)\n        \n        return results\n```\n\n### 5. Create CLI Interface (`rag.py`)\n\n```python\nimport os\nimport sys\nimport click\nfrom ingestion import IngestionPipeline\nfrom embeddings import EmbeddingModel\nfrom vector_store import VectorStore\nfrom retriever import Retriever\nfrom config import config\n\n@click.group()\ndef cli():\n    \"\"\"OpenClaw RAG System - Local document retrieval\"\"\"\n    pass\n\n@cli.command()\n@click.option('--docs-path', required=True, help='Path to folder containing documents')\n@click.option('--chunk-size', default=512, help='Chunk size for text splitting')\n@click.option('--chunk-overlap', default=128, help='Chunk overlap size')\ndef ingest(docs_path, chunk_size, chunk_overlap):\n    \"\"\"Ingest documents from a folder into the vector store\"\"\"\n    click.echo(f\"Starting ingestion from: {docs_path}\")\n    \n    # Initialize components\n    ingestion = IngestionPipeline(chunk_size=chunk_size, chunk_overlap=chunk_overlap)\n    embedding_model = EmbeddingModel()\n    vector_store = VectorStore()\n    \n    # Ingest documents\n    try:\n        chunks = ingestion.ingest_folder(docs_path)\n        \n        if not chunks:\n            click.echo(\"No documents found or processed.\")\n            return\n        \n        # Extract texts and metadata\n        texts = [chunk[\"text\"] for chunk in chunks]\n        metadata = [{\n            \"text\": chunk[\"text\"],\n            \"source\": chunk[\"source\"],\n            \"doc_type\": chunk[\"doc_type\"],\n            \"doc_id\": chunk[\"doc_id\"]\n        } for chunk in chunks]\n        \n        # Generate embeddings\n        click.echo(\"Generating embeddings...\")\n        embeddings = embedding_model.encode(texts)\n        \n        # Build and save vector store\n        vector_store.build_index(embeddings, metadata)\n        vector_store.save()\n        \n        click.echo(f\"[OK] Ingestion complete! Processed {len(chunks)} chunks.\")\n        \n    except Exception as e:\n        click.echo(f\"[ERROR] Error during ingestion: {e}\")\n        sys.exit(1)\n\n@cli.command()\n@click.option('--query', required=True, help='Search query')\n@click.option('--top-k', default=5, help='Number of results to return')\ndef query(query, top_k):\n    \"\"\"Query the vector store for relevant documents\"\"\"\n    # Load vector store\n    vector_store = VectorStore()\n    if not vector_store.load():\n        click.echo(\"No vector store found. Please ingest documents first.\")\n        return\n    \n    # Search\n    retriever = Retriever(vector_store)\n    results = retriever.search(query, top_k)\n    \n    if not results:\n        click.echo(\"No results found.\")\n        return\n    \n    # Display results\n    click.echo(f\"\\nFound {len(results)} relevant documents:\\n\")\n    for i, result in enumerate(results, 1):\n        click.echo(f\"[{i}] {result['source']}\")\n        click.echo(f\"    Score: {result['score']:.4f}\")\n        click.echo(f\"    Content: {result['text'][:200]}...\")\n        click.echo()\n\n@cli.command()\ndef stats():\n    \"\"\"Show statistics about the vector store\"\"\"\n    vector_store = VectorStore()\n    if vector_store.load():\n        click.echo(f\"Vector store statistics:\")\n        click.echo(f\"  Total vectors: {vector_store.index.ntotal}\")\n        click.echo(f\"  Metadata entries: {len(vector_store.metadata)}\")\n    else:\n        click.echo(\"No vector store found.\")\n\n@cli.command()\ndef clear():\n    \"\"\"Clear the vector store\"\"\"\n    vector_store = VectorStore()\n    vector_store.clear()\n    click.echo(\"Vector store cleared.\")\n\nif __name__ == \"__main__\":\n    cli()\n```\n\n## 📋 Usage Examples\n\n### Basic Workflow\n\n```bash\n# 1. Install dependencies\npip install sentence-transformers faiss-cpu click flask\n\n# 2. Download model (one-time)\npython -c \"from huggingface_hub import snapshot_download; snapshot_download(repo_id='sentence-transformers\u002Fall-MiniLM-L6-v2', local_dir='.\u002Fmodels\u002Fall-MiniLM-L6-v2')\"\n\n# 3. Ingest documents\npython rag.py ingest --docs-path .\u002Fmy-documents\n\n# 4. Query documents\npython rag.py query --query \"What is machine learning?\"\n\n# 5. Check statistics\npython rag.py stats\n```\n\n### Advanced Usage\n\n```bash\n# Custom chunk size\npython rag.py ingest --docs-path .\u002Fdocs --chunk-size 1024 --chunk-overlap 256\n\n# Get top 10 results\npython rag.py query --query \"AI applications\" --top-k 10\n\n# Interactive mode (create your own)\npython rag.py interactive\n```\n\n## 🔧 Troubleshooting\n\n### Model Download Issues\n\n```bash\n# Manual download from HuggingFace\n# Visit: https:\u002F\u002Fhuggingface.co\u002Fsentence-transformers\u002Fall-MiniLM-L6-v2\n# Download all files to .\u002Fmodels\u002Fall-MiniLM-L6-v2\u002F\n```\n\n### Memory Issues\n\n- Reduce chunk size: `--chunk-size 256`\n- Process documents in batches\n- Use smaller embedding model\n\n### Encoding Issues (Windows)\n\n```python\n# Add to rag.py for Windows compatibility\nimport sys\nimport io\nsys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')\n```\n\n## 📁 Project Structure\n\n```\nrag-system\u002F\n├── rag.py                 # CLI interface\n├── embeddings.py          # Embedding generation\n├── vector_store.py        # FAISS storage\n├── retriever.py           # Search functionality\n├── config.py              # Configuration\n├── ingestion.py           # Document processing\n├── models\u002F\n│   └── all-MiniLM-L6-v2\u002F  # Local embedding model\n├── vector_store\u002F          # FAISS index and metadata\n└── documents\u002F             # Your documents folder\n```\n\n## 🎯 Use Cases\n\n1. **Document Q&A System**\n   - Upload document library\n   - Ask questions get relevant answers\n   - Support multiple documents\n\n2. **Knowledge Base Search**\n   - Organize documents in folders\n   - Quick retrieval of relevant information\n   - Generate contextual answers\n\n3. **Research Assistant**\n   - Collect research materials\n   - Fast information lookup\n   - Assist with paper writing\n\n## 📚 References\n\n- **Embedding Model**: sentence-transformers\u002Fall-MiniLM-L6-v2\n- **Vector Database**: FAISS (Facebook AI Similarity Search)\n- **Similarity Metric**: Cosine Similarity\n- **Chunk Size**: 512 tokens (configurable)\n- **Chunk Overlap**: 128 tokens (configurable)\n\n## 🤝 Contributing\n\nThis skill is designed to be extended. You can:\n- Add support for more document formats\n- Implement different embedding models\n- Add web interface features\n- Create specialized RAG systems for specific domains\n\n---\n\n**Skill Version**: 1.0.0  \n**Last Updated**: 2026-03-05  \n**Author**: Wangwang (OpenClaw Personal Assistant)",{"name":5,"description":7},"master","4aa004da461d820f4ea5499e58eb8d196cf99016","community\u002Fclawhub\u002Fr\u002Frag-system-builder",0,"https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge","https:\u002F\u002Fskill-explorer-rho.vercel.app","https:\u002F\u002Fgithub.com\u002FLord1Egypt","Unbreakable. Unstoppable. Unmatched⚡.\r\n Speaker of machine tongues 🤖  | World-builder of decentralized dreams 🌐 | Defender of the digital realm🛡️.","2026-06-10 08:21:01",{"source":8,"skillName":5,"commands":34,"prompt":44,"zipAvailable":45},[35,38,41],{"tool":36,"command":37},"npx","npx skills add Lord1Egypt\u002Fawesome-skill-forge --skill rag-system-builder",{"tool":39,"command":40},"bunx","bunx skills add Lord1Egypt\u002Fawesome-skill-forge --skill rag-system-builder",{"tool":42,"command":43},"pnpm","pnpm dlx skills add Lord1Egypt\u002Fawesome-skill-forge --skill rag-system-builder","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fclawhub\u002Fr\u002Frag-system-builder\u002FSKILL.md",true,[],[48,55,62,69,76,83],{"skillNo":49,"name":50,"nameZh":6,"description":51,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":52,"categories":53,"keywords":54,"publishedAt":19},"01M785WKJB99G3STR1NF9NRTJW","youtube-content","YouTube transcripts to summaries, threads, blogs.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fyoutube-content\u002FSKILL.md",[],[],{"skillNo":56,"name":57,"nameZh":6,"description":58,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":59,"categories":60,"keywords":61,"publishedAt":19},"01M785WEFHB0G2S9YA6EPR3H0E","xurl","X\u002FTwitter via xurl CLI: post, search, DM, media, v2 API.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fxurl\u002FSKILL.md",[],[],{"skillNo":63,"name":64,"nameZh":6,"description":65,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":66,"categories":67,"keywords":68,"publishedAt":19},"01M785W98EDN4EFJXJPMQEHCRC","touchdesigner-mcp","Control a running TouchDesigner instance via twozero MCP — create operators, set parameters, wire connections, execute Python, build real-time visuals. 36 native tools.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Ftouchdesigner-mcp\u002FSKILL.md",[],[],{"skillNo":70,"name":71,"nameZh":6,"description":72,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":73,"categories":74,"keywords":75,"publishedAt":19},"01M785W5S9FP3QBH2V191E025P","test-driven-development","TDD: enforce RED-GREEN-REFACTOR, tests before code.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Ftest-driven-development\u002FSKILL.md",[],[],{"skillNo":77,"name":78,"nameZh":6,"description":79,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":80,"categories":81,"keywords":82,"publishedAt":19},"01M785W2AS08NSSH9YATCV6FJB","teams-meeting-pipeline","Operate the Teams meeting summary pipeline via Hermes CLI — summarize meetings, inspect pipeline status, replay jobs, manage Microsoft Graph subscriptions.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fteams-meeting-pipeline\u002FSKILL.md",[],[],{"skillNo":84,"name":85,"nameZh":6,"description":86,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":87,"categories":88,"keywords":89,"publishedAt":19},"01M785VXKW4T34BTP1SCHW1R7F","systematic-debugging","4-phase root cause debugging: understand bugs before fixing.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fsystematic-debugging\u002FSKILL.md",[],[]]