Overview
LangChain is the most popular and comprehensive framework for building applications with language models. Since its release in 2023, it has become the de facto standard for LLM application development, providing a modular architecture for chains, agents, retrieval systems, and more.
Features
- ✓1000+ integrations with external services
- ✓Pre-built chains for common patterns
- ✓Powerful agent framework with multiple paradigms
- ✓Built-in memory systems for stateful conversations
- ✓Complete RAG pipeline support
- ✓LangGraph integration for orchestration
Installation
pip install langchain langchain-openai langchain-communityPros
- +Largest ecosystem with 1000+ integrations
- +Comprehensive coverage of all LLM app development aspects
- +Extensive documentation with many examples
- +Large, active community with frequent updates
- +Modular, composable design
- +Python and TypeScript support
Cons
- −Complex API surface can be overwhelming
- −Frequent breaking changes due to rapid development
- −Performance overhead from abstraction layers
- −Some documentation areas incomplete or outdated
- −Large dependency tree increases bundle size
Alternatives
Documentation
LangChain
Overview
LangChain is the most popular and comprehensive framework for building applications with language models. Since its release in 2023, it has become the de facto standard for LLM application development, providing a modular architecture for chains, agents, retrieval systems, and more.
Installation
# Core package
pip install langchain
# With OpenAI support
pip install langchain-openai
# With all community integrations
pip install langchain-community
# Full installation
pip install langchain langchain-openai langchain-community langchain-core
Core Components
Models
from langchain_openai import ChatOpenAI, OpenAI
from langchain_anthropic import ChatAnthropic
from langchain_google_genai import ChatGoogleGenerativeAI
# Chat models
llm = ChatOpenAI(model="gpt-4o", temperature=0.7)
# Completion models
llm = OpenAI(model="gpt-4-turbo", temperature=0.7)
Prompts
from langchain_core.prompts import ChatPromptTemplate, PromptTemplate
# Chat prompt
chat_prompt = ChatPromptTemplate.from_messages([
("system", "You are a helpful assistant."),
("human", "{input}"),
])
# Filled prompt
prompt = chat_prompt.format(input="Hello!")
# Prompt template with variables
template = PromptTemplate.from_template("Tell me a joke about {topic}")
Documents
from langchain_core.documents import Document
doc = Document(
page_content="The capital of France is Paris.",
metadata={"source": "wikipedia", "page": 1}
)
Embeddings
from langchain_openai import OpenAIEmbeddings
from langchain_community.embeddings import HuggingFaceEmbeddings
embeddings = OpenAIEmbeddings(model="text-embedding-3-small")
Vector Stores
from langchain_chroma import Chroma
from langchain_community.vectorstores import FAISS, Pinecone, Weaviate
# Chroma (local)
vectorstore = Chroma.from_documents(documents, embeddings)
# FAISS (local, fast)
vectorstore = FAISS.from_documents(documents, embeddings)
# Pinecone (cloud)
vectorstore = Pinecone.from_documents(documents, embeddings, index_name="my-index")
Key Features
📚 Extensive Ecosystem
LangChain's greatest strength is its massive ecosystem:
- 1000+ Integrations: Connect to virtually any data source, API, or service
- Pre-built Chains: Ready-to-use patterns for common tasks
- Community Contributions: Active community contributing new integrations daily
- LangChain Hub: Shared, versioned chains and prompts
🔗 Chain Composition
Build complex applications by composing chains:
from langchain.chains import RetrievalQA
from langchain.chat_models import ChatOpenAI
from langchain.vectorstores import Chroma
from langchain.embeddings import OpenAIEmbeddings
# Simple RAG chain
qa_chain = RetrievalQA.from_chain_type(
llm=ChatOpenAI(model="gpt-4o"),
retriever=Chroma.from_documents(documents, OpenAIEmbeddings()).as_retriever()
)
result = qa_chain.invoke("What is the capital of France?")
🤖 Agent Orchestration
Powerful agent capabilities with multiple paradigms:
from langchain.agents import AgentExecutor, create_tool_calling_agent
from langchain.tools import tool
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
@tool
def search(query: str) -> str:
"""Search for information."""
return search_results
@tool
def calculator(expression: str) -> float:
"""Calculate mathematical expressions."""
return eval(expression)
tools = [search, calculator]
llm = ChatOpenAI(model="gpt-4o")
prompt = ChatPromptTemplate.from_messages([...])
agent = create_tool_calling_agent(llm, tools, prompt)
executor = AgentExecutor(agent=agent, tools=tools)
result = executor.invoke({"input": "What is 2+2 and search for AI news?"})
🗄️ Memory Systems
Built-in memory for stateful conversations:
from langchain.memory import ConversationBufferMemory, ConversationSummaryMemory
# Buffer memory - stores full conversation history
buffer_memory = ConversationBufferMemory()
# Summary memory - stores summarized conversation
summary_memory = ConversationSummaryMemory(llm=ChatOpenAI())
# Vector store memory - semantic search of past conversations
from langchain_community.vectorstores import FAISS
vector_memory = ConversationVectorStoreMemory(vectorstore=FAISS(...))
📖 Retrieval-Augmented Generation (RAG)
Complete RAG pipeline support:
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.document_loaders import PyPDFLoader
from langchain.chains import create_retrieval_chain
from langchain.chains.combine_documents import create_stuff_documents_chain
# Load and split documents
loader = PyPDFLoader("document.pdf")
docs = loader.load()
splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
splits = splitter.split_documents(docs)
# Create vector store and retriever
vectorstore = Chroma.from_documents(splits, OpenAIEmbeddings())
retriever = vectorstore.as_retriever()
# Create RAG chain
question_answer_chain = create_stuff_documents_chain(llm, prompt)
rag_chain = create_retrieval_chain(retriever, question_answer_chain)
response = rag_chain.invoke({"input": "What is the main finding?"})
🧪 LangGraph Integration
LangChain's agent orchestration layer:
from langgraph.graph import StateGraph, END
class AgentState(TypedDict):
messages: list
next: str
builder = StateGraph(AgentState)
builder.add_node("agent", agent_node)
builder.add_node("tools", tools_node)
builder.add_edge("agent", "tools")
builder.add_edge("tools", "agent")
builder.set_entry_point("agent")
builder.set_finish_point("agent")
graph = builder.compile()
Use Cases
LangChain excels in scenarios requiring maximum flexibility and extensive integrations:
| Use Case | Why LangChain |
|---|---|
| RAG Applications | Complete pipeline from document loading to retrieval to generation |
| Complex Agent Systems | Multiple agent paradigms (ReAct, Plan-and-Execute, Multi-Agent) |
| Multi-Provider Deployments | Support for 50+ LLM providers |
| Enterprise Applications | Extensive integrations with enterprise tools and databases |
| Prototyping to Production | Same codebase works for both development and production |
Pros & Cons
✅ Pros
- Largest Ecosystem — 1000+ integrations with external services and data sources
- Comprehensive — Covers every aspect of LLM application development
- Well-Documented — Extensive documentation with many examples
- Active Community — Large, active community with frequent updates
- Production-Ready — Used by many companies in production
- Modular Design — Composable components for flexible architectures
- Multi-Language — Python and JavaScript/TypeScript support
- LangGraph — Built-in graph-based workflow orchestration
❌ Cons
- Complexity — Large API surface can be overwhelming for beginners
- Frequent Breaking Changes — Rapid development leads to API changes
- Performance Overhead — Abstraction layers add some latency
- Documentation Quality — Some areas have incomplete or outdated docs
- Bundle Size — Large dependency tree can increase application size
- Version Confusion — LangChain 0.x vs 1.x can be confusing
Comparison with Alternatives
| Feature | LangChain | PydanticAI | CrewAI | DSPy |
|---|---|---|---|---|
| Ecosystem Size | Massive | Moderate | Moderate | Small |
| Complexity | High | Low-Medium | Low | High |
| Type Safety | Good | Excellent | Moderate | Excellent |
| Multi-Language | Yes | Python only | Python only | Python only |
| Learning Curve | Steep | Moderate | Gentle | Steep |
| Breaking Changes | Frequent | Rare | Rare | Rare |
| Best For | Complex apps, integrations | Clean Python code | Multi-agent teams | Production RAG |
Real-World Examples
Example 1: Simple RAG Chatbot
from langchain_community.chat_message_histories import ChatMessageHistory
from langchain_core.runnables.history import RunnableWithMessageHistory
from langchain_openai import ChatOpenAI
from langchain_chroma import Chroma
from langchain_openai import OpenAIEmbeddings
# Create vector store
vectorstore = Chroma.from_documents(documents, OpenAIEmbeddings())
retriever = vectorstore.as_retriever()
# Create chain
from langchain.chains import create_retrieval_chain
from langchain.chains.combine_documents import create_stuff_documents_chain
from langchain_core.prompts import ChatPromptTemplate
prompt = ChatPromptTemplate.from_messages([
("system", "You are a helpful assistant. Answer based on the following context:"),
("human", "{input}"),
])
question_answer_chain = create_stuff_documents_chain(llm, prompt)
rag_chain = create_retrieval_chain(retriever, question_answer_chain)
# Add message history
store = {}
def get_session_history(session_id: str):
if session_id not in store:
store[session_id] = ChatMessageHistory()
return store[session_id]
with_message_history = RunnableWithMessageHistory(
rag_chain,
get_session_history,
input_messages_key="input",
)
# Use it
response = with_message_history.invoke(
{"input": "What is the capital of France?"},
config={"configurable": {"session_id": "session1"}}
)
Example 2: Multi-Agent System with LangGraph
from langgraph.graph import StateGraph, END, MessagesState
from langgraph.prebuilt import ToolNode
# Define tools
from langchain_core.tools import tool
@tool
def search_web(query: str):
"""Search the web for information."""
# Implementation
@tool
def calculate(expression: str):
"""Calculate mathematical expressions."""
return eval(expression)
tools = [search_web, calculate]
# Define nodes
async def agent_node(state: MessagesState):
messages = state["messages"]
response = await llm.ainvoke(messages, {"tools": tools})
return {"messages": [response]}
# Build graph
builder = StateGraph(MessagesState)
builder.add_node("agent", agent_node)
builder.add_node("tools", ToolNode(tools))
builder.add_edge("agent", "tools")
builder.add_conditional_edges(
"tools",
lambda state: "agent" if state["messages"][-1].tool_calls else END,
)
builder.set_entry_point("agent")
graph = builder.compile()
Best Practices
- Use LangChain 1.x — The latest version has significant improvements and fixes many breaking changes.
- Pin versions — LangChain changes frequently; pin your dependencies.
- Use LangGraph for complex workflows — Better control and debugging than chains.
- Leverage LangSmith — For tracing, debugging, and monitoring in production.
- Keep chains simple — Start with simple chains, compose them for complexity.
- Use typed prompts — Leverage Pydantic for structured output.
- Cache embeddings — Don't re-embed documents on every run.
Troubleshooting
| Issue | Solution |
|---|---|
| Import errors | Ensure you have langchain-core, langchain-community, and provider packages |
| Chain not working | Check prompt template variable names match chain inputs |
| Memory not persisting | Use external storage (Redis, Postgres) for production |
| Slow performance | Use streaming, batch requests, and caching |
| Token limits exceeded | Use RecursiveCharacterTextSplitter with appropriate chunk sizes |
Resources
- Official Docs: https://python.langchain.com/
- JavaScript Docs: https://js.langchain.com/
- GitHub: https://github.com/langchain-ai/langchain
- Hub: https://smith.langchain.com/hub
- Forum: https://discuss.langchain.com/
- LangSmith: https://smith.langchain.com/
Last updated: June 2026
