Agentic Research

Complete LangChain Tutorial 2026: Building Enterprise-Grade LLM Applications from Scratch

2026/06/3086 min readBryan Chan閱讀中文原文
TopicsLangChainLLMAI AgentRAGPython

LangChain Complete Tutorial 2026: Building Enterprise-Grade LLM Applications from Scratch

TL;DR: LangChain is the leading framework for LLM application development in 2026, with 135K+ GitHub stars, and 35% of Fortune 500 enterprises are using it. This article starts from scratch and walks you through building Chain → RAG → Agent → LangGraph workflows with Python, then deploying them to production.


Table of Contents

  1. What is LangChain?
  2. Core Architecture: The Seven Major Components
  3. Installation and Environment Setup
  4. The First Chain: Getting Started with LCEL
  5. RAG: Document Q&A System
  6. Agent: Autonomous Decision-Making Agent
  7. LangGraph: Stateful Workflows
  8. LangSmith: Debugging and Monitoring
  9. Ecosystem Overview
  10. Production Deployment Best Practices
  11. LangChain vs. Competitor Comparison
  12. Frequently Asked Questions (FAQ)

1. What is LangChain?

One-Sentence Definition

LangChain is an open-source Python framework that helps you build real applications with large language models (LLMs).

It is not an LLM model itself, but a middle-layer framework that connects LLMs (GPT-4, Claude, Gemini, etc.) with your business logic, external data, and tool APIs.

┌─────────────────────────────────────┐
│          Your Business Application                  │
│   (Customer Service Bot / Document Q&A / Data Analysis)  │
├─────────────────────────────────────┤
│          LangChain Framework              │
│   Prompt │ Chain │ Agent │ Memory    │
├─────────────────────────────────────┤
│          LLM + External Resources              │
│   OpenAI │ Claude │ Database │ API     │
└─────────────────────────────────────┘

Why Is LangChain Needed?

Calling the LLM API directly only supports single-turn question answering. But real-world business needs:

RequirementDirect API CallsUsing LangChain
Single-turn Q&A✅✅
Multi-step reasoning chains❌ You have to build it yourself✅ Chain composition
Reading company documents to answer❌ You have to build RAG yourself✅ Built-in RAG components
Autonomous tool selection❌ You have to write the logic yourself✅ Agent framework
Remembering conversation history❌ You have to manage it yourself✅ Memory module
Switching between different LLMs❌ You have to change code✅ Unified interface
Debugging and tracing❌ You have to add logging yourself✅ LangSmith integration

Key Figures (2026)

  • GitHub Stars: 135,000+
  • Supported models: 80+ providers (OpenAI / Anthropic / Google / local models)
  • Production adoption: 35% of Fortune 500 companies
  • v1.0 release: October 2025 (architecture stabilization)
  • Klarna / LinkedIn / Uber / Replit all use LangChain for Agent workflows

2. Core Architecture: The Seven Major Components

LangChain's design philosophy is composable building blocks. You do not need to use all seven, but each has a clear purpose:

Component Overview

┌──────────────────────────────────────────────────┐
│                 LangChain Seven Major Components                  │
├──────────────────────────────────────────────────┤
│                                                  │
│  ① Chat Models ──── Unified interface to call different LLMs           │
│  ② Prompt Templates ── Parameterized prompt templates             │
│  ③ Chains (LCEL) ──── Compose multiple steps with the pipe | operator         │
│  ④ Retrievers ─────── RAG retrieval of external documents              │
│  ⑤ Tools ──────────── External tools for Agents to call         │
│  ⑥ Agents ─────────── Autonomous decision workflows                │
│  ⑦ Memory ─────────── Conversation memory management                  │
│                                                  │
└──────────────────────────────────────────────────┘

① Chat Models, Unified Model Interface

# Switch model providers in one line
from langchain_openai import ChatOpenAI
from langchain_anthropic import ChatAnthropic

# OpenAI
gpt = ChatOpenAI(model="gpt-4o", temperature=0)

# Anthropic
claude = ChatAnthropic(model="claude-sonnet-4-20250514", temperature=0)

# The interface is exactly the same
response = gpt.invoke("Hello")
response = claude.invoke("Hello")

② Prompt Templates, Parameterized Prompts

from langchain_core.prompts import ChatPromptTemplate

# Define the template
prompt = ChatPromptTemplate.from_messages([
    ("system", "You are a professional {role}, answer questions in {language}."),
    ("human", "{question}"),
])

# Fill in parameters
formatted = prompt.invoke({
    "role": "Financial Analyst",
    "language": "Traditional Chinese",
    "question": "Explain what DCF valuation is"
})

③ Chains (LCEL), Pipeline Composition

LCEL (LangChain Expression Language) is the only recommended composition method in 2026. Use the | pipe operator to string components together into a chain:

from langchain_core.output_parsers import StrOutputParser

# Prompt → Model → Parser = a Chain
chain = prompt | gpt | StrOutputParser()

# Invocation
result = chain.invoke({
    "role": "Financial Analyst",
    "language": "Traditional Chinese",
    "question": "Explain what DCF valuation is"
})
print(result)

④ Retrievers: RAG Document Retrieval

# Retrieve relevant documents from vector database
retriever = vectorstore.as_retriever(search_kwargs={"k": 3})
docs = retriever.invoke("What is M&A?")

⑤ Tools, External Tools

from langchain.tools import tool

@tool
def search_stock_price(stock_code: str) -> str:
    """Query real-time Hong Kong stock price"""
    # Your API call logic
    return f"{stock_code} current price HK$128.50"

⑥ Agents, Autonomous Decision Making

from langchain.agents import create_agent

agent = create_agent(
    model="openai:gpt-4o",
    tools=[search_stock_price],
    system_prompt="You are a Hong Kong stock analysis assistant"
)

⑦ Memory, Conversation Memory

# Agent automatically remembers conversation history
result = agent.invoke({
    "messages": [{"role": "user", "content": "What is Tencent's stock price?"}]
})
# On the next call, the Agent remembers the previous question about Tencent

3. Installation and Environment Setup

Basic Installation

# Core libraries
pip install langchain langchain-core

# Model providers (install as needed)
pip install langchain-openai      # OpenAI / GPT
pip install langchain-anthropic   # Anthropic / Claude
pip install langchain-google-genai # Google / Gemini

# Vector database (for RAG)
pip install langchain-community chromadb faiss-cpu

# Document loaders
pip install unstructured beautifulsoup4

# LangSmith debugging (optional but strongly recommended)
pip install langsmith

Environment Variables

# .env file
OPENAI_API_KEY=sk-xxxxxxxxxxxxxxxx
ANTHROPIC_API_KEY=sk-ant-xxxxxxxx
LANGSMITH_API_KEY=lsv2_pt_xxxxxxxx
LANGSMITH_TRACING=true
# Load environment variables
from dotenv import load_dotenv
load_dotenv()

Verify Installation

from langchain_openai import ChatOpenAI

model = ChatOpenAI(model="gpt-4o-mini")
response = model.invoke("Say something to prove you are GPT")
print(response.content)
# If it outputs normally, installation was successful ✅

4. The First Chain: Getting Started with LCEL

Concept: What Is LCEL?

LCEL (LangChain Expression Language) is the syntax for composing components with the | pipe operator. It is similar to Unix pipes:

Input → Prompt Template → LLM → Output Parser → Output

Hands-On: Translator

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

# 1. Define Prompt
prompt = ChatPromptTemplate.from_template(
    "Translate the following text into {target_language}, output only the translation result, do not explain:\n\n{text}"
)

# 2. Initialize model
model = ChatOpenAI(model="gpt-4o-mini", temperature=0)

# 3. Output parser
parser = StrOutputParser()

# 4. Combine into Chain
chain = prompt | model | parser

# 5. Invoke
result = chain.invoke({
    "target_language": "English",
    "text": "The weather is really nice today, perfect for going out for a walk."
})

print(result)
# Output: The weather is really nice today, perfect for going out for a walk.

Advanced: Chaining Multiple Chains

# Chain 1: Translation
translate_chain = prompt | model | parser

# Chain 2: Summary
summarize_prompt = ChatPromptTemplate.from_template(
    "Summarize the following content in one sentence:\n\n{text}"
)
summary_chain = summarize_prompt | model | parser

# Combination: Translation → Summary
full_chain = (
    {"text": translate_chain, "original": lambda x: x["text"]}
    | summarize_prompt
    | model
    | parser
)

Streaming Output

# All Chains support streaming
for chunk in chain.stream({"target_language": "Japanese", "text": "Hello World"}):
    print(chunk, end="", flush=True)

5. RAG: Document Q&A System

RAG (Retrieval-Augmented Generation) is the most common use case for LangChain. How it works:

User query
  ↓
Retrieve relevant document snippets from vector database
  ↓
Feed the document + question together to the LLM
  ↓
LLM generates answer based on document content

Complete RAG Pipeline

from langchain_community.document_loaders import TextLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_openai import OpenAIEmbeddings, ChatOpenAI
from langchain_community.vectorstores import FAISS
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnablePassthrough
from langchain_core.output_parsers import StrOutputParser

# ═══════════════════════════════════════
# Step 1: Load documents
# ═══════════════════════════════════════
loader = TextLoader("company_handbook.txt")
docs = loader.load()

# ═══════════════════════════════════════
# Step 2: Split into small chunks (chunk)
# ═══════════════════════════════════════
splitter = RecursiveCharacterTextSplitter(
    chunk_size=500,     # 500 characters per chunk
    chunk_overlap=50    # 50 character overlap (maintain context continuity)
)
chunks = splitter.split_documents(docs)

print(f"Document split into {len(chunks)} chunks")

# ═══════════════════════════════════════
# Step 3: Vectorize and store in database
# ═══════════════════════════════════════
embeddings = OpenAIEmbeddings(model="text-embedding-3-small")
vectorstore = FAISS.from_documents(chunks, embeddings)
retriever = vectorstore.as_retriever(search_kwargs={"k": 3})

# ═══════════════════════════════════════
# Step 4: Build RAG Chain
# ═══════════════════════════════════════
prompt = ChatPromptTemplate.from_template("""
Answer the question based on the following reference materials. If there is no relevant information in the materials, say "No relevant content found in the materials."

Reference materials:
{context}

Question: {question}
""")

def format_docs(docs):
    """Format retrieved documents into a string"""
    return "\n\n".join(doc.page_content for doc in docs)

rag_chain = (
    {"context": retriever | format_docs, "question": RunnablePassthrough()}
    | prompt
    | ChatOpenAI(model="gpt-4o-mini", temperature=0)
    | StrOutputParser()
)

# ═══════════════════════════════════════
# Step 5: Ask a question!
# ═══════════════════════════════════════
answer = rag_chain.invoke("What is the company's annual leave policy?")
print(answer)

Advanced RAG: Supporting PDF / Word / Webpages

# PDF
from langchain_community.document_loaders import PyPDFLoader
loader = PyPDFLoader("contract.pdf")
docs = loader.load()

# Word
from langchain_community.document_loaders import Docx2txtLoader
loader = Docx2txtLoader("report.docx")

# Webpage
from langchain_community.document_loaders import WebBaseLoader
loader = WebBaseLoader("https://example.com/about")
docs = loader.load()

Advanced RAG: Agentic RAG

Wrap RAG as an Agent tool, allowing the Agent to decide when to retrieve:

from langchain.tools import tool
from langchain.agents import create_agent

@tool
def retrieve_context(query: str) -> str:
    """Retrieve relevant information from the company knowledge base to answer questions"""
    docs = vectorstore.similarity_search(query, k=3)
    return "\n\n".join(doc.page_content for doc in docs)

agent = create_agent(
    model="openai:gpt-4o",
    tools=[retrieve_context],
    system_prompt="You are an enterprise knowledge assistant. Use the retrieve_context tool to query company documents."
)

result = agent.invoke({
    "messages": [{"role": "user", "content": "What is the leave policy?"}]
})
# The Agent will automatically call the retrieve_context tool

6. Agent: Autonomous Decision-Making Agent

An Agent is an LLM plus tools plus a decision loop. The Agent decides which tools to use and how many times to use them.

Minimal Agent

from langchain.agents import create_agent
from langchain.tools import tool

# Define tools
@tool
def get_weather(city: str) -> str:
    """Query city weather"""
    return f"{city} is sunny today, 28°C, humidity 65%"

@tool
def calculate(expression: str) -> str:
    """Calculate a mathematical expression"""
    return str(eval(expression))

# Create Agent
agent = create_agent(
    model="openai:gpt-4o",
    tools=[get_weather, calculate],
    system_prompt="You are a helpful assistant that can check the weather and do calculations."
)

# Run
result = agent.invoke({
    "messages": [{"role": "user", "content": "What is the temperature in Hong Kong today? If you multiply the temperature by 2, what is it?"}]
})
# The Agent will:
# 1. Call get_weather("Hong Kong") → 28°C
# 2. Call calculate("28 * 2") → 56
# 3. Answer "In Hong Kong it is 28°C today, multiplied by 2 is 56"

Custom Tool: Connecting to a Database

@tool
def query_database(sql: str) -> str:
    """Execute SQL query on company database"""
    import sqlite3
    conn = sqlite3.connect("company.db")
    cursor = conn.execute(sql)
    results = cursor.fetchall()
    conn.close()
    return str(results)

# Agent can automatically generate SQL queries
agent = create_agent(
    model="openai:gpt-4o",
    tools=[query_database],
    system_prompt="You are a data analysis assistant. Use the query_database tool to query data."
)

result = agent.invoke({
    "messages": [{"role": "user", "content": "What were the 3 products with the highest sales last month?"}]
})

Custom Tool: Calling an External API

import requests

@tool
def search_hkex_news(stock_code: str) -> str:
    """Search HKEXnews latest announcements"""
    url = f"https://www1.hkexnews.hk/search/titlesearch.xhtml?lang=zh"
    # ... API call logic
    return "Latest announcement content..."

@tool
def get_stock_quote(stock_code: str) -> str:
    """Get real-time quotes for Hong Kong stocks"""
    # ... API call logic
    return f"{stock_code} current price HK$128.50, up 1.2%"

7. LangGraph: Stateful Workflows

When Do You Need LangGraph?

A LangChain Agent is a simple loop: LLM → tool → LLM → tool → answer.

But real-world business requires more complex workflows:

RequirementLangChain AgentLangGraph
Simple tool-calling loop✅✅
Conditional branching (if A, do X; otherwise, do Y)❌✅
Parallel execution of multiple tasks❌✅
Pause for human approval❌✅
Resume after interruption❌✅
Persist state❌✅

LangGraph Core Concepts

┌────────────────────────────────────────┐
│           LangGraph Core Concepts      │
├────────────────────────────────────────┤
│                                        │
│  State ──── Shared state (all nodes RW)│
│  Node ───── Function that runs logic   │
│  Edge ───── Connection between nodes   │
│  Conditional Edge ── Conditional route │
│  Checkpointer ──── State persistence   │
│                                        │
└────────────────────────────────────────┘

Hands-On: Workflow with Human Approval

from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.memory import MemorySaver
from typing import TypedDict, Annotated
from langchain_core.messages import HumanMessage, AIMessage
import operator

# 1. Define state
class AgentState(TypedDict):
    messages: Annotated[list, operator.add]
    approved: bool

# 2. Define nodes
def agent_node(state: AgentState):
    """LLM decides the next step"""
    from langchain_openai import ChatOpenAI
    model = ChatOpenAI(model="gpt-4o")
    response = model.invoke(state["messages"])
    return {"messages": [response]}

def tool_node(state: AgentState):
    """Execute tool"""
    # ... tool execution logic
    return {"messages": [HumanMessage(content="Tool execution result: ...")]}

def human_approval_node(state: AgentState):
    """Wait for human approval"""
    # In a real application, it will pause and wait for user confirmation
    return {"approved": True}

# 3. Define routing logic
def should_continue(state: AgentState):
    last_message = state["messages"][-1]
    if hasattr(last_message, "tool_calls") and last_message.tool_calls:
        return "human_approval"
    return END

# 4. Build graph
workflow = StateGraph(AgentState)

workflow.add_node("agent", agent_node)
workflow.add_node("tools", tool_node)
workflow.add_node("human_approval", human_approval_node)

workflow.add_edge(START, "agent")
workflow.add_conditional_edges("agent", should_continue, {
    "human_approval": "human_approval",
    END: END
})
workflow.add_edge("human_approval", "tools")
workflow.add_edge("tools", "agent")

# 5. Compile (add Checkpointer)
checkpointer = MemorySaver()
app = workflow.compile(
    checkpointer=checkpointer,
    interrupt_before=["human_approval"]  # Pause before approval
)

# 6. Run
config = {"configurable": {"thread_id": "user-123"}}
result = app.invoke(
    {"messages": [HumanMessage(content="Help me check Tencent's latest stock price")]},
    config=config
)

LangGraph's Five Major Workflow Patterns

PatternDescriptionUse Cases
Prompt ChainingSequential execution, where the output of one step becomes the input of the next stepTranslation → Summarization → Sending
ParallelizationExecute multiple nodes in parallel and merge the resultsSearch multiple data sources simultaneously
RoutingRoute to different processing paths based on the inputCustomer complaints vs. product inquiries
Orchestrator-WorkerMain Agent assigns tasks to sub-AgentsComplex research tasks
Evaluator-OptimizerGenerate → Evaluate → Optimize loopCode generation + testing

Checkpointer: State Persistence

# Development phase: in-memory storage
from langgraph.checkpoint.memory import MemorySaver
checkpointer = MemorySaver()

# Testing phase: SQLite
from langgraph.checkpoint.sqlite import SqliteSaver
checkpointer = SqliteSaver.from_conn_string("checkpoints.db")

# Production phase: PostgreSQL
from langgraph.checkpoint.postgres import PostgresSaver
checkpointer = PostgresSaver.from_conn_string("postgresql://...")

8. LangSmith: Debugging and Monitoring

Why Do We Need LangSmith?

When your Agent takes 10 steps before producing an answer, how do you know which step went wrong? LangSmith helps you:

  • Trace: input/output/latency for each step
  • Debug: visualize the Agent's decision-making process
  • Evaluate: batch test Agent quality
  • Monitor: real-time alerts in production environments

Setting Up LangSmith

# 1. Register https://smith.langchain.com
# 2. Set environment variables
export LANGSMITH_TRACING=true
export LANGSMITH_API_KEY=lsv2_pt_xxxxxxxx
# No code changes needed at all! LangSmith automatic tracing
from langchain_openai import ChatOpenAI

model = ChatOpenAI(model="gpt-4o")
response = model.invoke("Hello")
# This call has already been automatically logged to LangSmith ✅

LangSmith UI Features

Trace View:
├── Agent Call (total time 3.2s)
│   ├── LLM Call #1 (tool selection) ── 0.8s
│   ├── Tool: search_stock (API call) ── 1.5s
│   ├── LLM Call #2 (process result) ── 0.6s
│   └── Tool: calculate (calculation) ── 0.3s
└── Final Answer

9. Ecosystem Overview

LangChain Product Family

┌─────────────────────────────────────────────────────────────┐
│                    LangChain Ecosystem                        │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────────────┐ │
│  │  LangChain   │  │  LangGraph  │  │   Deep Agents SDK   │ │
│  │  (High-level framework)   │  │  (Low-level orchestration)  │  │   (Full-featured Agent)    │ │
│  │             │  │             │  │                     │ │
│  │ create_agent│  │ StateGraph  │  │ Built-in planning + sub-Agent    │ │
│  │ LCEL Chain  │  │ Checkpoint  │  │ +File System+Memory      │ │
│  │ RAG Components    │  │ Human-in-   │  │                     │ │
│  │             │  │ the-loop    │  │                     │ │
│  └─────────────┘  └─────────────┘  └─────────────────────┘ │
│         │                 │                    │            │
│         └─────────────────┼────────────────────┘            │
│                           │                                 │
│                    ┌──────┴──────┐                          │
│                    │  LangSmith  │                          │
│                    │  (Debug Monitoring)  │                          │
│                    │             │                          │
│                    │ Trace       │                          │
│                    │ Evaluate    │                          │
│                    │ Monitor     │                          │
│                    └─────────────┘                          │
│                                                             │
│                    ┌─────────────┐                          │
│                    │  LangServe  │                          │
│                    │  (API deployment)  │                          │
│                    └─────────────┘                          │
│                                                             │
└─────────────────────────────────────────────────────────────┘

Selection Guide

Your RequirementRecommended Product
Quickly build a simple AgentLangChain create_agent
Need RAG document Q&ALangChain RAG components
Complex workflows (branching/loops/parallelism)LangGraph
Need human approval workflowsLangGraph + Checkpointer
Full-featured Agent (planning + sub-Agents)Deep Agents SDK
Debugging and monitoringLangSmith
Deploy as REST APILangServe

10. Production Deployment Best Practices

Architecture Recommendations

┌─────────────────────────────────────────────┐
│              Production Environment Architecture                      │
├─────────────────────────────────────────────┤
│                                             │
│  Frontend (React/Next.js)                   │
│       │                                     │
│       ▼                                     │
│  LangServe (FastAPI)                        │
│       │                                     │
│       ▼                                     │
│  LangGraph Agent                            │
│       │                                     │
│       ├── LLM (GPT-4o / Claude)            │
│       ├── Vector DB (Pinecone / Weaviate)   │
│       ├── Checkpointer (PostgreSQL)         │
│       └── Tools (APIs / DBs)               │
│                                             │
│  LangSmith (Monitoring + Alerts)                     │
│                                             │
└─────────────────────────────────────────────┘

Performance Optimization Checklist

Optimization ItemApproachEffect
Model SelectionUse gpt-4o-mini for simple tasks, gpt-4o for complex tasksReduce cost by 90%
Vector Retrievalchunk_size=500, k=3-5Balance accuracy and speed
StreamingUse .stream() instead of .invoke()Greatly improves user experience
CachingCache answers to identical questionsReduce LLM calls
ParallelismExecute multiple independent retrievals in parallelReduce latency by 50%
RetryAdd retry logic to LLM callsImprove stability

Security Checklist

# ✅ Never hardcode API Key
# ✅ Use environment variables or secret manager
# ✅ Limit the scope of tools available to the Agent
# ✅ Sanitize user input
# ✅ Set a token usage limit
# ✅ Log all Agent operations (LangSmith)
# ✅ Add human approval for sensitive operations

# ❌ Do not let the Agent directly execute arbitrary SQL
# ❌ Do not let the Agent access unnecessary tools
# ❌ Do not trust LLM output (must validate)

Cost Estimation

ScenarioModelCost per CallMonthly Cost (1000/day)
Simple Q&Agpt-4o-mini~$0.001~$30
RAG Q&Agpt-4o~$0.01~$300
Complex Agent (5 steps)gpt-4o~$0.05~$1,500
Hybrid Strategymini + 4o~$0.005~$150

💡 Recommendation: Use the mini model for 80% of requests, and route only complex tasks to gpt-4o.


11. LangChain vs. Competitor Comparison

FeatureLangChainLlamaIndexCrewAIAutoGenPydantic AI
PositioningGeneral-purpose LLM frameworkData retrievalMulti-agentMulti-agent conversationType safety
RAG✅ Strong✅ Best⚠️ Moderate⚠️ Moderate⚠️ Basic
Agent✅ Strong⚠️ Moderate✅ Strong✅ Strong⚠️ Basic
Workflow orchestration✅ LangGraph❌⚠️ Linear⚠️ Conversational❌
Model support80+50+30+20+10+
Learning curveMediumMediumLowMediumLow
Production-ready✅✅⚠️⚠️⚠️
Community activity⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐

Selection Recommendations

  • General-purpose LLM applications → LangChain
  • Pure RAG / knowledge base → LlamaIndex (more focused)
  • Multi-agent collaboration → CrewAI (simplest) or LangGraph (most flexible)
  • Need type safety → Pydantic AI
  • Rapid prototyping → CrewAI or LangChain

12. Frequently Asked Questions (FAQ)

Q: Is LangChain too heavy? I don't want to use it for simple applications?

A: If you are only making a simple single API call, using the official SDK directly is enough. LangChain's value lies in multi-step Chains, RAG, Agents, and model switching. If you need these, LangChain saves you a significant amount of development time.

Q: What is the difference between LCEL and the old Chain?

A: The old LLMChain / SequentialChain are deprecated. LCEL uses the | pipe syntax, which is more intuitive and supports streaming, async, and batch. New projects should use only LCEL.

Q: Does LangChain support local models?

A: Yes. Use langchain-ollama to connect to local Ollama models:

from langchain_ollama import ChatOllama
model = ChatOllama(model="llama3")

Q: How should I handle Agent hallucinations?

A: Three strategies:

  1. RAG: Force the Agent to answer based on retrieved documents
  2. Guardrails: Use middleware to check outputs
  3. LangSmith: Monitor abnormal outputs

Q: LangChain vs. using the OpenAI API directly?

A: If you only need single-turn Q&A, use the API directly. If you need RAG / Agent / multi-step / model switching / debugging and tracing, LangChain saves you hundreds of lines of code.


Summary: Learning Roadmap

Week 1: Fundamentals
├── Install LangChain
├── Write the first LCEL Chain
└── Understand Prompt Template + Output Parser

Week 2: RAG
├── Document loading + splitting
├── Vector database (FAISS / Chroma)
└── Build RAG Chain

Week 3: Agent
├── Define custom Tool
├── Build Agent with create_agent
└── Integrate LangSmith for debugging

Week 4: Advanced
├── LangGraph workflow
├── Checkpointer persistence
└── Production deployment

References


This article was written in June 2026, based on LangChain v1.0+ / LangGraph v1.2.0. The framework updates quickly, so it is recommended to check the official documentation regularly.