[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6FK3ZWTCFXDS42NBD0E5TPR":3,"skill-same:01M6FK3ZWTCFXDS42NBD0E5TPR":59},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":26,"linkOnly":27,"markdownContent":28,"markdownBody":29,"frontMatter":30,"refName":32,"commitSha":33,"skillDirectory":34,"forksCount":35,"repositoryHtmlUrl":36,"repositoryHomepageUrl":6,"ownerHtmlUrl":37,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":38,"install":39,"resources":52},"01M6FK3ZWTCFXDS42NBD0E5TPR","rag-construction",null,"Build RAG systems for construction knowledge bases. Create searchable AI-powered construction document systems","kbarbel640-del\u002Fskills","kbarbel640-del","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F255315490?v=4","01M6CJPPQGCCESXMG3K7BBGQ5J","01M6CJPPX2PB2BCZERFVM2C2B3",1,"MIT","https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fdatadrivenconstruction\u002Frag-construction\u002FSKILL.md",[],[18,19,20,21,22,23,24,25],"rag","rag construction","create","knowledge","bases","document","build","systems","2026-11-10 10:12:30",false,"---\r\nslug: \"rag-construction\"\r\ndisplay_name: \"Rag Construction\"\r\ndescription: \"Build RAG systems for construction knowledge bases. Create searchable AI-powered construction document systems\"\r\n---\r\n\r\n# RAG Construction\r\n\r\n## Overview\r\n\r\nBased on DDC methodology (Chapter 2.3), this skill builds Retrieval-Augmented Generation (RAG) systems for construction knowledge bases, enabling semantic search and AI-powered question answering over construction documents.\r\n\r\n**Book Reference:** \"Pandas DataFrame и LLM ChatGPT\" \u002F \"Pandas DataFrame and LLM ChatGPT\"\r\n\r\n## Quick Start\r\n\r\n```python\r\nfrom dataclasses import dataclass, field\r\nfrom enum import Enum\r\nfrom typing import List, Dict, Optional, Any, Callable\r\nfrom datetime import datetime\r\nimport json\r\nimport hashlib\r\nimport re\r\n\r\nclass DocumentType(Enum):\r\n    \"\"\"Types of construction documents\"\"\"\r\n    SPECIFICATION = \"specification\"\r\n    DRAWING = \"drawing\"\r\n    CONTRACT = \"contract\"\r\n    RFI = \"rfi\"\r\n    SUBMITTAL = \"submittal\"\r\n    CHANGE_ORDER = \"change_order\"\r\n    MEETING_MINUTES = \"meeting_minutes\"\r\n    DAILY_REPORT = \"daily_report\"\r\n    SAFETY_REPORT = \"safety_report\"\r\n    INSPECTION = \"inspection\"\r\n    MANUAL = \"manual\"\r\n    STANDARD = \"standard\"\r\n\r\nclass ChunkingStrategy(Enum):\r\n    \"\"\"Text chunking strategies\"\"\"\r\n    FIXED_SIZE = \"fixed_size\"\r\n    PARAGRAPH = \"paragraph\"\r\n    SECTION = \"section\"\r\n    SEMANTIC = \"semantic\"\r\n    SENTENCE = \"sentence\"\r\n\r\n@dataclass\r\nclass DocumentChunk:\r\n    \"\"\"A chunk of document text\"\"\"\r\n    id: str\r\n    document_id: str\r\n    content: str\r\n    metadata: Dict[str, Any]\r\n    embedding: Optional[List[float]] = None\r\n    token_count: int = 0\r\n    position: int = 0\r\n\r\n@dataclass\r\nclass Document:\r\n    \"\"\"Construction document\"\"\"\r\n    id: str\r\n    title: str\r\n    doc_type: DocumentType\r\n    content: str\r\n    source: str\r\n    metadata: Dict[str, Any] = field(default_factory=dict)\r\n    chunks: List[DocumentChunk] = field(default_factory=list)\r\n    created_at: datetime = field(default_factory=datetime.now)\r\n\r\n@dataclass\r\nclass SearchResult:\r\n    \"\"\"Search result from vector store\"\"\"\r\n    chunk: DocumentChunk\r\n    score: float\r\n    document_title: str\r\n    doc_type: DocumentType\r\n\r\n@dataclass\r\nclass RAGResponse:\r\n    \"\"\"Response from RAG system\"\"\"\r\n    query: str\r\n    answer: str\r\n    sources: List[SearchResult]\r\n    confidence: float\r\n    tokens_used: int\r\n\r\n\r\nclass TextChunker:\r\n    \"\"\"Split documents into chunks for embedding\"\"\"\r\n\r\n    def __init__(\r\n        self,\r\n        strategy: ChunkingStrategy = ChunkingStrategy.PARAGRAPH,\r\n        chunk_size: int = 500,\r\n        chunk_overlap: int = 50\r\n    ):\r\n        self.strategy = strategy\r\n        self.chunk_size = chunk_size\r\n        self.chunk_overlap = chunk_overlap\r\n\r\n    def chunk_document(self, document: Document) -> List[DocumentChunk]:\r\n        \"\"\"Split document into chunks\"\"\"\r\n        if self.strategy == ChunkingStrategy.FIXED_SIZE:\r\n            return self._chunk_fixed_size(document)\r\n        elif self.strategy == ChunkingStrategy.PARAGRAPH:\r\n            return self._chunk_by_paragraph(document)\r\n        elif self.strategy == ChunkingStrategy.SECTION:\r\n            return self._chunk_by_section(document)\r\n        elif self.strategy == ChunkingStrategy.SENTENCE:\r\n            return self._chunk_by_sentence(document)\r\n        else:\r\n            return self._chunk_fixed_size(document)\r\n\r\n    def _chunk_fixed_size(self, document: Document) -> List[DocumentChunk]:\r\n        \"\"\"Chunk by fixed character size with overlap\"\"\"\r\n        chunks = []\r\n        text = document.content\r\n        start = 0\r\n        position = 0\r\n\r\n        while start \u003C len(text):\r\n            end = start + self.chunk_size\r\n\r\n            # Find word boundary\r\n            if end \u003C len(text):\r\n                while end > start and text[end] not in ' \\n\\t':\r\n                    end -= 1\r\n\r\n            chunk_text = text[start:end].strip()\r\n            if chunk_text:\r\n                chunk_id = self._generate_chunk_id(document.id, position)\r\n                chunks.append(DocumentChunk(\r\n                    id=chunk_id,\r\n                    document_id=document.id,\r\n                    content=chunk_text,\r\n                    metadata={\r\n                        \"doc_type\": document.doc_type.value,\r\n                        \"title\": document.title,\r\n                        **document.metadata\r\n                    },\r\n                    token_count=len(chunk_text.split()),\r\n                    position=position\r\n                ))\r\n                position += 1\r\n\r\n            start = end - self.chunk_overlap\r\n            if start >= len(text):\r\n                break\r\n\r\n        return chunks\r\n\r\n    def _chunk_by_paragraph(self, document: Document) -> List[DocumentChunk]:\r\n        \"\"\"Chunk by paragraphs\"\"\"\r\n        chunks = []\r\n        paragraphs = document.content.split('\\n\\n')\r\n        current_chunk = \"\"\r\n        position = 0\r\n\r\n        for para in paragraphs:\r\n            para = para.strip()\r\n            if not para:\r\n                continue\r\n\r\n            if len(current_chunk) + len(para) \u003C self.chunk_size:\r\n                current_chunk += \"\\n\\n\" + para if current_chunk else para\r\n            else:\r\n                if current_chunk:\r\n                    chunk_id = self._generate_chunk_id(document.id, position)\r\n                    chunks.append(DocumentChunk(\r\n                        id=chunk_id,\r\n                        document_id=document.id,\r\n                        content=current_chunk,\r\n                        metadata={\r\n                            \"doc_type\": document.doc_type.value,\r\n                            \"title\": document.title,\r\n                            **document.metadata\r\n                        },\r\n                        token_count=len(current_chunk.split()),\r\n                        position=position\r\n                    ))\r\n                    position += 1\r\n                current_chunk = para\r\n\r\n        # Add remaining content\r\n        if current_chunk:\r\n            chunk_id = self._generate_chunk_id(document.id, position)\r\n            chunks.append(DocumentChunk(\r\n                id=chunk_id,\r\n                document_id=document.id,\r\n                content=current_chunk,\r\n                metadata={\r\n                    \"doc_type\": document.doc_type.value,\r\n                    \"title\": document.title,\r\n                    **document.metadata\r\n                },\r\n                token_count=len(current_chunk.split()),\r\n                position=position\r\n            ))\r\n\r\n        return chunks\r\n\r\n    def _chunk_by_section(self, document: Document) -> List[DocumentChunk]:\r\n        \"\"\"Chunk by document sections (headers)\"\"\"\r\n        # Split by common section patterns\r\n        section_pattern = r'\\n(?=(?:\\d+\\.|\\d+\\s|SECTION|ARTICLE|PART)\\s+[A-Z])'\r\n        sections = re.split(section_pattern, document.content)\r\n\r\n        chunks = []\r\n        for position, section in enumerate(sections):\r\n            section = section.strip()\r\n            if section:\r\n                # If section is too large, further split it\r\n                if len(section) > self.chunk_size * 2:\r\n                    sub_chunker = TextChunker(ChunkingStrategy.PARAGRAPH, self.chunk_size)\r\n                    sub_doc = Document(\r\n                        id=f\"{document.id}_sec{position}\",\r\n                        title=document.title,\r\n                        doc_type=document.doc_type,\r\n                        content=section,\r\n                        source=document.source,\r\n                        metadata=document.metadata\r\n                    )\r\n                    sub_chunks = sub_chunker.chunk_document(sub_doc)\r\n                    for i, chunk in enumerate(sub_chunks):\r\n                        chunk.id = self._generate_chunk_id(document.id, position * 100 + i)\r\n                        chunk.position = position * 100 + i\r\n                    chunks.extend(sub_chunks)\r\n                else:\r\n                    chunk_id = self._generate_chunk_id(document.id, position)\r\n                    chunks.append(DocumentChunk(\r\n                        id=chunk_id,\r\n                        document_id=document.id,\r\n                        content=section,\r\n                        metadata={\r\n                            \"doc_type\": document.doc_type.value,\r\n                            \"title\": document.title,\r\n                            **document.metadata\r\n                        },\r\n                        token_count=len(section.split()),\r\n                        position=position\r\n                    ))\r\n\r\n        return chunks\r\n\r\n    def _chunk_by_sentence(self, document: Document) -> List[DocumentChunk]:\r\n        \"\"\"Chunk by sentences, grouping to meet size requirements\"\"\"\r\n        # Simple sentence splitting\r\n        sentences = re.split(r'(?\u003C=[.!?])\\s+', document.content)\r\n\r\n        chunks = []\r\n        current_chunk = \"\"\r\n        position = 0\r\n\r\n        for sentence in sentences:\r\n            if len(current_chunk) + len(sentence) \u003C self.chunk_size:\r\n                current_chunk += \" \" + sentence if current_chunk else sentence\r\n            else:\r\n                if current_chunk:\r\n                    chunk_id = self._generate_chunk_id(document.id, position)\r\n                    chunks.append(DocumentChunk(\r\n                        id=chunk_id,\r\n                        document_id=document.id,\r\n                        content=current_chunk.strip(),\r\n                        metadata={\r\n                            \"doc_type\": document.doc_type.value,\r\n                            \"title\": document.title,\r\n                            **document.metadata\r\n                        },\r\n                        token_count=len(current_chunk.split()),\r\n                        position=position\r\n                    ))\r\n                    position += 1\r\n                current_chunk = sentence\r\n\r\n        if current_chunk:\r\n            chunk_id = self._generate_chunk_id(document.id, position)\r\n            chunks.append(DocumentChunk(\r\n                id=chunk_id,\r\n                document_id=document.id,\r\n                content=current_chunk.strip(),\r\n                metadata={\r\n                    \"doc_type\": document.doc_type.value,\r\n                    \"title\": document.title,\r\n                    **document.metadata\r\n                },\r\n                token_count=len(current_chunk.split()),\r\n                position=position\r\n            ))\r\n\r\n        return chunks\r\n\r\n    def _generate_chunk_id(self, doc_id: str, position: int) -> str:\r\n        \"\"\"Generate unique chunk ID\"\"\"\r\n        return hashlib.md5(f\"{doc_id}_{position}\".encode()).hexdigest()[:12]\r\n\r\n\r\nclass VectorStore:\r\n    \"\"\"Simple in-memory vector store for RAG\"\"\"\r\n\r\n    def __init__(self):\r\n        self.chunks: Dict[str, DocumentChunk] = {}\r\n        self.embeddings: Dict[str, List[float]] = {}\r\n\r\n    def add_chunks(self, chunks: List[DocumentChunk]):\r\n        \"\"\"Add chunks to the store\"\"\"\r\n        for chunk in chunks:\r\n            self.chunks[chunk.id] = chunk\r\n            if chunk.embedding:\r\n                self.embeddings[chunk.id] = chunk.embedding\r\n\r\n    def search(\r\n        self,\r\n        query_embedding: List[float],\r\n        top_k: int = 5,\r\n        filter_metadata: Optional[Dict] = None\r\n    ) -> List[Tuple[DocumentChunk, float]]:\r\n        \"\"\"Search for similar chunks\"\"\"\r\n        results = []\r\n\r\n        for chunk_id, chunk in self.chunks.items():\r\n            # Apply metadata filter\r\n            if filter_metadata:\r\n                match = all(\r\n                    chunk.metadata.get(k) == v\r\n                    for k, v in filter_metadata.items()\r\n                )\r\n                if not match:\r\n                    continue\r\n\r\n            # Calculate similarity (cosine similarity simulation)\r\n            if chunk_id in self.embeddings:\r\n                score = self._cosine_similarity(query_embedding, self.embeddings[chunk_id])\r\n                results.append((chunk, score))\r\n\r\n        # Sort by score descending\r\n        results.sort(key=lambda x: x[1], reverse=True)\r\n        return results[:top_k]\r\n\r\n    def _cosine_similarity(self, a: List[float], b: List[float]) -> float:\r\n        \"\"\"Calculate cosine similarity between two vectors\"\"\"\r\n        if len(a) != len(b):\r\n            return 0.0\r\n\r\n        dot_product = sum(x * y for x, y in zip(a, b))\r\n        norm_a = sum(x * x for x in a) ** 0.5\r\n        norm_b = sum(x * x for x in b) ** 0.5\r\n\r\n        if norm_a == 0 or norm_b == 0:\r\n            return 0.0\r\n\r\n        return dot_product \u002F (norm_a * norm_b)\r\n\r\n    def get_stats(self) -> Dict:\r\n        \"\"\"Get store statistics\"\"\"\r\n        doc_types = {}\r\n        for chunk in self.chunks.values():\r\n            doc_type = chunk.metadata.get(\"doc_type\", \"unknown\")\r\n            doc_types[doc_type] = doc_types.get(doc_type, 0) + 1\r\n\r\n        return {\r\n            \"total_chunks\": len(self.chunks),\r\n            \"chunks_with_embeddings\": len(self.embeddings),\r\n            \"chunks_by_type\": doc_types\r\n        }\r\n\r\n\r\nclass EmbeddingModel:\r\n    \"\"\"Simulated embedding model (replace with actual model in production)\"\"\"\r\n\r\n    def __init__(self, model_name: str = \"text-embedding-ada-002\"):\r\n        self.model_name = model_name\r\n        self.dimension = 1536\r\n\r\n    def embed(self, text: str) -> List[float]:\r\n        \"\"\"Generate embedding for text\"\"\"\r\n        # Simulation: generate deterministic embedding based on text hash\r\n        text_hash = hashlib.sha256(text.encode()).digest()\r\n        embedding = []\r\n        for i in range(self.dimension):\r\n            byte_idx = i % len(text_hash)\r\n            embedding.append((text_hash[byte_idx] - 128) \u002F 128.0)\r\n        return embedding\r\n\r\n    def embed_batch(self, texts: List[str]) -> List[List[float]]:\r\n        \"\"\"Generate embeddings for multiple texts\"\"\"\r\n        return [self.embed(text) for text in texts]\r\n\r\n\r\nclass ConstructionRAG:\r\n    \"\"\"\r\n    RAG system for construction knowledge bases.\r\n    Based on DDC methodology Chapter 2.3.\r\n    \"\"\"\r\n\r\n    def __init__(\r\n        self,\r\n        embedding_model: Optional[EmbeddingModel] = None,\r\n        chunking_strategy: ChunkingStrategy = ChunkingStrategy.PARAGRAPH,\r\n        chunk_size: int = 500\r\n    ):\r\n        self.embedding_model = embedding_model or EmbeddingModel()\r\n        self.chunker = TextChunker(chunking_strategy, chunk_size)\r\n        self.vector_store = VectorStore()\r\n        self.documents: Dict[str, Document] = {}\r\n\r\n    def add_document(self, document: Document) -> int:\r\n        \"\"\"\r\n        Add a document to the knowledge base.\r\n\r\n        Args:\r\n            document: Document to add\r\n\r\n        Returns:\r\n            Number of chunks created\r\n        \"\"\"\r\n        # Store document\r\n        self.documents[document.id] = document\r\n\r\n        # Chunk document\r\n        chunks = self.chunker.chunk_document(document)\r\n\r\n        # Generate embeddings\r\n        for chunk in chunks:\r\n            chunk.embedding = self.embedding_model.embed(chunk.content)\r\n\r\n        # Add to vector store\r\n        self.vector_store.add_chunks(chunks)\r\n\r\n        # Update document with chunks\r\n        document.chunks = chunks\r\n\r\n        return len(chunks)\r\n\r\n    def add_documents(self, documents: List[Document]) -> Dict[str, int]:\r\n        \"\"\"Add multiple documents\"\"\"\r\n        results = {}\r\n        for doc in documents:\r\n            results[doc.id] = self.add_document(doc)\r\n        return results\r\n\r\n    def search(\r\n        self,\r\n        query: str,\r\n        top_k: int = 5,\r\n        doc_type: Optional[DocumentType] = None\r\n    ) -> List[SearchResult]:\r\n        \"\"\"\r\n        Search the knowledge base.\r\n\r\n        Args:\r\n            query: Search query\r\n            top_k: Number of results to return\r\n            doc_type: Filter by document type\r\n\r\n        Returns:\r\n            List of search results\r\n        \"\"\"\r\n        # Generate query embedding\r\n        query_embedding = self.embedding_model.embed(query)\r\n\r\n        # Build filter\r\n        filter_metadata = None\r\n        if doc_type:\r\n            filter_metadata = {\"doc_type\": doc_type.value}\r\n\r\n        # Search vector store\r\n        results = self.vector_store.search(\r\n            query_embedding,\r\n            top_k=top_k,\r\n            filter_metadata=filter_metadata\r\n        )\r\n\r\n        # Build search results\r\n        search_results = []\r\n        for chunk, score in results:\r\n            doc = self.documents.get(chunk.document_id)\r\n            search_results.append(SearchResult(\r\n                chunk=chunk,\r\n                score=score,\r\n                document_title=doc.title if doc else \"Unknown\",\r\n                doc_type=doc.doc_type if doc else DocumentType.MANUAL\r\n            ))\r\n\r\n        return search_results\r\n\r\n    def query(\r\n        self,\r\n        question: str,\r\n        top_k: int = 5,\r\n        doc_type: Optional[DocumentType] = None\r\n    ) -> RAGResponse:\r\n        \"\"\"\r\n        Answer a question using RAG.\r\n\r\n        Args:\r\n            question: Question to answer\r\n            top_k: Number of context chunks to use\r\n            doc_type: Filter by document type\r\n\r\n        Returns:\r\n            RAG response with answer and sources\r\n        \"\"\"\r\n        # Search for relevant context\r\n        search_results = self.search(question, top_k=top_k, doc_type=doc_type)\r\n\r\n        if not search_results:\r\n            return RAGResponse(\r\n                query=question,\r\n                answer=\"I couldn't find relevant information to answer this question.\",\r\n                sources=[],\r\n                confidence=0.0,\r\n                tokens_used=0\r\n            )\r\n\r\n        # Build context from search results\r\n        context_parts = []\r\n        for i, result in enumerate(search_results):\r\n            context_parts.append(\r\n                f\"[Source {i+1}: {result.document_title}]\\n{result.chunk.content}\"\r\n            )\r\n\r\n        context = \"\\n\\n\".join(context_parts)\r\n\r\n        # Generate answer (simulated - in production, call LLM)\r\n        answer = self._generate_answer(question, context, search_results)\r\n\r\n        # Calculate confidence\r\n        avg_score = sum(r.score for r in search_results) \u002F len(search_results)\r\n\r\n        return RAGResponse(\r\n            query=question,\r\n            answer=answer,\r\n            sources=search_results,\r\n            confidence=avg_score,\r\n            tokens_used=len(context.split()) + len(question.split())\r\n        )\r\n\r\n    def _generate_answer(\r\n        self,\r\n        question: str,\r\n        context: str,\r\n        sources: List[SearchResult]\r\n    ) -> str:\r\n        \"\"\"\r\n        Generate answer from context.\r\n        In production, this would call an LLM API.\r\n        \"\"\"\r\n        # Simulated answer generation\r\n        answer_parts = [\r\n            f\"Based on the available construction documentation:\\n\"\r\n        ]\r\n\r\n        # Extract key information from sources\r\n        for source in sources[:3]:\r\n            # Take first sentence of each relevant chunk\r\n            first_sentence = source.chunk.content.split('.')[0] + '.'\r\n            answer_parts.append(f\"- {first_sentence}\")\r\n\r\n        answer_parts.append(\r\n            f\"\\n\\nThis information comes from {len(sources)} source documents \"\r\n            f\"including: {', '.join(set(s.document_title for s in sources[:3]))}.\"\r\n        )\r\n\r\n        return \"\\n\".join(answer_parts)\r\n\r\n    def get_document_summary(self, document_id: str) -> Optional[Dict]:\r\n        \"\"\"Get summary of a document\"\"\"\r\n        doc = self.documents.get(document_id)\r\n        if not doc:\r\n            return None\r\n\r\n        return {\r\n            \"id\": doc.id,\r\n            \"title\": doc.title,\r\n            \"type\": doc.doc_type.value,\r\n            \"chunks\": len(doc.chunks),\r\n            \"total_tokens\": sum(c.token_count for c in doc.chunks),\r\n            \"source\": doc.source,\r\n            \"created_at\": doc.created_at.isoformat()\r\n        }\r\n\r\n    def get_stats(self) -> Dict:\r\n        \"\"\"Get system statistics\"\"\"\r\n        return {\r\n            \"total_documents\": len(self.documents),\r\n            \"vector_store\": self.vector_store.get_stats(),\r\n            \"embedding_model\": self.embedding_model.model_name,\r\n            \"chunking_strategy\": self.chunker.strategy.value\r\n        }\r\n\r\n    def export_knowledge_base(self) -> Dict:\r\n        \"\"\"Export knowledge base for backup\u002Ftransfer\"\"\"\r\n        return {\r\n            \"documents\": [\r\n                {\r\n                    \"id\": doc.id,\r\n                    \"title\": doc.title,\r\n                    \"type\": doc.doc_type.value,\r\n                    \"content\": doc.content,\r\n                    \"source\": doc.source,\r\n                    \"metadata\": doc.metadata\r\n                }\r\n                for doc in self.documents.values()\r\n            ],\r\n            \"stats\": self.get_stats(),\r\n            \"exported_at\": datetime.now().isoformat()\r\n        }\r\n```\r\n\r\n## Common Use Cases\r\n\r\n### Build Construction Knowledge Base\r\n\r\n```python\r\nrag = ConstructionRAG(\r\n    chunking_strategy=ChunkingStrategy.SECTION,\r\n    chunk_size=500\r\n)\r\n\r\n# Add specifications\r\nspec_doc = Document(\r\n    id=\"spec-03300\",\r\n    title=\"Cast-in-Place Concrete Specification\",\r\n    doc_type=DocumentType.SPECIFICATION,\r\n    content=\"\"\"\r\n    SECTION 03 30 00 - CAST-IN-PLACE CONCRETE\r\n\r\n    PART 1 - GENERAL\r\n    1.1 SUMMARY\r\n    A. Section includes cast-in-place concrete for foundations,\r\n       slabs, walls, and other structural elements.\r\n\r\n    1.2 RELATED SECTIONS\r\n    A. Section 03 10 00 - Concrete Forming\r\n    B. Section 03 20 00 - Concrete Reinforcing\r\n\r\n    PART 2 - PRODUCTS\r\n    2.1 CONCRETE MATERIALS\r\n    A. Portland Cement: ASTM C150, Type I or II\r\n    B. Aggregates: ASTM C33, graded\r\n    C. Water: Clean, potable\r\n    \"\"\",\r\n    source=\"project_specs.pdf\",\r\n    metadata={\"division\": \"03\", \"project\": \"Building A\"}\r\n)\r\n\r\nchunks_created = rag.add_document(spec_doc)\r\nprint(f\"Created {chunks_created} chunks\")\r\n```\r\n\r\n### Search Knowledge Base\r\n\r\n```python\r\n# Search for concrete requirements\r\nresults = rag.search(\r\n    query=\"concrete strength requirements\",\r\n    top_k=5,\r\n    doc_type=DocumentType.SPECIFICATION\r\n)\r\n\r\nfor result in results:\r\n    print(f\"Score: {result.score:.3f}\")\r\n    print(f\"Document: {result.document_title}\")\r\n    print(f\"Content: {result.chunk.content[:200]}...\")\r\n    print()\r\n```\r\n\r\n### Answer Questions with RAG\r\n\r\n```python\r\nresponse = rag.query(\r\n    question=\"What type of cement should be used for foundations?\",\r\n    top_k=3\r\n)\r\n\r\nprint(f\"Answer: {response.answer}\")\r\nprint(f\"Confidence: {response.confidence:.0%}\")\r\nprint(f\"Sources: {len(response.sources)}\")\r\n```\r\n\r\n## Quick Reference\r\n\r\n| Component | Purpose |\r\n|-----------|---------|\r\n| `ConstructionRAG` | Main RAG system |\r\n| `TextChunker` | Document chunking |\r\n| `VectorStore` | Embedding storage |\r\n| `EmbeddingModel` | Text embeddings |\r\n| `DocumentChunk` | Chunk with metadata |\r\n| `RAGResponse` | Query response |\r\n\r\n## Resources\r\n\r\n- **Book**: \"Data-Driven Construction\" by Artem Boiko, Chapter 2.3\r\n- **Website**: https:\u002F\u002Fdatadrivenconstruction.io\r\n\r\n## Next Steps\r\n\r\n- Use [llm-data-automation](..\u002Fllm-data-automation\u002FSKILL.md) for automation\r\n- Use [vector-search](..\u002F..\u002FChapter-4.4\u002Fvector-search\u002FSKILL.md) for advanced search\r\n- Use [document-classification-nlp](..\u002F..\u002F..\u002FDDC_Innovative\u002Fdocument-classification-nlp\u002FSKILL.md) for classification\r\n","# RAG Construction\r\n\r\n## Overview\r\n\r\nBased on DDC methodology (Chapter 2.3), this skill builds Retrieval-Augmented Generation (RAG) systems for construction knowledge bases, enabling semantic search and AI-powered question answering over construction documents.\r\n\r\n**Book Reference:** \"Pandas DataFrame и LLM ChatGPT\" \u002F \"Pandas DataFrame and LLM ChatGPT\"\r\n\r\n## Quick Start\r\n\r\n```python\r\nfrom dataclasses import dataclass, field\r\nfrom enum import Enum\r\nfrom typing import List, Dict, Optional, Any, Callable\r\nfrom datetime import datetime\r\nimport json\r\nimport hashlib\r\nimport re\r\n\r\nclass DocumentType(Enum):\r\n    \"\"\"Types of construction documents\"\"\"\r\n    SPECIFICATION = \"specification\"\r\n    DRAWING = \"drawing\"\r\n    CONTRACT = \"contract\"\r\n    RFI = \"rfi\"\r\n    SUBMITTAL = \"submittal\"\r\n    CHANGE_ORDER = \"change_order\"\r\n    MEETING_MINUTES = \"meeting_minutes\"\r\n    DAILY_REPORT = \"daily_report\"\r\n    SAFETY_REPORT = \"safety_report\"\r\n    INSPECTION = \"inspection\"\r\n    MANUAL = \"manual\"\r\n    STANDARD = \"standard\"\r\n\r\nclass ChunkingStrategy(Enum):\r\n    \"\"\"Text chunking strategies\"\"\"\r\n    FIXED_SIZE = \"fixed_size\"\r\n    PARAGRAPH = \"paragraph\"\r\n    SECTION = \"section\"\r\n    SEMANTIC = \"semantic\"\r\n    SENTENCE = \"sentence\"\r\n\r\n@dataclass\r\nclass DocumentChunk:\r\n    \"\"\"A chunk of document text\"\"\"\r\n    id: str\r\n    document_id: str\r\n    content: str\r\n    metadata: Dict[str, Any]\r\n    embedding: Optional[List[float]] = None\r\n    token_count: int = 0\r\n    position: int = 0\r\n\r\n@dataclass\r\nclass Document:\r\n    \"\"\"Construction document\"\"\"\r\n    id: str\r\n    title: str\r\n    doc_type: DocumentType\r\n    content: str\r\n    source: str\r\n    metadata: Dict[str, Any] = field(default_factory=dict)\r\n    chunks: List[DocumentChunk] = field(default_factory=list)\r\n    created_at: datetime = field(default_factory=datetime.now)\r\n\r\n@dataclass\r\nclass SearchResult:\r\n    \"\"\"Search result from vector store\"\"\"\r\n    chunk: DocumentChunk\r\n    score: float\r\n    document_title: str\r\n    doc_type: DocumentType\r\n\r\n@dataclass\r\nclass RAGResponse:\r\n    \"\"\"Response from RAG system\"\"\"\r\n    query: str\r\n    answer: str\r\n    sources: List[SearchResult]\r\n    confidence: float\r\n    tokens_used: int\r\n\r\n\r\nclass TextChunker:\r\n    \"\"\"Split documents into chunks for embedding\"\"\"\r\n\r\n    def __init__(\r\n        self,\r\n        strategy: ChunkingStrategy = ChunkingStrategy.PARAGRAPH,\r\n        chunk_size: int = 500,\r\n        chunk_overlap: int = 50\r\n    ):\r\n        self.strategy = strategy\r\n        self.chunk_size = chunk_size\r\n        self.chunk_overlap = chunk_overlap\r\n\r\n    def chunk_document(self, document: Document) -> List[DocumentChunk]:\r\n        \"\"\"Split document into chunks\"\"\"\r\n        if self.strategy == ChunkingStrategy.FIXED_SIZE:\r\n            return self._chunk_fixed_size(document)\r\n        elif self.strategy == ChunkingStrategy.PARAGRAPH:\r\n            return self._chunk_by_paragraph(document)\r\n        elif self.strategy == ChunkingStrategy.SECTION:\r\n            return self._chunk_by_section(document)\r\n        elif self.strategy == ChunkingStrategy.SENTENCE:\r\n            return self._chunk_by_sentence(document)\r\n        else:\r\n            return self._chunk_fixed_size(document)\r\n\r\n    def _chunk_fixed_size(self, document: Document) -> List[DocumentChunk]:\r\n        \"\"\"Chunk by fixed character size with overlap\"\"\"\r\n        chunks = []\r\n        text = document.content\r\n        start = 0\r\n        position = 0\r\n\r\n        while start \u003C len(text):\r\n            end = start + self.chunk_size\r\n\r\n            # Find word boundary\r\n            if end \u003C len(text):\r\n                while end > start and text[end] not in ' \\n\\t':\r\n                    end -= 1\r\n\r\n            chunk_text = text[start:end].strip()\r\n            if chunk_text:\r\n                chunk_id = self._generate_chunk_id(document.id, position)\r\n                chunks.append(DocumentChunk(\r\n                    id=chunk_id,\r\n                    document_id=document.id,\r\n                    content=chunk_text,\r\n                    metadata={\r\n                        \"doc_type\": document.doc_type.value,\r\n                        \"title\": document.title,\r\n                        **document.metadata\r\n                    },\r\n                    token_count=len(chunk_text.split()),\r\n                    position=position\r\n                ))\r\n                position += 1\r\n\r\n            start = end - self.chunk_overlap\r\n            if start >= len(text):\r\n                break\r\n\r\n        return chunks\r\n\r\n    def _chunk_by_paragraph(self, document: Document) -> List[DocumentChunk]:\r\n        \"\"\"Chunk by paragraphs\"\"\"\r\n        chunks = []\r\n        paragraphs = document.content.split('\\n\\n')\r\n        current_chunk = \"\"\r\n        position = 0\r\n\r\n        for para in paragraphs:\r\n            para = para.strip()\r\n            if not para:\r\n                continue\r\n\r\n            if len(current_chunk) + len(para) \u003C self.chunk_size:\r\n                current_chunk += \"\\n\\n\" + para if current_chunk else para\r\n            else:\r\n                if current_chunk:\r\n                    chunk_id = self._generate_chunk_id(document.id, position)\r\n                    chunks.append(DocumentChunk(\r\n                        id=chunk_id,\r\n                        document_id=document.id,\r\n                        content=current_chunk,\r\n                        metadata={\r\n                            \"doc_type\": document.doc_type.value,\r\n                            \"title\": document.title,\r\n                            **document.metadata\r\n                        },\r\n                        token_count=len(current_chunk.split()),\r\n                        position=position\r\n                    ))\r\n                    position += 1\r\n                current_chunk = para\r\n\r\n        # Add remaining content\r\n        if current_chunk:\r\n            chunk_id = self._generate_chunk_id(document.id, position)\r\n            chunks.append(DocumentChunk(\r\n                id=chunk_id,\r\n                document_id=document.id,\r\n                content=current_chunk,\r\n                metadata={\r\n                    \"doc_type\": document.doc_type.value,\r\n                    \"title\": document.title,\r\n                    **document.metadata\r\n                },\r\n                token_count=len(current_chunk.split()),\r\n                position=position\r\n            ))\r\n\r\n        return chunks\r\n\r\n    def _chunk_by_section(self, document: Document) -> List[DocumentChunk]:\r\n        \"\"\"Chunk by document sections (headers)\"\"\"\r\n        # Split by common section patterns\r\n        section_pattern = r'\\n(?=(?:\\d+\\.|\\d+\\s|SECTION|ARTICLE|PART)\\s+[A-Z])'\r\n        sections = re.split(section_pattern, document.content)\r\n\r\n        chunks = []\r\n        for position, section in enumerate(sections):\r\n            section = section.strip()\r\n            if section:\r\n                # If section is too large, further split it\r\n                if len(section) > self.chunk_size * 2:\r\n                    sub_chunker = TextChunker(ChunkingStrategy.PARAGRAPH, self.chunk_size)\r\n                    sub_doc = Document(\r\n                        id=f\"{document.id}_sec{position}\",\r\n                        title=document.title,\r\n                        doc_type=document.doc_type,\r\n                        content=section,\r\n                        source=document.source,\r\n                        metadata=document.metadata\r\n                    )\r\n                    sub_chunks = sub_chunker.chunk_document(sub_doc)\r\n                    for i, chunk in enumerate(sub_chunks):\r\n                        chunk.id = self._generate_chunk_id(document.id, position * 100 + i)\r\n                        chunk.position = position * 100 + i\r\n                    chunks.extend(sub_chunks)\r\n                else:\r\n                    chunk_id = self._generate_chunk_id(document.id, position)\r\n                    chunks.append(DocumentChunk(\r\n                        id=chunk_id,\r\n                        document_id=document.id,\r\n                        content=section,\r\n                        metadata={\r\n                            \"doc_type\": document.doc_type.value,\r\n                            \"title\": document.title,\r\n                            **document.metadata\r\n                        },\r\n                        token_count=len(section.split()),\r\n                        position=position\r\n                    ))\r\n\r\n        return chunks\r\n\r\n    def _chunk_by_sentence(self, document: Document) -> List[DocumentChunk]:\r\n        \"\"\"Chunk by sentences, grouping to meet size requirements\"\"\"\r\n        # Simple sentence splitting\r\n        sentences = re.split(r'(?\u003C=[.!?])\\s+', document.content)\r\n\r\n        chunks = []\r\n        current_chunk = \"\"\r\n        position = 0\r\n\r\n        for sentence in sentences:\r\n            if len(current_chunk) + len(sentence) \u003C self.chunk_size:\r\n                current_chunk += \" \" + sentence if current_chunk else sentence\r\n            else:\r\n                if current_chunk:\r\n                    chunk_id = self._generate_chunk_id(document.id, position)\r\n                    chunks.append(DocumentChunk(\r\n                        id=chunk_id,\r\n                        document_id=document.id,\r\n                        content=current_chunk.strip(),\r\n                        metadata={\r\n                            \"doc_type\": document.doc_type.value,\r\n                            \"title\": document.title,\r\n                            **document.metadata\r\n                        },\r\n                        token_count=len(current_chunk.split()),\r\n                        position=position\r\n                    ))\r\n                    position += 1\r\n                current_chunk = sentence\r\n\r\n        if current_chunk:\r\n            chunk_id = self._generate_chunk_id(document.id, position)\r\n            chunks.append(DocumentChunk(\r\n                id=chunk_id,\r\n                document_id=document.id,\r\n                content=current_chunk.strip(),\r\n                metadata={\r\n                    \"doc_type\": document.doc_type.value,\r\n                    \"title\": document.title,\r\n                    **document.metadata\r\n                },\r\n                token_count=len(current_chunk.split()),\r\n                position=position\r\n            ))\r\n\r\n        return chunks\r\n\r\n    def _generate_chunk_id(self, doc_id: str, position: int) -> str:\r\n        \"\"\"Generate unique chunk ID\"\"\"\r\n        return hashlib.md5(f\"{doc_id}_{position}\".encode()).hexdigest()[:12]\r\n\r\n\r\nclass VectorStore:\r\n    \"\"\"Simple in-memory vector store for RAG\"\"\"\r\n\r\n    def __init__(self):\r\n        self.chunks: Dict[str, DocumentChunk] = {}\r\n        self.embeddings: Dict[str, List[float]] = {}\r\n\r\n    def add_chunks(self, chunks: List[DocumentChunk]):\r\n        \"\"\"Add chunks to the store\"\"\"\r\n        for chunk in chunks:\r\n            self.chunks[chunk.id] = chunk\r\n            if chunk.embedding:\r\n                self.embeddings[chunk.id] = chunk.embedding\r\n\r\n    def search(\r\n        self,\r\n        query_embedding: List[float],\r\n        top_k: int = 5,\r\n        filter_metadata: Optional[Dict] = None\r\n    ) -> List[Tuple[DocumentChunk, float]]:\r\n        \"\"\"Search for similar chunks\"\"\"\r\n        results = []\r\n\r\n        for chunk_id, chunk in self.chunks.items():\r\n            # Apply metadata filter\r\n            if filter_metadata:\r\n                match = all(\r\n                    chunk.metadata.get(k) == v\r\n                    for k, v in filter_metadata.items()\r\n                )\r\n                if not match:\r\n                    continue\r\n\r\n            # Calculate similarity (cosine similarity simulation)\r\n            if chunk_id in self.embeddings:\r\n                score = self._cosine_similarity(query_embedding, self.embeddings[chunk_id])\r\n                results.append((chunk, score))\r\n\r\n        # Sort by score descending\r\n        results.sort(key=lambda x: x[1], reverse=True)\r\n        return results[:top_k]\r\n\r\n    def _cosine_similarity(self, a: List[float], b: List[float]) -> float:\r\n        \"\"\"Calculate cosine similarity between two vectors\"\"\"\r\n        if len(a) != len(b):\r\n            return 0.0\r\n\r\n        dot_product = sum(x * y for x, y in zip(a, b))\r\n        norm_a = sum(x * x for x in a) ** 0.5\r\n        norm_b = sum(x * x for x in b) ** 0.5\r\n\r\n        if norm_a == 0 or norm_b == 0:\r\n            return 0.0\r\n\r\n        return dot_product \u002F (norm_a * norm_b)\r\n\r\n    def get_stats(self) -> Dict:\r\n        \"\"\"Get store statistics\"\"\"\r\n        doc_types = {}\r\n        for chunk in self.chunks.values():\r\n            doc_type = chunk.metadata.get(\"doc_type\", \"unknown\")\r\n            doc_types[doc_type] = doc_types.get(doc_type, 0) + 1\r\n\r\n        return {\r\n            \"total_chunks\": len(self.chunks),\r\n            \"chunks_with_embeddings\": len(self.embeddings),\r\n            \"chunks_by_type\": doc_types\r\n        }\r\n\r\n\r\nclass EmbeddingModel:\r\n    \"\"\"Simulated embedding model (replace with actual model in production)\"\"\"\r\n\r\n    def __init__(self, model_name: str = \"text-embedding-ada-002\"):\r\n        self.model_name = model_name\r\n        self.dimension = 1536\r\n\r\n    def embed(self, text: str) -> List[float]:\r\n        \"\"\"Generate embedding for text\"\"\"\r\n        # Simulation: generate deterministic embedding based on text hash\r\n        text_hash = hashlib.sha256(text.encode()).digest()\r\n        embedding = []\r\n        for i in range(self.dimension):\r\n            byte_idx = i % len(text_hash)\r\n            embedding.append((text_hash[byte_idx] - 128) \u002F 128.0)\r\n        return embedding\r\n\r\n    def embed_batch(self, texts: List[str]) -> List[List[float]]:\r\n        \"\"\"Generate embeddings for multiple texts\"\"\"\r\n        return [self.embed(text) for text in texts]\r\n\r\n\r\nclass ConstructionRAG:\r\n    \"\"\"\r\n    RAG system for construction knowledge bases.\r\n    Based on DDC methodology Chapter 2.3.\r\n    \"\"\"\r\n\r\n    def __init__(\r\n        self,\r\n        embedding_model: Optional[EmbeddingModel] = None,\r\n        chunking_strategy: ChunkingStrategy = ChunkingStrategy.PARAGRAPH,\r\n        chunk_size: int = 500\r\n    ):\r\n        self.embedding_model = embedding_model or EmbeddingModel()\r\n        self.chunker = TextChunker(chunking_strategy, chunk_size)\r\n        self.vector_store = VectorStore()\r\n        self.documents: Dict[str, Document] = {}\r\n\r\n    def add_document(self, document: Document) -> int:\r\n        \"\"\"\r\n        Add a document to the knowledge base.\r\n\r\n        Args:\r\n            document: Document to add\r\n\r\n        Returns:\r\n            Number of chunks created\r\n        \"\"\"\r\n        # Store document\r\n        self.documents[document.id] = document\r\n\r\n        # Chunk document\r\n        chunks = self.chunker.chunk_document(document)\r\n\r\n        # Generate embeddings\r\n        for chunk in chunks:\r\n            chunk.embedding = self.embedding_model.embed(chunk.content)\r\n\r\n        # Add to vector store\r\n        self.vector_store.add_chunks(chunks)\r\n\r\n        # Update document with chunks\r\n        document.chunks = chunks\r\n\r\n        return len(chunks)\r\n\r\n    def add_documents(self, documents: List[Document]) -> Dict[str, int]:\r\n        \"\"\"Add multiple documents\"\"\"\r\n        results = {}\r\n        for doc in documents:\r\n            results[doc.id] = self.add_document(doc)\r\n        return results\r\n\r\n    def search(\r\n        self,\r\n        query: str,\r\n        top_k: int = 5,\r\n        doc_type: Optional[DocumentType] = None\r\n    ) -> List[SearchResult]:\r\n        \"\"\"\r\n        Search the knowledge base.\r\n\r\n        Args:\r\n            query: Search query\r\n            top_k: Number of results to return\r\n            doc_type: Filter by document type\r\n\r\n        Returns:\r\n            List of search results\r\n        \"\"\"\r\n        # Generate query embedding\r\n        query_embedding = self.embedding_model.embed(query)\r\n\r\n        # Build filter\r\n        filter_metadata = None\r\n        if doc_type:\r\n            filter_metadata = {\"doc_type\": doc_type.value}\r\n\r\n        # Search vector store\r\n        results = self.vector_store.search(\r\n            query_embedding,\r\n            top_k=top_k,\r\n            filter_metadata=filter_metadata\r\n        )\r\n\r\n        # Build search results\r\n        search_results = []\r\n        for chunk, score in results:\r\n            doc = self.documents.get(chunk.document_id)\r\n            search_results.append(SearchResult(\r\n                chunk=chunk,\r\n                score=score,\r\n                document_title=doc.title if doc else \"Unknown\",\r\n                doc_type=doc.doc_type if doc else DocumentType.MANUAL\r\n            ))\r\n\r\n        return search_results\r\n\r\n    def query(\r\n        self,\r\n        question: str,\r\n        top_k: int = 5,\r\n        doc_type: Optional[DocumentType] = None\r\n    ) -> RAGResponse:\r\n        \"\"\"\r\n        Answer a question using RAG.\r\n\r\n        Args:\r\n            question: Question to answer\r\n            top_k: Number of context chunks to use\r\n            doc_type: Filter by document type\r\n\r\n        Returns:\r\n            RAG response with answer and sources\r\n        \"\"\"\r\n        # Search for relevant context\r\n        search_results = self.search(question, top_k=top_k, doc_type=doc_type)\r\n\r\n        if not search_results:\r\n            return RAGResponse(\r\n                query=question,\r\n                answer=\"I couldn't find relevant information to answer this question.\",\r\n                sources=[],\r\n                confidence=0.0,\r\n                tokens_used=0\r\n            )\r\n\r\n        # Build context from search results\r\n        context_parts = []\r\n        for i, result in enumerate(search_results):\r\n            context_parts.append(\r\n                f\"[Source {i+1}: {result.document_title}]\\n{result.chunk.content}\"\r\n            )\r\n\r\n        context = \"\\n\\n\".join(context_parts)\r\n\r\n        # Generate answer (simulated - in production, call LLM)\r\n        answer = self._generate_answer(question, context, search_results)\r\n\r\n        # Calculate confidence\r\n        avg_score = sum(r.score for r in search_results) \u002F len(search_results)\r\n\r\n        return RAGResponse(\r\n            query=question,\r\n            answer=answer,\r\n            sources=search_results,\r\n            confidence=avg_score,\r\n            tokens_used=len(context.split()) + len(question.split())\r\n        )\r\n\r\n    def _generate_answer(\r\n        self,\r\n        question: str,\r\n        context: str,\r\n        sources: List[SearchResult]\r\n    ) -> str:\r\n        \"\"\"\r\n        Generate answer from context.\r\n        In production, this would call an LLM API.\r\n        \"\"\"\r\n        # Simulated answer generation\r\n        answer_parts = [\r\n            f\"Based on the available construction documentation:\\n\"\r\n        ]\r\n\r\n        # Extract key information from sources\r\n        for source in sources[:3]:\r\n            # Take first sentence of each relevant chunk\r\n            first_sentence = source.chunk.content.split('.')[0] + '.'\r\n            answer_parts.append(f\"- {first_sentence}\")\r\n\r\n        answer_parts.append(\r\n            f\"\\n\\nThis information comes from {len(sources)} source documents \"\r\n            f\"including: {', '.join(set(s.document_title for s in sources[:3]))}.\"\r\n        )\r\n\r\n        return \"\\n\".join(answer_parts)\r\n\r\n    def get_document_summary(self, document_id: str) -> Optional[Dict]:\r\n        \"\"\"Get summary of a document\"\"\"\r\n        doc = self.documents.get(document_id)\r\n        if not doc:\r\n            return None\r\n\r\n        return {\r\n            \"id\": doc.id,\r\n            \"title\": doc.title,\r\n            \"type\": doc.doc_type.value,\r\n            \"chunks\": len(doc.chunks),\r\n            \"total_tokens\": sum(c.token_count for c in doc.chunks),\r\n            \"source\": doc.source,\r\n            \"created_at\": doc.created_at.isoformat()\r\n        }\r\n\r\n    def get_stats(self) -> Dict:\r\n        \"\"\"Get system statistics\"\"\"\r\n        return {\r\n            \"total_documents\": len(self.documents),\r\n            \"vector_store\": self.vector_store.get_stats(),\r\n            \"embedding_model\": self.embedding_model.model_name,\r\n            \"chunking_strategy\": self.chunker.strategy.value\r\n        }\r\n\r\n    def export_knowledge_base(self) -> Dict:\r\n        \"\"\"Export knowledge base for backup\u002Ftransfer\"\"\"\r\n        return {\r\n            \"documents\": [\r\n                {\r\n                    \"id\": doc.id,\r\n                    \"title\": doc.title,\r\n                    \"type\": doc.doc_type.value,\r\n                    \"content\": doc.content,\r\n                    \"source\": doc.source,\r\n                    \"metadata\": doc.metadata\r\n                }\r\n                for doc in self.documents.values()\r\n            ],\r\n            \"stats\": self.get_stats(),\r\n            \"exported_at\": datetime.now().isoformat()\r\n        }\r\n```\r\n\r\n## Common Use Cases\r\n\r\n### Build Construction Knowledge Base\r\n\r\n```python\r\nrag = ConstructionRAG(\r\n    chunking_strategy=ChunkingStrategy.SECTION,\r\n    chunk_size=500\r\n)\r\n\r\n# Add specifications\r\nspec_doc = Document(\r\n    id=\"spec-03300\",\r\n    title=\"Cast-in-Place Concrete Specification\",\r\n    doc_type=DocumentType.SPECIFICATION,\r\n    content=\"\"\"\r\n    SECTION 03 30 00 - CAST-IN-PLACE CONCRETE\r\n\r\n    PART 1 - GENERAL\r\n    1.1 SUMMARY\r\n    A. Section includes cast-in-place concrete for foundations,\r\n       slabs, walls, and other structural elements.\r\n\r\n    1.2 RELATED SECTIONS\r\n    A. Section 03 10 00 - Concrete Forming\r\n    B. Section 03 20 00 - Concrete Reinforcing\r\n\r\n    PART 2 - PRODUCTS\r\n    2.1 CONCRETE MATERIALS\r\n    A. Portland Cement: ASTM C150, Type I or II\r\n    B. Aggregates: ASTM C33, graded\r\n    C. Water: Clean, potable\r\n    \"\"\",\r\n    source=\"project_specs.pdf\",\r\n    metadata={\"division\": \"03\", \"project\": \"Building A\"}\r\n)\r\n\r\nchunks_created = rag.add_document(spec_doc)\r\nprint(f\"Created {chunks_created} chunks\")\r\n```\r\n\r\n### Search Knowledge Base\r\n\r\n```python\r\n# Search for concrete requirements\r\nresults = rag.search(\r\n    query=\"concrete strength requirements\",\r\n    top_k=5,\r\n    doc_type=DocumentType.SPECIFICATION\r\n)\r\n\r\nfor result in results:\r\n    print(f\"Score: {result.score:.3f}\")\r\n    print(f\"Document: {result.document_title}\")\r\n    print(f\"Content: {result.chunk.content[:200]}...\")\r\n    print()\r\n```\r\n\r\n### Answer Questions with RAG\r\n\r\n```python\r\nresponse = rag.query(\r\n    question=\"What type of cement should be used for foundations?\",\r\n    top_k=3\r\n)\r\n\r\nprint(f\"Answer: {response.answer}\")\r\nprint(f\"Confidence: {response.confidence:.0%}\")\r\nprint(f\"Sources: {len(response.sources)}\")\r\n```\r\n\r\n## Quick Reference\r\n\r\n| Component | Purpose |\r\n|-----------|---------|\r\n| `ConstructionRAG` | Main RAG system |\r\n| `TextChunker` | Document chunking |\r\n| `VectorStore` | Embedding storage |\r\n| `EmbeddingModel` | Text embeddings |\r\n| `DocumentChunk` | Chunk with metadata |\r\n| `RAGResponse` | Query response |\r\n\r\n## Resources\r\n\r\n- **Book**: \"Data-Driven Construction\" by Artem Boiko, Chapter 2.3\r\n- **Website**: https:\u002F\u002Fdatadrivenconstruction.io\r\n\r\n## Next Steps\r\n\r\n- Use [llm-data-automation](..\u002Fllm-data-automation\u002FSKILL.md) for automation\r\n- Use [vector-search](..\u002F..\u002FChapter-4.4\u002Fvector-search\u002FSKILL.md) for advanced search\r\n- Use [document-classification-nlp](..\u002F..\u002F..\u002FDDC_Innovative\u002Fdocument-classification-nlp\u002FSKILL.md) for classification\r\n",{"slug":5,"description":7,"display_name":31},"Rag Construction","main","e7e336ac628c3e3bd771aff1aaa469c93778f94a","skills\u002Fdatadrivenconstruction\u002Frag-construction",0,"https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills","https:\u002F\u002Fgithub.com\u002Fkbarbel640-del","2026-08-23 22:39:37",{"source":8,"skillName":5,"commands":40,"prompt":50,"zipAvailable":51},[41,44,47],{"tool":42,"command":43},"npx","npx skills add kbarbel640-del\u002Fskills --skill rag-construction",{"tool":45,"command":46},"bunx","bunx skills add kbarbel640-del\u002Fskills --skill rag-construction",{"tool":48,"command":49},"pnpm","pnpm dlx skills add kbarbel640-del\u002Fskills --skill rag-construction","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fdatadrivenconstruction\u002Frag-construction\u002FSKILL.md",true,[53],{"path":54,"resourceType":55,"resourceTypeDesc":56,"sizeBytes":57,"sourceHtmlUrl":58},"_meta.json","REFERENCE","参考文档",300,"https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fdatadrivenconstruction\u002Frag-construction\u002F_meta.json",[60,86,109,127,132,152],{"skillNo":61,"name":62,"nameZh":6,"description":63,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":64,"categories":65,"keywords":66,"publishedAt":26},"01M6G8J55967D6281ACMKAKTEQ","crowd-prompting","A marketplace where AI agents improve prompts, system instructions, tool descriptions, and other text-based content with domain expertise from real-world operations — and earn tokens for valuable contributions.","https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fzzadrian\u002Fcrowd-prompting\u002FSKILL.md",[],[67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85],"crowd prompting","prompting","api","with","tokens","domain","world","prompts","operations","instructions","text","tool","system","improve","productivity","marketplace","https","content","ai agents",{"skillNo":87,"name":88,"nameZh":6,"description":89,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":90,"categories":91,"keywords":92,"publishedAt":26},"01M6G8J0PKPAYVET6BWE8W4C26","dilemm-ai","Compete in DilemmAI, the prisoner's dilemma AI arena at dilemm.ai. Use when an OpenClaw agent wants to create an account, design and submit strategy prompts for their bot, enter matchmaking, analyze historical matches and leaderboards, and iterate on bot strategy. Requires headless browser automation (no API available yet).","https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fzyori\u002Fdilemm-ai\u002FSKILL.md",[],[93,69,94,95,96,97,20,98,99,100,101,102,103,104,105,106,107,74,108],"dilemm ai","arena","analyze","browser","openclaw agent","automation","browser automation","bot","openclaw","design","strategy","headless","compete","submit","matchmaking","use",{"skillNo":110,"name":111,"nameZh":6,"description":112,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":113,"categories":114,"keywords":115,"publishedAt":26},"01M6G8HWAF3K9SW7NP3Z83CPJ6","arxiv-paper-reviews","Interact with arXiv Crawler API to fetch papers, read reviews, and submit comments. Use when working with arXiv papers, fetching paper lists by date\u002Fcategory\u002Finterest, viewing paper details with comments, or submitting paper reviews via API at http:\u002F\u002F150.158.152.82:8000.","https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fzxrys\u002Fweak-accept\u002FSKILL.md",[],[116,117,118,119,120,121,122,70,123,106,108,124,69,125,126],"arxiv paper reviews","reviews","arxiv","paper","crawler","papers","comments","fetch","read","http","via",{"skillNo":128,"name":111,"nameZh":6,"description":112,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":129,"categories":130,"keywords":131,"publishedAt":26},"01M6G8HQJ7N7WMY6YV7D7SSJ16","https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fzxrys\u002Farxiv-paper-reviews\u002FSKILL.md",[],[119,118,117,116,126,121,122,70,120,106,108,123,124,69,125],{"skillNo":133,"name":134,"nameZh":6,"description":135,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":136,"categories":137,"keywords":138,"publishedAt":26},"01M6G8HM95Y64JNVFC2HN4E2BG","git-summary","Get a quick summary of the current Git repository including status, recent commits, branches, and contributors.","https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fzweack\u002Fgit-summary\u002FSKILL.md",[],[139,140,141,142,143,144,145,146,147,148,149,150,151],"git","summary","git summary","commits","repository","win32","status","linux","contributors","true","quick","get","branches",{"skillNo":153,"name":154,"nameZh":6,"description":155,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":156,"categories":157,"keywords":158,"publishedAt":26},"01M6G8HGEGF05CNEJCGVYFSC4R","agent-constitution","Interact with AgentConstitution governance contracts on Base Sepolia. Check compliance, read rules, log actions, query governance state.","https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fztsalexey\u002Fagent-constitution\u002FSKILL.md",[],[159,160,161,162,70,163,164,32,165,124,166,167,168,169,170,83,171,172,173],"agent constitution","constitution","contracts","tree","query","base","log","check","Rules","projects","compliance","actions","state","governance","github"]