langchain-4-rag-retrieval-augmented-generation

Sub-skill of langchain: 4. RAG (Retrieval Augmented Generation).

5 stars

Best use case

langchain-4-rag-retrieval-augmented-generation is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

Sub-skill of langchain: 4. RAG (Retrieval Augmented Generation).

Teams using langchain-4-rag-retrieval-augmented-generation should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/4-rag-retrieval-augmented-generation/SKILL.md --create-dirs "https://raw.githubusercontent.com/vamseeachanta/workspace-hub/main/.agents/skills/_archive/ai/prompting/langchain/4-rag-retrieval-augmented-generation/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/4-rag-retrieval-augmented-generation/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How langchain-4-rag-retrieval-augmented-generation Compares

Feature / Agentlangchain-4-rag-retrieval-augmented-generationStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

Sub-skill of langchain: 4. RAG (Retrieval Augmented Generation).

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

SKILL.md Source

# 4. RAG (Retrieval Augmented Generation)

## 4. RAG (Retrieval Augmented Generation)


**Complete RAG Pipeline:**
```python
from langchain_openai import OpenAIEmbeddings, ChatOpenAI
from langchain_community.vectorstores import Chroma
from langchain_community.document_loaders import DirectoryLoader, PyPDFLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnablePassthrough
from langchain_core.output_parsers import StrOutputParser
from pathlib import Path
from typing import List

def create_rag_pipeline(
    documents_dir: str,
    collection_name: str = "engineering_docs",
    chunk_size: int = 1000,
    chunk_overlap: int = 200
):
    """
    Create a complete RAG pipeline.

    Args:
        documents_dir: Directory containing documents
        collection_name: Name for vector store collection
        chunk_size: Size of text chunks
        chunk_overlap: Overlap between chunks

    Returns:
        RAG chain for question answering
    """
    # 1. Load documents
    loader = DirectoryLoader(
        documents_dir,
        glob="**/*.pdf",
        loader_cls=PyPDFLoader,
        show_progress=True
    )
    documents = loader.load()

    print(f"Loaded {len(documents)} document pages")

    # 2. Split documents into chunks
    text_splitter = RecursiveCharacterTextSplitter(
        chunk_size=chunk_size,
        chunk_overlap=chunk_overlap,
        length_function=len,
        separators=["\n\n", "\n", " ", ""]
    )
    chunks = text_splitter.split_documents(documents)

    print(f"Created {len(chunks)} chunks")

    # 3. Create embeddings and vector store
    embeddings = OpenAIEmbeddings(model="text-embedding-3-small")

    vectorstore = Chroma.from_documents(
        documents=chunks,
        embedding=embeddings,
        collection_name=collection_name,
        persist_directory="./chroma_db"
    )

    # 4. Create retriever
    retriever = vectorstore.as_retriever(
        search_type="similarity",
        search_kwargs={"k": 5}
    )

    # 5. Create RAG prompt
    rag_prompt = ChatPromptTemplate.from_template("""
    You are an expert assistant answering questions based on the provided context.
    Use only the information from the context to answer.
    If the context doesn't contain the answer, say "I don't have enough information."

    Context:
    {context}

    Question: {question}

    Answer:
    """)

    # 6. Create LLM
    llm = ChatOpenAI(model="gpt-4", temperature=0)

    # 7. Build RAG chain
    def format_docs(docs):
        return "\n\n---\n\n".join(
            f"Source: {doc.metadata.get('source', 'Unknown')}\n{doc.page_content}"
            for doc in docs
        )

    rag_chain = (
        {"context": retriever | format_docs, "question": RunnablePassthrough()}
        | rag_prompt
        | llm
        | StrOutputParser()
    )

    return rag_chain, retriever

# Usage
rag_chain, retriever = create_rag_pipeline(
    documents_dir="./engineering_docs",
    collection_name="offshore_standards"
)

# Query
answer = rag_chain.invoke(
    "What are the safety factor requirements for mooring lines?"
)
print(answer)

# Get source documents
docs = retriever.get_relevant_documents(
    "mooring line safety factors"
)
for doc in docs:
    print(f"Source: {doc.metadata['source']}")
    print(f"Content: {doc.page_content[:200]}...")
    print()
```

**RAG with Reranking:**
```python
from langchain_openai import OpenAIEmbeddings, ChatOpenAI
from langchain_community.vectorstores import Chroma
from langchain.retrievers import ContextualCompressionRetriever
from langchain.retrievers.document_compressors import CrossEncoderReranker
from langchain_community.cross_encoders import HuggingFaceCrossEncoder
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnablePassthrough
from langchain_core.output_parsers import StrOutputParser

def create_reranked_rag_pipeline(
    vectorstore: Chroma,
    top_k_initial: int = 20,
    top_k_final: int = 5
):
    """
    Create RAG pipeline with reranking for better relevance.

    Args:
        vectorstore: Existing vector store
        top_k_initial: Number of docs to retrieve initially
        top_k_final: Number of docs after reranking
    """
    # Base retriever - get more docs initially
    base_retriever = vectorstore.as_retriever(
        search_kwargs={"k": top_k_initial}
    )

    # Reranker using cross-encoder
    reranker_model = HuggingFaceCrossEncoder(
        model_name="cross-encoder/ms-marco-MiniLM-L-6-v2"
    )
    compressor = CrossEncoderReranker(
        model=reranker_model,
        top_n=top_k_final
    )

    # Compression retriever with reranking
    retriever = ContextualCompressionRetriever(
        base_compressor=compressor,
        base_retriever=base_retriever
    )

    # Build chain
    llm = ChatOpenAI(model="gpt-4", temperature=0)

    prompt = ChatPromptTemplate.from_template("""
    Answer the question based on the context below.
    Cite your sources by mentioning which document the information came from.

    Context:
    {context}

    Question: {question}

    Answer with citations:
    """)

    def format_docs_with_citations(docs):
        formatted = []

*Content truncated — see parent skill for full reference.*

Related Skills

label-driven-prompt-generation-architecture

5
from vamseeachanta/workspace-hub

Pattern for building automation scripts that classify GitHub issues into prompt templates using label-based routing and extract contextual data for batch processing

agent-team-prompt-generation

5
from vamseeachanta/workspace-hub

Create self-contained execution prompts that define multi-role workflows for Codex sessions without external dependencies

gtm-workflow-gif-generation

5
from vamseeachanta/workspace-hub

Generate workflow-style GTM GIFs from validated HTML demo reports using synthetic scene slides plus Playwright/Pillow scroll capture, with Python 3.12 fallback and GIF size optimization.

gtm-demo-workflow-gif-generation

5
from vamseeachanta/workspace-hub

Generate GTM demo GIF assets from validated HTML reports, including both report-scroll GIFs and one higher-fidelity workflow-style GIF, while avoiding Playwright/Python environment traps.

stable-diffusion-image-generation

5
from vamseeachanta/workspace-hub

State-of-the-art text-to-image generation with Stable Diffusion models via HuggingFace Diffusers. Use when generating images from text prompts, performing image-to-image translation, inpainting, or building custom diffusion pipelines.

orcawave-mesh-generation

5
from vamseeachanta/workspace-hub

Panel mesh generation for OrcaWave diffraction analysis. Use when converting CAD/STL to panel mesh, validating mesh quality, running convergence studies, or generating GDF files for hydrodynamic computations.

cad-mesh-generation

5
from vamseeachanta/workspace-hub

Generate parametric CAD geometry and finite element meshes using FreeCAD and GMSH

lead-generation

5
from vamseeachanta/workspace-hub

B2B demand generation with CAC optimization, multi-channel strategies, and lead qualification frameworks. Use for lead acquisition, nurture campaigns, and conversion optimization. Based on alirezarezvani/Codex-skills.

json-config-loader-3-json-report-generation

5
from vamseeachanta/workspace-hub

Sub-skill of json-config-loader: 3. JSON Report Generation.

wave-theory-4-time-series-generation

5
from vamseeachanta/workspace-hub

Sub-skill of wave-theory: 4. Time Series Generation (+1).

orcawave-mesh-generation-standard-mesh-generation

5
from vamseeachanta/workspace-hub

Sub-skill of orcawave-mesh-generation: Standard Mesh Generation (+1).

orcawave-mesh-generation-panel-quality-thresholds

5
from vamseeachanta/workspace-hub

Sub-skill of orcawave-mesh-generation: Panel Quality Thresholds (+1).