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.
Related Products
on GumroadDeveloper Productivity Bundle
Stop rebuilding the same setup every project. 51 VSCode snippets, 40 Git aliases, 5 Docker Compose stacks, 5 GitHub Actions workflows, 5 README templates, and a dotfiles kit. Set up a professional dev environment in under an hour.
Buy on Gumroad →AI Prompt Engineering Toolkit
58 structured prompt templates for Claude, ChatGPT, and Gemini — organized by use case. Code Review, Debugging, Documentation, Architecture, and 10 model-specific tips. Stop writing prompts from scratch.
Buy on Gumroad →Developer Cheat Sheet Bundle
10 print-ready cheat sheets for the tools developers use every day: Git, Docker, Linux CLI, SQL, Regex, HTTP Status codes, VS Code shortcuts, Bash scripting, jq/JSON, and Markdown.
Buy on Gumroad →You Might Also Need
JSON Formatter & Validator
Format, beautify, and validate JSON online. Paste your JSON to instantly pretty-print it with 2-space, 4-space, or tab indentation. Minify JSON too. Free, runs in your browser.
Open free tool →
Regex Tester
Free regex tester. Test regular expressions against multiple strings with expected match/no-match assertions — see instant pass/fail results. Built-in presets for email, URL, IPv4, and phone. Pro: unl
Open free tool →
Base64 Encoder & Decoder
Free Base64 Encoder & Decoder. Convert text, images, and any file to Base64 and back. Supports URL-safe Base64, image data URIs, and file download from Base64. Runs 100% in your browser — no data sent
Open free tool →
More Free Tools
Related Articles
curl 深度使用手冊:API 測試從入門到進階
curl 是每位開發者必備的 CLI 工具。本文涵蓋 GET/POST/PUT/DELETE 請求、認證、header 設定、檔案上傳、除錯技巧,以及 REST API 測試的完整實戰範例。
Best AI Code Review Tools 2026: CodeRabbit, Sourcery, DeepCode & Bito Compared
Compare top AI code review tools for 2026: CodeRabbit, Sourcery, DeepCode, and Bito. Features, pricing, GitHub/GitLab integration, and choosing the right tool for your team.
AI Code Review Tools 2026: GitHub Copilot, CodeRabbit, Qodo Merge Ranked
Compare AI code review tools for 2026: GitHub Copilot code review, CodeRabbit, Qodo Merge, Sourcery, and PR-Agent. Pricing, accuracy, and GitHub integration.
AI Coding Tools Comparison 2026: GitHub Copilot vs Cursor vs Windsurf vs Cline
Comprehensive comparison of the best AI coding tools in 2026: GitHub Copilot, Cursor, Windsurf, and Cline. Pricing, features, model support, and real-world benchmarks.
AI Pair Programming in 2026: GitHub Copilot vs Cursor vs Claude Code
Master AI pair programming in 2026. Compare GitHub Copilot, Cursor, and Claude Code for autocomplete, chat, and agentic workflows. Includes setup guides and productivity tips.
Enjoying this tool? Get more like it.
Weekly developer tool guides, productivity playbooks & AI tricks. Free. No spam.
Unlock AI-Powered Dev Tools
- ⚡ AI Code Review, Doc Generator & SQL Builder
- ⚡ All premium templates & early access
- ⚡ Member discounts on Gumroad products
$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.
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 focus | Chains & agents | RAG & data indexing | NLP pipelines | Enterprise .NET/Python |
| Agent support | Excellent | Good | Basic | Excellent (Planner) |
| RAG quality | Good | Excellent | Good | Good |
| Observability | LangSmith | LlamaCloud | Hayhooks | Azure Monitor |
| LLM integrations | 100+ | 50+ | 30+ | 20+ |
| Language | Python / JS | Python / TS | Python | C# / Python |
| Best for | General AI apps, agents | Complex RAG, data Q&A | NLP production pipelines | Microsoft 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.
Related Products
on GumroadAI Prompt Engineering Toolkit
58 structured prompt templates for Claude, ChatGPT, and Gemini — organized by use case. Code Review, Debugging, Documentation, Architecture, and 10 model-specific tips. Stop writing prompts from scratch.
Buy on Gumroad →AI Developer Prompts Pack
55 battle-tested prompt templates for the workflows developers actually use: code review, debugging, architecture, documentation, and testing. Stop writing prompts from scratch.
Buy on Gumroad →Developer Productivity Bundle
Stop rebuilding the same setup every project. 51 VSCode snippets, 40 Git aliases, 5 Docker Compose stacks, 5 GitHub Actions workflows, 5 README templates, and a dotfiles kit. Set up a professional dev environment in under an hour.
Buy on Gumroad →You Might Also Need
AI Hallucination Detector
Scan LLM-generated text for hallucination risk signals: fabricated citations, overconfident claims, suspect statistics, and verification gaps. Risk score 0-100 with highlighted problem spans.
Open free tool →
AI Safety Checklist Generator
Generate a customized AI safety evaluation checklist for your deployment. Covers technical safety, content moderation, security, bias, privacy, and regulatory compliance. Export to Markdown.
Open free tool →
CrewAI Agent Config Generator
Build CrewAI agent configurations visually. Define roles, goals, backstories, and tools. Generate YAML or Python code for multi-agent crews.
Open free tool →
More Free Tools
Related Articles
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.
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.
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.
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.
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.
Unlock AI-Powered Dev Tools
- ⚡ AI Code Review, Doc Generator & SQL Builder
- ⚡ All premium templates & early access
- ⚡ Member discounts on Gumroad products
$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.
MIT licensed · Instant download · No subscription
See what's included → Browse all deals →