LangChain Basics: Core Components, Prompts, Chains, Memory, and Agents
This article introduces LangChain, an open‑source framework for building LLM applications, covering its modular design, supported models, core components such as Prompt templates, Chains, Memory, Agents, and practical Python code examples for each feature.
1. LangChain Overview
LangChain is an open‑source framework that helps developers build end‑to‑end applications with large language models (LLMs). Its main characteristics are modular design, multi‑model support (OpenAI, Anthropic, HuggingFace, etc.), rich tool integrations (vector databases, search engines, APIs), and flexible extensibility.
1.1 Core Components
Model I/O : manages model inputs and outputs.
Prompt : handles prompt template management.
Chain : enables sequential or parallel chain calls.
Memory : stores conversation history.
Agent : implements ReAct‑style reasoning and tool usage.
Tool : defines external utilities that agents can invoke.
Index : provides indexing and retrieval capabilities.
Callback : offers a callback mechanism for monitoring.
1.2 LangChain vs. LCEL (LangChain Expression Language)
LCEL introduces a runnable protocol, automatic parallel execution, built‑in error handling, and native streaming support, simplifying development compared with the older LangChain syntax that requires manual handling.
2. Prompt Templates
2.1 Basic Prompt
from langchain.prompts import PromptTemplate
template = PromptTemplate.from_template(
"请将以下文本翻译成{target_language}:{text}"
)
# 使用模板
result = template.invoke({
"target_language": "英语",
"text": "你好,世界"
})2.2 Few‑Shot Prompt
from langchain.prompts import FewShotPromptTemplate
from langchain.prompts.example_selector import SemanticSimilarityExampleSelector
examples = [
{"input": "happy", "output": "开心"},
{"input": "sad", "output": "悲伤"},
{"input": "angry", "output": "生气"}
]
example_selector = SemanticSimilarityExampleSelector.from_examples(
examples,
OpenAIEmbeddings(),
Chroma,
k=2
)
few_shot_prompt = FewShotPromptTemplate(
example_selector=example_selector,
example_prompt=PromptTemplate.from_template("输入: {input}
输出: {output}"),
prefix="请将英文单词翻译成中文:",
suffix="输入: {adjective}
输出:",
input_variables=["adjective"]
)2.3 Chat Prompt
from langchain.prompts import ChatPromptTemplate
chat_template = ChatPromptTemplate.from_messages([
("system", "你是一个专业的{profession}。"),
("human", "请问{question}"),
("ai", "{answer}"),
("human", "请再详细解释一下第{point}点")
])
chat_prompt = chat_template.invoke({
"profession": "软件架构师",
"question": "微服务架构的优势是什么",
"answer": "微服务架构的主要优势包括:1. 可独立部署...",
"point": "2"
})3. Chain Usage
3.1 LLMChain
from langchain.chains import LLMChain
from langchain_openai import ChatOpenAI
from langchain.prompts import PromptTemplate
llm = ChatOpenAI(model="gpt-4", temperature=0)
prompt = PromptTemplate.from_template("请用一句话解释{concept}:")
chain = LLMChain(llm=llm, prompt=prompt)
result = chain.invoke({"concept": "微服务架构"})3.2 SequentialChain
from langchain.chains import SequentialChain
# Translation chain
translation_chain = LLMChain(
llm=llm,
prompt=PromptTemplate.from_template("将以下中文翻译成英文:{text}"),
output_key="english_text"
)
# Summarization chain
summary_chain = LLMChain(
llm=llm,
prompt=PromptTemplate.from_template("用一句话总结以下英文文本:{english_text}"),
output_key="summary"
)
sequential_chain = SequentialChain(
chains=[translation_chain, summary_chain],
input_variables=["text"],
output_variables=["english_text", "summary"]
)
result = sequential_chain.invoke({"text": "微服务架构是一种软件设计方法"})3.3 RouterChain (example skeleton)
from langchain.chains.router import MultiPromptChain
from langchain.chains.router.llm_router import LLMRouterChain
from langchain.chains.router.prompt_selector import LLMPromptSelector
math_prompt = PromptTemplate.from_template("请解决以下数学问题:{question}")
history_prompt = PromptTemplate.from_template("请回答以下历史问题:{question}")
router_chain = LLMRouterChain.from_router(
llm,
LLMPromptSelector(),
destinations={"math": math_chain, "history": history_chain}
)3.4 LCEL Expression Chain (recommended)
from langchain.schema import StrOutputParser
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(model="gpt-4")
chain = (
PromptTemplate.from_template("请用一句话解释{topic}")
| llm
| StrOutputParser()
)
result = chain.invoke({"topic": "什么是Docker"})4. Memory Components
4.1 Basic Memory Types
ConversationBufferMemory – stores full short‑dialogue history.
ConversationSummaryMemory – automatically summarizes long dialogues.
ConversationBufferWindowMemory – keeps a sliding window of recent turns.
EntityMemory – remembers entity information.
KnowledgeGraphMemory – handles complex relational data.
4.2 ConversationSummaryMemory Example
from langchain.memory import ConversationSummaryMemory
from langchain.chat_models import ChatOpenAI
llm = ChatOpenAI(model="gpt-3.5-turbo")
memory = ConversationSummaryMemory(llm=llm)
for i in range(5):
memory.save_context(
{"input": f"这是第{i+1}轮对话"},
{"output": f"这是第{i+1}轮回复"}
)
history = memory.load_memory_variables({})4.3 Using Memory in a Chain
from langchain.chains import ConversationChain
conversation = ConversationChain(
llm=llm,
memory=ConversationBufferMemory(),
verbose=True
)
response = conversation.invoke({"input": "我叫张三"})
response = conversation.invoke({"input": "我叫什么名字?"})5. Agents
5.1 Agent Workflow
The agent receives user input, the LLM performs ReAct reasoning, selects an action, executes the corresponding tool, observes the result, and finally returns an answer to the user.
5.2 Common Agent Types
ZeroShotAgent – single‑step decision, suited for simple tasks.
ConversationalAgent – chat‑style interaction.
ReactAgent – reasoning‑action‑observation loop for tasks requiring inference.
SelfAskAgent – self‑questioning for multi‑hop QA.
OpenAI Functions Agent – leverages OpenAI function calling for structured outputs.
5.3 Defining Tools
from langchain.tools import tool
from langchain.tools import Tool
from langchain.utilities import SerpAPIWrapper
@tool
def get_weather(city: str) -> str:
"""获取指定城市的天气信息"""
return f"{city}今天天气晴朗,25度"
search = SerpAPIWrapper()
search_tool = Tool(
name="搜索",
func=search.run,
description="用于搜索互联网信息"
)
tools = [get_weather, search_tool]5.4 Creating an Agent
from langchain.agents import initialize_agent, AgentType
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(model="gpt-4", temperature=0)
agent = initialize_agent(
tools=tools,
llm=llm,
agent=AgentType.CHAT_CONVERSATIONAL_REACT_DESCRIPTION,
verbose=True
)
result = agent.invoke({"input": "北京今天天气怎么样?请顺便搜索一下北京有哪些好玩的景点。"})5.5 Custom Tool Example (SQL Database)
from langchain.tools import Tool
from langchain_community.utilities import SQLDatabase
db = SQLDatabase.from_uri("sqlite:///chinook.db")
def run_query(query: str) -> str:
"""执行 SQL 查询并返回结果"""
return db.run(query)
query_tool = Tool(
name="数据库查询",
func=run_query,
description="使用SQL查询数据库,输入应该是有效的SQL语句"
)
agent = initialize_agent(
tools=[query_tool],
llm=llm,
agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION
)6. Real‑World Applications
6.1 RAG Question‑Answering System
from langchain.chains import RetrievalQA
from langchain.vectorstores import Chroma
from langchain.embeddings import OpenAIEmbeddings
from langchain_openai import ChatOpenAI
vectorstore = Chroma.from_documents(documents=splits, embedding=OpenAIEmbeddings())
retriever = vectorstore.as_retriever(search_kwargs={"k": 3})
qa_chain = RetrievalQA.from_chain_type(
llm=ChatOpenAI(model="gpt-4"),
chain_type="stuff",
retriever=retriever,
return_source_documents=True
)
result = qa_chain.invoke({"query": "什么是微服务架构?"})6.2 Multi‑Step Task Execution
from langchain.schema import HumanMessage
from langchain.agents import AgentExecutor, OpenAI FunctionsAgent
from langchain.prompts import MessagesPlaceholder
prompt = OpenAI FunctionsAgent.create_prompt(
system_message="你是一个助手,可以帮助用户完成多种任务。",
extra_prompt_messages=[MessagesPlaceholder(variable_name="chat_history")]
)
agent = OpenAI FunctionsAgent(llm=llm, tools=tools, prompt=prompt)
agent_executor = AgentExecutor(
agent=agent,
tools=tools,
verbose=True,
memory=ConversationBufferMemory(memory_key="chat_history")
)
result = agent_executor.invoke({"input": "帮我查一下上海的天气,然后搜索附近有哪些餐厅"})6.3 Complex Chain Composition (Parallel LCEL)
from langchain.schema import StrOutputParser
from langchain.prompts import PromptTemplate
from langchain import Parallel
analyze_chain = (
PromptTemplate.from_template("分析以下文本的情感和主题:{text}")
| llm
| StrOutputParser()
)
translate_chain = (
PromptTemplate.from_template("将以下内容翻译成英文:{content}")
| llm
| StrOutputParser()
)
summarize_chain = (
PromptTemplate.from_template("用50字概括:{content}")
| llm
| StrOutputParser()
)
combined = (
{"analysis": analyze_chain, "translation": translate_chain}
| (lambda x: {"analysis": x["analysis"], "translation": x["translation"], "content": x["translation"]})
| summarize_chain
)Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Long Ge's Treasure Box
I'm Long Ge, and this is my treasure chest—packed with cutting‑edge tech insights, career‑advancement tips, and a touch of relaxation you crave. Open it daily for a new surprise.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
