langchain
Build LLM-powered applications with LangChain. Use when a user asks to create AI chains, build RAG pipelines, implement agents with tools, set up document loaders, create vector stores, build conversational AI, implement prompt templates, chain LLM calls, add memory to chatbots, or orchestrate language model workflows. Covers LangChain v0.3+ with LCEL (LangChain Expression Language), structured output, tool calling, retrieval, and production deployment patterns.
What this skill does
# LangChain
## Overview
Build production-grade LLM applications using LangChain's composable framework. This skill covers chains, agents, retrieval-augmented generation (RAG), tool integration, memory, and deployment — using modern LCEL patterns (not legacy `LLMChain`).
## Instructions
### Step 1: Project Setup
Determine the user's runtime (Python or TypeScript) and initialize the project:
**Python:**
```bash
pip install langchain langchain-core langchain-openai langchain-community
# For RAG:
pip install langchain-chroma sentence-transformers
# For document loading:
pip install unstructured pypdf docx2txt
```
**TypeScript:**
```bash
npm install langchain @langchain/core @langchain/openai @langchain/community
# For RAG:
npm install @langchain/chroma
```
Verify the LLM provider API key is set:
```bash
echo $OPENAI_API_KEY # or ANTHROPIC_API_KEY, etc.
```
### Step 2: Understand LCEL (LangChain Expression Language)
All modern LangChain code uses LCEL — the pipe (`|`) operator for composing runnables:
```python
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
from langchain_core.output_parsers import StrOutputParser
prompt = ChatPromptTemplate.from_messages([
("system", "You are a helpful assistant specialized in {domain}."),
("human", "{question}")
])
chain = prompt | ChatOpenAI(model="gpt-4o") | StrOutputParser()
result = chain.invoke({"domain": "Python", "question": "Explain decorators"})
```
Key LCEL concepts:
- **Runnables**: Any component that implements `.invoke()`, `.stream()`, `.batch()`
- **Pipe operator**: `a | b` means output of `a` feeds into `b`
- **RunnablePassthrough**: Pass input through unchanged
- **RunnableLambda**: Wrap any function as a runnable
- **RunnableParallel**: Run multiple chains simultaneously
### Step 3: Implement Core Patterns
#### Simple Chain
```python
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
prompt = ChatPromptTemplate.from_template("Summarize this text in {language}: {text}")
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
chain = prompt | llm
result = chain.invoke({"language": "Spanish", "text": "..."})
```
#### Structured Output
```python
from pydantic import BaseModel, Field
class ExtractedInfo(BaseModel):
name: str = Field(description="Person's full name")
role: str = Field(description="Job title or role")
sentiment: str = Field(description="Overall sentiment: positive, negative, neutral")
llm_structured = llm.with_structured_output(ExtractedInfo)
chain = prompt | llm_structured
# Returns ExtractedInfo object, not raw text
```
#### Retrieval-Augmented Generation (RAG)
```python
from langchain_community.document_loaders import PyPDFLoader
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_chroma import Chroma
from langchain_openai import OpenAIEmbeddings
from langchain_core.runnables import RunnablePassthrough
# Load and split documents
loader = PyPDFLoader("docs/manual.pdf")
docs = loader.load()
splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
splits = splitter.split_documents(docs)
# Create vector store
vectorstore = Chroma.from_documents(splits, OpenAIEmbeddings())
retriever = vectorstore.as_retriever(search_kwargs={"k": 4})
# RAG chain
rag_prompt = ChatPromptTemplate.from_template(
"Answer based on context:\n\n{context}\n\nQuestion: {question}"
)
def format_docs(docs):
return "\n\n".join(d.page_content for d in docs)
rag_chain = (
{"context": retriever | format_docs, "question": RunnablePassthrough()}
| rag_prompt
| llm
| StrOutputParser()
)
answer = rag_chain.invoke("What is the return policy?")
```
#### Tool-Calling Agent
```python
from langchain_core.tools import tool
from langchain_openai import ChatOpenAI
from langgraph.prebuilt import create_react_agent
@tool
def search_database(query: str) -> str:
"""Search the product database for matching items."""
# Implementation here
return f"Found 3 results for '{query}'"
@tool
def calculate_discount(price: float, percent: float) -> float:
"""Calculate discounted price."""
return price * (1 - percent / 100)
tools = [search_database, calculate_discount]
llm = ChatOpenAI(model="gpt-4o")
# Modern approach uses LangGraph for agents
agent = create_react_agent(llm, tools)
result = agent.invoke({"messages": [("human", "Find laptops under $1000 and apply 15% discount")]})
```
#### Conversational Memory
```python
from langchain_core.chat_history import InMemoryChatMessageHistory
from langchain_core.runnables.history import RunnableWithMessageHistory
store = {}
def get_session_history(session_id: str):
if session_id not in store:
store[session_id] = InMemoryChatMessageHistory()
return store[session_id]
prompt = ChatPromptTemplate.from_messages([
("system", "You are a helpful assistant."),
("placeholder", "{history}"),
("human", "{input}")
])
chain = prompt | llm | StrOutputParser()
chain_with_history = RunnableWithMessageHistory(
chain,
get_session_history,
input_messages_key="input",
history_messages_key="history",
)
# Each call remembers previous messages
response = chain_with_history.invoke(
{"input": "My name is Alice"},
config={"configurable": {"session_id": "user-123"}}
)
```
### Step 4: Document Loaders and Text Splitters
Common loaders:
```python
from langchain_community.document_loaders import (
PyPDFLoader, # PDF files
TextLoader, # Plain text
CSVLoader, # CSV files
DirectoryLoader, # Entire directories
WebBaseLoader, # Web pages
UnstructuredHTMLLoader,# HTML files
Docx2txtLoader, # Word documents
JSONLoader, # JSON files
)
```
Splitting strategies:
```python
from langchain_text_splitters import (
RecursiveCharacterTextSplitter, # General purpose (recommended)
TokenTextSplitter, # Token-aware splitting
MarkdownHeaderTextSplitter, # Split by markdown headers
HTMLHeaderTextSplitter, # Split by HTML headers
)
# Best default:
splitter = RecursiveCharacterTextSplitter(
chunk_size=1000,
chunk_overlap=200,
separators=["\n\n", "\n", ". ", " ", ""]
)
```
### Step 5: Vector Stores
```python
# Chroma (local dev), FAISS (fast in-memory), Pinecone (managed production)
from langchain_chroma import Chroma
vectorstore = Chroma.from_documents(docs, embeddings, persist_directory="./chroma_db")
# Use MMR retrieval for diversity over pure similarity
retriever = vectorstore.as_retriever(search_type="mmr", search_kwargs={"k": 5, "fetch_k": 20})
```
### Step 6: Production Patterns
```python
# Streaming
async for chunk in chain.astream({"question": "Explain quantum computing"}):
print(chunk, end="", flush=True)
# Batch processing with concurrency control
results = chain.batch([
{"question": "What is Python?"},
{"question": "What is Rust?"},
], config={"max_concurrency": 3})
# Fallbacks: use a different provider if primary fails
from langchain_anthropic import ChatAnthropic
llm_with_fallback = ChatOpenAI(model="gpt-4o").with_fallback([ChatAnthropic(model="claude-sonnet-4-20250514")])
# Caching: avoid duplicate LLM calls
from langchain_core.globals import set_llm_cache
from langchain_community.cache import SQLiteCache
set_llm_cache(SQLiteCache(database_path=".langchain_cache.db"))
```
## Examples
### Example 1: Build a RAG pipeline over internal documentation
**User prompt:** "I have 40 PDF files of internal engineering docs in ./docs/. Build a RAG pipeline so I can ask questions about our architecture and get accurate answers with source citations."
The agent will create a Python script that loads all PDFs from `./docs/` using `DirectoryLoader` with `PyPDFLoader`, splits them with `RecursiveCharacterTextSplitter` (chunk_size=1000, chunk_overlap=200), creates a Chroma vector store persisted to Related in AI Agents
skill-development
IncludedComprehensive meta-skill for creating, managing, validating, auditing, and distributing Claude Code skills and slash commands (unified in v2.1.3+). Provides skill templates, creation workflows, validation patterns, audit checklists, naming conventions, YAML frontmatter guidance, progressive disclosure examples, and best practices lookup. Use when creating new skills, validating existing skills, auditing skill quality, understanding skill architecture, needing skill templates, learning about YAML frontmatter requirements, progressive disclosure patterns, tool restrictions (allowed-tools), skill composition, skill naming conventions, troubleshooting skill activation issues, creating custom slash commands, configuring command frontmatter, using command arguments ($ARGUMENTS, $1, $2), bash execution in commands, file references in commands, command namespacing, plugin commands, MCP slash commands, Skill tool configuration, or deciding between skills vs slash commands. Delegates to docs-management skill for official documentation.
reprompter
IncludedTransform messy prompts into well-structured, effective prompts — single or multi-agent. Use when: "reprompt", "reprompt this", "clean up this prompt", "structure my prompt", rough text needing XML tags and best practices, "reprompter teams", "repromptception", "run with quality", "smart run", "smart agents", multi-agent tasks, audits, parallel work, anything going to agent teams. Don't use when: simple Q&A, pure chat, immediate execution-only tasks. See "Don't Use When" section for details. Outputs: Structured XML/Markdown prompt, quality score (before/after), optional team brief + per-agent sub-prompts, agent team output files. Success criteria: Single mode quality score ≥ 7/10; Repromptception per-agent prompt quality score 8+/10; all required sections present, actionable and specific.
adaptive-compaction
IncludedAdaptive add-on policy and recovery layer that decides WHEN to compact, prune, snapshot, or fork -- replacing fixed-percent auto-compaction across Claude Code, Codex, and MCP-capable hosts. Trigger on auto-compact timing or damage: "when should I compact", "is it safe to compact now or start a fresh session", "auto-compact fires too early/mid-task", "switching to an unrelated task but the window still has space", "context rot", "answers get worse the longer the session runs", "the agent forgot the plan or my decisions after it summarized", "add a layer on top that manages context without changing the agent", raising autoCompactWindow to give the policy room, or installing/tuning a cross-tool compaction policy or PreCompact hook -- even when "compaction" is never said but the problem is context-window pressure or post-summarization memory loss. Do NOT use to summarize a conversation, build RAG, write a summarization prompt (decides WHEN not HOW), or answer max-context-length trivia.
agent-skill-creator
IncludedCreate cross-platform agent skills from workflow descriptions. Activates when users ask to create an agent, automate a repetitive workflow, create a custom skill, or need advanced agent creation. Triggers on phrases like create agent for, automate workflow, create skill for, every day I have to, daily I need to, turn process into agent, need to automate, create a cross-platform skill, validate this skill, export this skill, migrate this skill. Supports single skills, multi-agent suites, transcript processing, template-based creation, interactive configuration, cross-platform export, and spec validation.
llm-wiki
IncludedUse when building or maintaining a persistent personal knowledge base (second brain) in Obsidian where an LLM incrementally ingests sources, updates entity/concept pages, maintains cross-references, and keeps a synthesis current. Triggers include "second brain", "Obsidian wiki", "personal knowledge management", "ingest this paper/article/book", "build a research wiki", "compound knowledge", "Memex", or whenever the user wants knowledge to accumulate across sessions instead of being re-derived by RAG on every query.
skill-master
IncludedAgent Skills authoring, evaluation, and optimization. Create, edit, validate, benchmark, and improve skills following the agentskills.io specification. Use when designing SKILL.md files, structuring skill folders (references, scripts, assets), ingesting external documentation into skills, running trigger evals, benchmarking skill quality, optimizing descriptions, or performing blind A/B comparisons. Keywords: agentskills.io, SKILL.md, skill authoring, eval, benchmark, trigger optimization.