langchain-4-rag-retrieval-augmented-generation
Sub-skill of langchain: 4. RAG (Retrieval Augmented Generation).
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
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/4-rag-retrieval-augmented-generation/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How langchain-4-rag-retrieval-augmented-generation Compares
| Feature / Agent | langchain-4-rag-retrieval-augmented-generation | Standard Approach |
|---|---|---|
| Platform Support | Not specified | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | Unknown | N/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
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
Create self-contained execution prompts that define multi-role workflows for Codex sessions without external dependencies
gtm-workflow-gif-generation
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
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
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
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
Generate parametric CAD geometry and finite element meshes using FreeCAD and GMSH
lead-generation
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
Sub-skill of json-config-loader: 3. JSON Report Generation.
wave-theory-4-time-series-generation
Sub-skill of wave-theory: 4. Time Series Generation (+1).
orcawave-mesh-generation-standard-mesh-generation
Sub-skill of orcawave-mesh-generation: Standard Mesh Generation (+1).
orcawave-mesh-generation-panel-quality-thresholds
Sub-skill of orcawave-mesh-generation: Panel Quality Thresholds (+1).