Skip to main content

LangChain: LLM Application Framework Guide 2026

LangChain is the most widely used framework for building LLM-powered applications. It provides composable building blocks for RAG pipelines, autonomous agents, document processing, conversation memory, and LLM chain orchestration — with integrations for 100+ LLM providers, vector databases, and external tools. Build production AI apps faster with LCEL's declarative chain syntax.

✓ LCEL composable chains ✓ 100+ LLM integrations ✓ RAG pipelines ✓ Agents & tools ✓ LangSmith observability
Share this tool: X / Twitter LinkedIn
✓ 60,000+ developers use DevPlaybook ★★★★★ 4.8 / 5 on Gumroad ✓ MIT licensed · Instant download ✓ No login required

Related Products

on Gumroad

You Might Also Need

More Free Tools

Enjoying this tool? Get more like it.

Weekly developer tool guides, productivity playbooks & AI tricks. Free. No spam.

DevPlaybook Pro 7 days free

Unlock AI-Powered Dev Tools

  • ⚡ AI Code Review, Doc Generator & SQL Builder
  • ⚡ All premium templates & early access
  • ⚡ Member discounts on Gumroad products
Start Free Trial →

$9/mo after trial · Cancel anytime

Want the full toolkit?

Get DevPlaybook Pro

Every template, guide, boilerplate, and automation script in one bundle. 13 premium products — grab them all at once and save big.

$79
$241 separately Save $162 (67% off)
Get DevPlaybook Pro — $79 →

MIT licensed · Instant download · No subscription

See what's included → Browse all deals →

LCEL: LangChain Expression Language

Build composable chains with the pipe operator. Every component is a Runnable with invoke/stream/batch support.

pip install langchain langchain-openai langchain-community

from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser

llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)

# LCEL chain — pipe operator composes Runnables
prompt = ChatPromptTemplate.from_messages([
    ("system", "You are a helpful developer assistant. Be concise."),
    ("human", "{question}")
])

chain = prompt | llm | StrOutputParser()

# Invoke synchronously
result = chain.invoke({"question": "What is HNSW indexing?"})
print(result)

# Stream tokens in real-time
for chunk in chain.stream({"question": "Explain RAG in 3 steps"}):
    print(chunk, end="", flush=True)

# Batch multiple inputs efficiently
results = chain.batch([
    {"question": "What is pgvector?"},
    {"question": "What is Qdrant?"},
    {"question": "What is LangSmith?"},
])

# Async support (in async context)
# result = await chain.ainvoke({"question": "..."})

Building a RAG Pipeline with LCEL

Load documents, split, embed, store in a vector DB, then wire up a retrieval-augmented generation chain.

from langchain_community.document_loaders import WebBaseLoader, DirectoryLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_openai import OpenAIEmbeddings
from langchain_community.vectorstores import Chroma
from langchain_core.runnables import RunnablePassthrough
from langchain_core.prompts import ChatPromptTemplate

# 1. Load documents
loader = DirectoryLoader("./docs", glob="**/*.md")
docs = loader.load()

# 2. Split into chunks
splitter = RecursiveCharacterTextSplitter(
    chunk_size=1000,
    chunk_overlap=200,
    separators=["\n\n", "\n", ".", " "]
)
chunks = splitter.split_documents(docs)

# 3. Embed and store in vector database
embeddings = OpenAIEmbeddings(model="text-embedding-3-small")
vectorstore = Chroma.from_documents(chunks, embeddings, persist_directory="./chroma")
retriever = vectorstore.as_retriever(search_kwargs={"k": 4})

# 4. RAG prompt template
rag_prompt = ChatPromptTemplate.from_messages([
    ("system", """Answer the question using only the following context.
If the answer is not in the context, say "I don't know."

Context:
{context}"""),
    ("human", "{question}")
])

def format_docs(docs):
    return "\n\n".join(doc.page_content for doc in docs)

# 5. LCEL RAG chain
rag_chain = (
    {"context": retriever | format_docs, "question": RunnablePassthrough()}
    | rag_prompt
    | llm
    | StrOutputParser()
)

answer = rag_chain.invoke("What is the main architecture of Milvus?")
print(answer)

LangChain Agents with Tool Use

Create an agent that dynamically decides which tools to call to answer a user's question.

from langchain_core.tools import tool
from langchain.agents import create_tool_calling_agent, AgentExecutor
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
import httpx

@tool
def web_search(query: str) -> str:
    """Search the web for current information about a topic."""
    # Placeholder — integrate Tavily or SerpAPI in production
    return f"Search results for: {query}"

@tool
def calculator(expression: str) -> str:
    """Evaluate a mathematical expression. Input: valid Python math expression."""
    try:
        return str(eval(expression, {"__builtins__": {}}))
    except Exception as e:
        return f"Error: {e}"

tools = [web_search, calculator]

agent_prompt = ChatPromptTemplate.from_messages([
    ("system", "You are a helpful assistant. Use tools when needed."),
    ("human", "{input}"),
    MessagesPlaceholder("agent_scratchpad")
])

agent = create_tool_calling_agent(llm, tools, agent_prompt)
executor = AgentExecutor(agent=agent, tools=tools, verbose=True)

result = executor.invoke({"input": "What is 256 * 1536 and why does that number matter for embeddings?"})
print(result["output"])

# Enable LangSmith tracing (set env vars)
import os
os.environ["LANGCHAIN_TRACING_V2"] = "true"
os.environ["LANGCHAIN_API_KEY"] = "YOUR_LANGSMITH_KEY"

LangChain vs LlamaIndex vs Haystack vs Semantic Kernel

Feature LangChain LlamaIndex Haystack Semantic Kernel
Primary focusChains & agentsRAG & data indexingNLP pipelinesEnterprise .NET/Python
Agent supportExcellentGoodBasicExcellent (Planner)
RAG qualityGoodExcellentGoodGood
ObservabilityLangSmithLlamaCloudHayhooksAzure Monitor
LLM integrations100+50+30+20+
LanguagePython / JSPython / TSPythonC# / Python
Best forGeneral AI apps, agentsComplex RAG, data Q&ANLP production pipelinesMicrosoft ecosystem

Frequently Asked Questions

What is LangChain and what is it used for?▼

LangChain is an open-source framework for building applications powered by large language models. It provides abstractions for connecting LLMs to data sources (documents, databases, APIs), chaining operations together, building autonomous agents with tools, managing conversation memory, and evaluating outputs. It is the most widely-adopted LLM framework with integrations for 100+ LLM providers, vector stores, and tools.

What is LCEL (LangChain Expression Language)?▼

LCEL is LangChain's declarative composition syntax using the pipe operator (|). It replaces the old chain classes (LLMChain, ConversationalRetrievalChain) with composable Runnables. A chain looks like: prompt | llm | output_parser. LCEL provides streaming, batching, async, and parallel execution out-of-the-box. Every LCEL chain is a Runnable with invoke/stream/batch/astream methods.

What is LangSmith and why use it?▼

LangSmith is LangChain's observability and evaluation platform. It automatically traces every LLM call, retrieval step, and tool invocation in your chain — capturing inputs, outputs, latency, and token counts. You can debug chain behavior, create evaluation datasets, run A/B tests between prompts, and set up automated regression tests. It connects with one environment variable: LANGCHAIN_TRACING_V2=true.

How does LangChain handle memory in conversations?▼

LangChain provides several memory types: ConversationBufferMemory (full history), ConversationSummaryMemory (LLM-summarized), ConversationBufferWindowMemory (last N messages), and ConversationSummaryBufferMemory (hybrid). In LCEL, memory is typically managed by passing chat history as a variable in the prompt and updating it externally, or using RunnableWithMessageHistory for automatic history management.

LangChain vs LlamaIndex: which should I choose?▼

LangChain is a general-purpose LLM application framework — excellent for agents, tool use, multi-step chains, and diverse integrations. LlamaIndex is more focused on the data ingestion and retrieval layer — it excels at complex RAG patterns like multi-document synthesis, hierarchical indexing, and query routing. Many production systems use both: LlamaIndex for ingestion/retrieval and LangChain for the agent/chain orchestration layer.

What are LangChain agents and when should I use them?▼

LangChain agents let an LLM decide which tools to call at runtime based on the user's request. You provide a list of tools (web search, calculator, SQL query, code executor) and the LLM generates a sequence of tool calls to answer the question. Use agents when the task requires dynamic decision-making — e.g., 'research this topic and write a summary.' For deterministic workflows, a fixed LCEL chain is simpler and more reliable.

Share this tool: X / Twitter LinkedIn
✓ 60,000+ developers use DevPlaybook ★★★★★ 4.8 / 5 on Gumroad ✓ MIT licensed · Instant download ✓ No login required

Related Products

on Gumroad

You Might Also Need

More Free Tools

AI Hallucination Detector AI Safety Checklist Generator CrewAI Agent Config Generator AI Model Comparator Test Coverage Calculator AI Agent Memory Planner AI Model Comparison Tool Jotai Atom Explorer Embedding Storage Calculator RAG Chunk Size Optimizer LLM Cost Calculator CSS Container Query Builder LLM Context Window Calculator AI Prompt Cost Calculator LLM JSON Schema Builder AI Agent Run Cost Tracker AI Pipeline DAG Builder LLM Benchmark Calculator Prompt Injection Tester LangChain PromptTemplate Builder AI Token Cost Calculator MySQL Query Explainer PostgreSQL EXPLAIN Analyzer GraphQL Fragment Generator Jest Coverage Config Generator AI Model Benchmark Comparator Cron Expression Explainer Font Pairing Preview LLM Prompt Cost Calculator AI Model Context Window Visualizer RAG Chunking Calculator OpenAI Prompt Tester AI Rate Limit Calculator LLM System Prompt Analyzer Vibe Coding Prompt Optimizer AI IDE Comparator RAG Chunking Calculator Token Counter & Cost Estimator AI Model Comparison Table LLM Prompt Template Builder AI Commit Message Generator AI Doc Generator — Pro Tool AI Regex Explainer — Pro Tool AI System Guardian Vitest Configuration Generator Mermaid Diagram Generator Elasticsearch Query Tester mTLS Certificate Chain Builder Prompt Token Estimator JS Prototype Chain Visualizer OpenAI Token Counter System Prompt Builder Token Context Calculator LLM Prompt Caching Calculator Multi-Agent Orchestration Planner AI Prompt Token Estimator OpenAI Function Calling Generator AI Context Window Visualizer AI API Rate Limit Calculator HTTP Headers Analyzer AI Code Review — Pro Tool AI Error Explainer — Pro Tool AI SQL Builder — Pro Tool AI Unit Test Generator — Pro Tool Color Palette Generator Docker Compose Generator JWT Decoder Prompt Template Builder Regex Tester RSA Key Pair Generator SMTP Server Tester Biome Config Generator Terraform Variable Validator Haproxy Config Validator SBOM Generator AI Variable Namer AI PR Description Generator AI JSDoc Generator K8s Resource Limits Calculator Regex Flags Explainer LLM Token Counter OAuth2 Flow Visualizer Jest Testing Framework Guide Vitest Guide — Vite-native Testing Playwright E2E Testing Guide Core Web Vitals Calculator Solana Program ID Generator Multi-Chain Wallet Address Validator AI Embeddings Dimension Explorer Bezier Curve Editor Embedding Similarity Calculator TypeScript Discriminated Union Builder Core Web Vitals Budget Calculator JWT Decoder & Validator Blockchain Transaction Fee Calculator Database Query Cost Analyzer

Related Articles

Mar 27, 2026 · 16 min read

Vercel AI SDK vs LangChain.js vs Mastra: AI Framework Comparison 2026

A comprehensive technical comparison of Vercel AI SDK, LangChain.js, and Mastra for building AI applications in 2026 — covering streaming, tool calling, RAG, agents, and when to choose each.

Apr 2, 2026 · 10 min read

LLM Application Architecture Patterns 2026: RAG, Agents, Tool-Calling & Memory

Design production LLM applications with proven architectural patterns: RAG pipelines, agent loops, tool-calling, memory systems, and evaluation frameworks.

Mar 28, 2026 · 12 min read

Building a RAG Pipeline from Scratch: Embeddings, Vector Databases, and Retrieval

Step-by-step guide to building a production-ready RAG pipeline in Python. Covers embeddings, chunking strategies, Chroma and Pinecone setup, hybrid search, reranking, and evaluation with RAGAS.

Mar 28, 2026 · 18 min read

Building a Production RAG Pipeline: Complete Implementation Guide 2026

A comprehensive guide to building production-ready RAG pipelines in 2026. Covers chunking strategies, embedding models, vector store selection, retrieval techniques, reranking, evaluation with RAGAS/TruLens, and LangChain vs LlamaIndex vs custom implementations.

Mar 27, 2026 · 14 min read

LangChain vs LlamaIndex: Which AI Framework Should You Use in 2026?

A head-to-head comparison of LangChain vs LlamaIndex in 2026 — covering architecture philosophy, RAG pipelines, agent support, ecosystem, and a decision framework for your next AI project.

Enjoying this tool? Get more like it.

Weekly developer tool guides, productivity playbooks & AI tricks. Free. No spam.

DevPlaybook Pro 7 days free

Unlock AI-Powered Dev Tools

  • ⚡ AI Code Review, Doc Generator & SQL Builder
  • ⚡ All premium templates & early access
  • ⚡ Member discounts on Gumroad products
Start Free Trial →

$9/mo after trial · Cancel anytime

Want the full toolkit?

Get DevPlaybook Pro

Every template, guide, boilerplate, and automation script in one bundle. 13 premium products — grab them all at once and save big.

$79
$241 separately Save $162 (67% off)
Get DevPlaybook Pro — $79 →

MIT licensed · Instant download · No subscription

See what's included → Browse all deals →