langchain-llamaindex
Skill13 starsChanged 8 months agoMITView on GitHub
LangChain and LlamaIndex patterns for RAG pipelines, agent workflows, retrieval strategies, and cost-optimized LLM chains. Covers advanced RAG, multi-hop retrieval, reranking, and structured output.
In this repository60 other files it gives its agents.
- AGENTS.mdAGENTS.md
- examples/CLAUDE.mdCLAUDE.md
- agentic-engineeringSkill
- api-designSkill
- api-integrationsSkill
- architecture-decision-recordsSkill
- autonomous-agent-harnessSkill
- autonomous-loopsSkill
- aws-deploymentSkill
- aws-devopsSkill
- backend-patternsSkill
- backlog-managementSkill
- ci-pipelineSkill
- claude-apiSkill
- codebase-onboardingSkill
- codebase-reportSkill
- code-reviewSkill
- coding-standardsSkill
- context-pruneSkill
- continuous-agent-loopSkill
- database-migrationsSkill
- data-pipelines-aiSkill
- data-pipelinesSkill
- deep-researchSkill
- deployment-patternsSkill
- dmux-workflowsSkill
- docker-patternsSkill
- documentation-lookupSkill
- document-processingSkill
- e2e-testingSkill
- eval-harnessSkill
- exa-searchSkill
- frontend-designSkill
- frontend-patternsSkill
- github-opsSkill
- git-workflowSkill
- hexagonal-architectureSkill
- iterative-retrievalSkill
- mcp-server-patternsSkill
- mlops-ragSkill
- mlops-workflowSkill
- multi-agent-git-workflowSkill
- observability-telemetrySkill
- openai-apiSkill
- postgres-patternsSkill
- prompt-optimizerSkill
- python-patternsSkill
- python-testingSkill
- pytorch-patternsSkill
- search-firstSkill
- security-reviewSkill
- security-scanSkill
- skill-authoringSkill
- tdd-workflowSkill
- technical-debt-reportSkill
- token-budget-advisorSkill
- typescript-patternsSkill
- verification-loopSkill
- workflow-statusSkill
- wxt-chrome-extensionSkill
The file
We split this skill into the rules it gives an agent
8 rules. About 0 are common, 6 are distinctive, and 2 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈6
Distinctive · estimate
This author's own choices. Worth a look.
2
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 8
Use this skill when building RAG pipelines, LangChain agent workflows, or LlamaIndex retrieval systems.
- Distinctive: line 206
Sending entire document as context: Use retrieval with top-k, not dump-everything
- Distinctive: line 207
No chunking strategy: Default character splitting breaks semantic units.
- Distinctive: line 209
Hardcoding temperature: Use temperature=0 for factual RAG, 0.3-0.7 for creative generation
- Distinctive: line 211
Storing embeddings without metadata: Always store document source, chunk index, and metadata for filtering
- Very specific: line 217
Use text-embedding-3-small for most tasks.
- Distinctive: line 218
Always add a reranking step (cross-encoder or Cohere rerank) between retrieval and generation
- Very specific: line 221
Use gpt-4o-mini for chain orchestration and extraction.
≈ “Common” is an estimate: at least 1 in 5 of the 213,895 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
LangChain & LlamaIndex
Use this skill when building RAG pipelines, LangChain agent workflows, or LlamaIndex retrieval systems. Covers document processing, vector store integration, advanced retrieval strategies, and cost optimization.
When to Use
- Building RAG (Retrieval-Augmented Generation) pipelines
- Creating LangChain chains or agents with tool calling
- Setting up LlamaIndex document indexes and query engines
- Implementing advanced retrieval: hybrid search, reranking, multi-hop
- Optimizing LLM token costs and response patterns
Core Concepts
LangChain Core Building Blocks
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnablePassthrough
from langchain_openai import ChatOpenAI, OpenAIEmbeddings
from langchain_core.output_parsers import StrOutputParser
# Basic chain
prompt = ChatPromptTemplate.from_messages([
("system", "You are a helpful assistant. Answer based on context:\n{context}"),
("human", "{question}")
])
model = ChatOpenAI(model="gpt-4o-mini", temperature=0)
chain = (
{"context": retriever, "question": RunnablePassthrough()}
| prompt
| model
| StrOutputParser()
)
result = chain.invoke("What is the RAG evaluation strategy?")LangChain Agent with Tool Calling
from langchain.agents import create_tool_calling_agent, AgentExecutor
from langchain_core.tools import tool
@tool
def search_database(query: str) -> str:
"""Search the knowledge base for relevant information."""
return retriever.invoke(query)
tools = [search_database]
agent = create_tool_calling_agent(model, tools, prompt)
executor = AgentExecutor(agent=agent, tools=tools, verbose=True)LlamaIndex RAG Pipeline
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader
from llama_index.llms.openai import OpenAI
from llama_index.embeddings.openai import OpenAIEmbedding
from llama_index.core.node_parser import SentenceSplitter
# Load and parse documents
documents = SimpleDirectoryReader("data/").load_data()
# Chunking strategy
node_parser = SentenceSplitter(chunk_size=512, chunk_overlap=50)
nodes = node_parser.get_nodes_from_documents(documents)
# Build index with custom settings
index = VectorStoreIndex(
nodes,
llm=OpenAI(model="gpt-4o-mini"),
embed_model=OpenAIEmbedding(model="text-embedding-3-small"),
)
# Query engine with retrieval configuration
query_engine = index.as_query_engine(
similarity_top_k=5,
response_mode="compact", # compact, refine, tree_summarize
)Text Splitting Strategies
| Strategy | Use Case | Chunk Size | Overlap |
| Character split | Simple text | 500-1000 chars | 50-100 chars |
| Token split | LLM-aligned boundaries | 256-512 tokens | 25-50 tokens |
| Semantic split | Meaning-preserving | Variable | N/A |
| Recursive character | Code, markdown | 512-1024 | 50-100 |
| Structure-aware | HTML, JSON, code blocks | Per-block | 0-25 |
Vector Store Comparison
| Store | Best For | Filtering | Cost | Ops Overhead |
| Pinecone | Managed, scale | Metadata + namespace | $$/M queries | Low |
| Weaviate | GraphQL, hybrid | Rich filters + generative | $$ | Medium |
| Qdrant | Performance, quantization | Payload filtering | $ | Medium |
| pgvector | PostgreSQL-native | Full SQL + vector | $ (infra) | Low (if PG exists) |
| FAISS | Local, offline | Basic | Free (local) | Low |
| Chroma | Rapid prototyping | Metadata | Free (local) | Low |
Advanced RAG Patterns
Hybrid Search (Dense + Sparse)
from langchain.retrievers import EnsembleRetriever
from langchain_community.retrievers import BM25Retriever
dense_retriever = vector_store.as_retriever(search_kwargs={"k": 5})
bm25_retriever = BM25Retriever.from_texts(texts)
bm25_retriever.k = 5
ensemble = EnsembleRetriever(
retrievers=[dense_retriever, bm25_retriever],
weights=[0.7, 0.3], # Weight dense higher for semantic, sparse for keyword
)Multi-Query Retrieval
from langchain.retrievers.multi_query import MultiQueryRetriever
retriever = MultiQueryRetriever.from_llm(
retriever=vector_store.as_retriever(),
llm=ChatOpenAI(model="gpt-4o-mini", temperature=0),
)
# Generates multiple query variations, deduplicates resultsContextual Compression
from langchain.retrievers import ContextualCompressionRetriever
from langchain.retrievers.document_compressors import LLMChainExtractor
compressor = LLMChainExtractor.from_llm(model)
compression_retriever = ContextualCompressionRetriever(
base_compressor=compressor,
base_retriever=vector_store.as_retriever(),
)
# Retrieves broadly, then uses LLM to extract only relevant portionsCross-Encoder Reranking
from langchain.retrievers.document_compressors import CrossEncoderReranker
from langchain_community.cross_encoders import HuggingFaceCrossEncoder
model = HuggingFaceCrossEncoder(model_name="cross-encoder/ms-marco-MiniLM-L-6-v2")
reranker = CrossEncoderReranker(model=model, top_n=3)
compression_retriever = ContextualCompressionRetriever(
base_compressor=reranker,
base_retriever=ensemble_retriever,
)Query Rewriting + Multi-Hop
from langchain_core.prompts import PromptTemplate
rewrite_prompt = PromptTemplate.from_template(
"Given this question and retrieved context, generate a follow-up question "
"that would help answer the original question more completely.\n"
"Question: {question}\nContext: {context}\nFollow-up:"
)
# Chain: Query → Retrieve → Rewrite → Retrieve again → GenerateRetrieval-Time Prompt Guards
def sanitize_retrieved_context(context: str) -> str:
"""Remove potential injection vectors from retrieved content."""
# Strip system prompt patterns
context = re.sub(r'(?i)ignore previous instructions', '', context)
context = re.sub(r'(?i)you are now', '', context)
# Truncate to prevent context window overflow
return context[:4000]Memory Patterns
from langchain.memory import ConversationBufferMemory, ConversationSummaryMemory
# Buffer memory (full conversation history)
memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
# Summary memory (condenses conversation for long sessions)
summary_memory = ConversationSummaryMemory(
llm=ChatOpenAI(model="gpt-4o-mini"),
memory_key="chat_history",
return_messages=True,
)
# Vector store-backed memory (for very long conversations)
from langchain.memory import VectorStoreRetrieverMemory
vector_memory = VectorStoreRetrieverMemory(
retriever=vector_store.as_retriever(search_kwargs={"k": 3}),
)Anti-Patterns
- Sending entire document as context: Use retrieval with top-k, not dump-everything
- No chunking strategy: Default character splitting breaks semantic units; use structure-aware splitting
- Skipping reranking: Top-k by embedding similarity alone misses keyword matches; add cross-encoder reranking
- Hardcoding temperature: Use temperature=0 for factual RAG, 0.3-0.7 for creative generation
- No token budgeting: Track token usage per chain; implement early exit for simple queries
- Storing embeddings without metadata: Always store document source, chunk index, and metadata for filtering
- Ignoring rate limits: Implement exponential backoff for API calls; use batch processing where possible
Best Practices
- Chunk at semantic boundaries (paragraph breaks, code function boundaries) with 10% overlap
- Use
text-embedding-3-smallfor most tasks; upgrade totext-embedding-3-largeonly if retrieval quality demands it - Always add a reranking step (cross-encoder or Cohere rerank) between retrieval and generation
- Implement response validation: check that answers are grounded in retrieved context (faithfulness scoring)
- Cache frequent query results with semantic similarity matching to reduce API costs
- Use
gpt-4o-minifor chain orchestration and extraction; reservegpt-4ofor final generation - Log all chain executions with LangSmith for debugging and cost tracking
- Implement fallback: if retrieval returns low-confidence results, acknowledge uncertainty rather than hallucinate
Related Skills
mlops-rag— RAG evaluation, model versioning, observabilitydata-pipelines-ai— Document ingestion pipelines, chunking strategiesopenai-api— Model selection, cost optimization, API patternseval-harness— RAG evaluation with RAGAS, DeepEval, LangSmith
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

