LA

LangChain

92,000Python/TypeScriptFull-Stack

The most popular framework for building applications with language models.

PythonTypeScriptEcosystemRAGAgents

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-community

Pros

  • +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 CaseWhy LangChain
RAG ApplicationsComplete pipeline from document loading to retrieval to generation
Complex Agent SystemsMultiple agent paradigms (ReAct, Plan-and-Execute, Multi-Agent)
Multi-Provider DeploymentsSupport for 50+ LLM providers
Enterprise ApplicationsExtensive integrations with enterprise tools and databases
Prototyping to ProductionSame 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

FeatureLangChainPydanticAICrewAIDSPy
Ecosystem SizeMassiveModerateModerateSmall
ComplexityHighLow-MediumLowHigh
Type SafetyGoodExcellentModerateExcellent
Multi-LanguageYesPython onlyPython onlyPython only
Learning CurveSteepModerateGentleSteep
Breaking ChangesFrequentRareRareRare
Best ForComplex apps, integrationsClean Python codeMulti-agent teamsProduction 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

  1. Use LangChain 1.x — The latest version has significant improvements and fixes many breaking changes.
  2. Pin versions — LangChain changes frequently; pin your dependencies.
  3. Use LangGraph for complex workflows — Better control and debugging than chains.
  4. Leverage LangSmith — For tracing, debugging, and monitoring in production.
  5. Keep chains simple — Start with simple chains, compose them for complexity.
  6. Use typed prompts — Leverage Pydantic for structured output.
  7. Cache embeddings — Don't re-embed documents on every run.

Troubleshooting

IssueSolution
Import errorsEnsure you have langchain-core, langchain-community, and provider packages
Chain not workingCheck prompt template variable names match chain inputs
Memory not persistingUse external storage (Redis, Postgres) for production
Slow performanceUse streaming, batch requests, and caching
Token limits exceededUse RecursiveCharacterTextSplitter with appropriate chunk sizes

Resources


Last updated: June 2026