Master LangChain’s Four Core Components in 5 Minutes – Stop Treating LLMs Like Simple APIs

This article introduces LangChain’s four core components—Model, Prompt, Chain, and Agent—explains their purposes, shows how to install and configure the library, demonstrates building pipelines with LCEL, and provides code examples for agents, parallel execution, and environment setup.

Tech Ocean
Tech Ocean
Tech Ocean
Master LangChain’s Four Core Components in 5 Minutes – Stop Treating LLMs Like Simple APIs
Confused by the four terms Model, Prompt, Chain, Agent on your first day learning LangChain? The article explains each concept and shows how to use them.

Four Core Concepts

Model : unified large‑model interface that wraps OpenAI, Claude, Ollama, etc. (analogy: database connection pool)

Prompt : template‑based prompt definition that supports reuse, composition, and dynamic variable injection. (analogy: SQL template)

Chain : assembles multiple steps—Model, Prompt, Tool, etc.—into a workflow pipeline. (analogy: production line)

Agent : model‑driven autonomous decision loop (think → act → observe → output). (analogy: intelligent robot)

Model: Unified Entry for All Large Models

LangChain provides two wrapper classes:

ChatModel : chat‑style interface where input and output are messages (e.g., GPT‑4.1, Claude‑sonnet‑4‑6).

LLM : text‑completion interface where input and output are plain strings (e.g., GPT‑4.1‑mini, Claude native).

# Install version‑locked dependencies
# pip install langchain==1.2.15 langchain-core==1.3.0 langchain-openai==1.1.14

from langchain_openai import ChatOpenAI

# Switch model with a single line
llm = ChatOpenAI(model="Pro/MiniMaxAI/MiniMax-M2.5", temperature=0.7)
response = llm.invoke("用一句话解释量子计算")
print(response.content)

Reasons for a unified wrapper:

Swap underlying models without changing business code.

Consistent retry, timeout, and rate‑limit handling.

Uniform output format regardless of provider.

Prompt: Template‑Based Flexibility

Prompt templates eliminate the need to modify code for every requirement change.

from langchain_core.prompts import ChatPromptTemplate

# Define a template with {} placeholders
prompt = ChatPromptTemplate.from_messages([
    ("system", "你是一个专业的{language}翻译助手"),
    ("human", "把以下句子翻译成{language}:{sentence}")
])

# Chain the prompt with the model using LCEL syntax
chain = prompt | llm
result = chain.invoke({
    "language": "日语",
    "sentence": "大模型正在改变编程方式"
})
print(result.content)

Advantages of using templates:

Prompt definitions can be managed and versioned independently.

The same code supports multiple languages or scenarios.

Facilitates A/B testing of different prompt formulations.

Chain: Stitching Multiple Steps

A chain composes Prompt, Model, and an output parser into a single runnable pipeline.

from langchain_core.output_parsers import StrOutputParser

# Three‑step chain: Prompt → Model → OutputParser
chain = prompt | llm | StrOutputParser()

# Execute the whole workflow in one call
result = chain.invoke({
    "language": "法语",
    "sentence": "LangChain makes LLM apps easy"
})

Common LCEL composition patterns:

Basic chain: prompt | llm | parser RAG (retrieval‑augmented generation): retriever | prompt | llm With memory: combine a memory component with an LCEL chain.

Agent: Model‑Driven Autonomous Decision‑Making

Agents let the model decide when to invoke tools, process observations, and produce final output.

from langchain_core.tools import tool
from langchain_openai import ChatOpenAI
from langchain.agents import create_agent

@tool
def calculator(expression: str) -> str:
    """Execute a mathematical calculation"""
    return str(eval(expression))

model = ChatOpenAI(model="Pro/MiniMaxAI/MiniMax-M2.5")
agent = create_agent(
    model,
    tools=[calculator],
    system_prompt="你是一个计算助手,可以调用计算器完成数学运算。"
)

# Let the AI decide when to call the calculator
result = agent.invoke({
    "messages": [{"role": "user", "content": "计算 (35 + 17) * 2 的值"}]
})
print(result["messages"][-1].content)

LCEL: Pipe Operator for Linking Runnables

LCEL (LangChain Expression Language) uses the | operator as syntactic sugar for sequential .invoke() calls.

# Equivalent to chaining .invoke() calls
chain = prompt | llm | StrOutputParser()
# Under the hood: prompt.invoke(input) → llm.invoke(...) → StrOutputParser.invoke(...)

LCEL advantages:

Declarative style; code serves as documentation.

Lazy evaluation; execution occurs on demand.

Unified interface supporting invoke, batch, stream, and async.

Parallel execution via chain1 + chain2, which runs both branches concurrently and merges results.

from langchain_core.runnables import RunnableParallel

parallel_chain = RunnableParallel(
    summary=summary_chain,
    translation=translation_chain
)
result = parallel_chain.invoke({"text": "LangChain is powerful"})
# Result example: {"summary": "...", "translation": "..."}

Environment Setup

# Core packages (required)
pip install langchain==1.2.15 langchain-core==1.3.0

# OpenAI integration
pip install langchain-openai==1.1.14

# Community integrations (tools, loaders, vector stores)
pip install langchain-community==0.4.1

# Vector database (used later)
pip install langchain-chroma==1.1.0 faiss-cpu

# Optional local model support
pip install langchain-ollama

Verify installation:

import langchain
print(f"LangChain version: {langchain.__version__}")
# Expected output: LangChain version: 1.2.15

Domestic Model Configuration (Optional)

When using domestic APIs such as SiliconFlow, configure environment variables:

import os

# Method 1: environment variables (recommended)
os.environ["OPENAI_API_KEY"] = "your-api-key"
os.environ["OPENAI_BASE_URL"] = "https://api.siliconflow.cn/v1"
os.environ["OPENAI_MODEL"] = "Pro/MiniMaxAI/MiniMax-M2.5"
llm = ChatOpenAI()  # Reads env vars automatically

# Method 2: pass parameters directly
llm = ChatOpenAI(
    model="Pro/MiniMaxAI/MiniMax-M2.5",
    base_url="https://api.siliconflow.cn/v1",
    api_key="your-api-key"
)

Embedding configuration example:

embedding = OpenAIEmbeddings(
    model="BAAI/bge-m3",
    base_url="https://api.siliconflow.cn/v1",
    api_key="your-api-key"
)

Day 1 Recap

Model : unified interface; swapping models requires no code changes.

Prompt : template‑based, reusable, supports dynamic variables.

Chain : combines multiple components into a pipeline.

Agent : autonomous decision loop (think → act → observe → output).

LCEL : pipe operator ( |) for linking runnables.

Related Links

LangChain official docs: https://python.langchain.com/docs/
LCEL tutorial: https://python.langchain.com/docs/concepts/lcel/
LangChain GitHub: https://github.com/langchain-ai/langchain
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonLLMPrompt EngineeringLangChainAgentLCELChain
Tech Ocean
Written by

Tech Ocean

Focused on AI programming, sharing ready-to-use development efficiency solutions.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.