Building agents with LangChain
Building agents with LangChain
LangChain is a framework for building LLM applications, upgrading model calls into composable, controllable, and scalable application systems.
LangChain doesn't solve how to call the model, but rather:
- How to organize multi-step reasoning
- How to integrate external data
- How tools can be safely called by the model
- How context can be managed long-term
Open source address:https://github.com/langchain-ai/langchain.
LangChain tutorial:https://www.runoob.com/langchain/langchain-tutorial.html

Imagine you are building an intelligent robot assistant that needs to understand your questions, find information from various sources, perform logical reasoning, and finally answer you in natural language. Using a language model like GPT alone is like giving the robot a smart brain, but it lacks hands and eyes—it doesn't know how to retrieve external data or how to execute specific tasks.
LangChainis such a framework that acts as a connector and coordinator.
LangChaincleverly connects powerful language models (such as GPT-4, DeepSeek) with external data sources, computational tools, and memory systems to build powerful, practical AI applications.
Simply put, the core value of LangChain lies in:Making language models useful, solving several key limitations of large language models (LLMs):
- Knowledge timeliness: LLM training data has a cutoff date and cannot access the latest information.
- Domain specialization: General LLMs lack private knowledge of specific industries or companies.
- OperabilityLLMs themselves cannot perform actions such as computation, database querying, or API calling.
- Conversational coherenceIn multi-turn conversations, LLMs need to remember the previous chat history.
LangChain organizes these functionalities through a series of standardized Chains and Components, allowing developers to quickly build complex AI applications like assembling building blocks.
LangChain Module Overview:
- LLMs / ChatModelsModel interface
- Prompt TemplatesPrompt Structuring
- ChainsWorkflow Orchestration
- MemoryContext Management
- Retrievers / VectorStoresKnowledge Retrieval
- Agents & ToolsAutomatic decision making and execution
Environment preparation
Install using domestic mirror:
pip install langchain langchain-openai langchain-community python-dotenv -i https://mirrors.aliyun.com/pypi/simple/
If you use OpenAI, you can configure the environment variable:
Original prompt (Chinese, left untranslated)
export OPENAI_API_KEY=你的key
Then use the following code to test:
Instance
from
langchain_openai
import
ChatOpenAI
llm
=
ChatOpenAI
(
model
=
"gpt-4o-mini"
,
temperature
=
0
)
resp
=
llm.
invoke
(
"Explain what LangChain is in one sentence"
)
(
resp.
content
)
Domestically, we can use the DeepSeek large model for testing. If you don't have one yet, you need to go tohttps://platform.deepseek.com/api_keyscreate an API key first.
DeepSeek API documentation reference:https://api-docs.deepseek.com/zh-cn/.
If you need to uniformly manage multiple third-party models, you can choose to install LiteLLM as a model gateway:
pip install -U litellm
However, the example in this document directly usesChatOpenAICompatibilityopenai_api_baseConnect DeepSeek with parameters, no extra LiteLLM installation required.
Instance
import
os
from
langchain_openai
import
ChatOpenAI
It is recommended to place the API Key in an environment variable, or assign it directly here (do not hardcode in production environments).
os.environ["DEEPSEEK_API_KEY"] = "sk-your DeepSeek key"
Initialize the model
llm
=
ChatOpenAI
(
model
=
"deepseek-v4-pro"
,
DeepSeek V4 model name
openai_api_key
=
"sk-Your Key"
,
Enter your DeepSeek API Key
openai_api_base
=
"https://api.deepseek.com"
,
DeepSeek API address
temperature
=
0.7
,
max_tokens
=
1024
)
Test
response
=
llm.
invoke
(
"Hello, DeepSeek! Please give a brief self-introduction."
)
(
response.
content
)
Executing the above code will output the content:
Original prompt (Chinese, left untranslated)
你好!很高兴认识你!
I am DeepSeek, an AI assistant created by DeepSeek Company. My features include:
。。。
Build the LCEL chain (LangChain Expression Language)
Simply calling the model is not powerful enough; we need to build a standard processing workflow:
Prompt -> LLM -> OutputParser
The complete code is as follows:
Example
from
langchain_core.
prompts
import
ChatPromptTemplate
from
langchain_core.
output_parsers
import
StrOutputParser
from
langchain_openai
import
ChatOpenAI
1. Define Model
llm
=
ChatOpenAI
(
model
=
"deepseek-v4-pro"
,
openai_api_key
=
"YOUR_DEEPSEEK_API_KEY"
,
openai_api_base
=
"https://api.deepseek.com"
)
2. Define the prompt template (Prompt)
system: Set the AI's role
user: The user's specific input
prompt
=
ChatPromptTemplate.
from_messages
(
[
(
"system"
,
"You are a senior technical expert skilled at explaining complex technological concepts in plain, easy-to-understand language. Your explanation should include a vivid analogy."
)
,
(
"user"
,
"{concept}"
)
]
)
3. Define the Output Parser
Convert the model's Message object directly to a pure string
parser
=
StrOutputParser
(
)
4. Build Chain - Connect using the pipe operator |
Flow: Input dictionary -> Fill Prompt -> Send to LLM -> Parse output
chain
=
prompt | llm |
parser
5. Call Chain
concept_to_explain
=
"Quantum Entanglement"
(
f
"Explaining concept: {concept_to_explain}...\n"
)
result
=
chain.
invoke
(
{
"concept"
: concept_to_explain
}
)
(
"--- DeepSeek Answer ---"
)
(
result
)
Streaming
In practical applications (such as chatbots), we need to output text character by character, like ChatGPT, instead of waiting for the entire generation to finish before displaying it all at once.
LangChain supports this very simply, by using .stream() instead of .invoke():
Instance
from
langchain_core.
prompts
import
ChatPromptTemplate
from
langchain_core.
output_parsers
import
StrOutputParser
from
langchain_openai
import
ChatOpenAI
1. Define the model (Model)
llm
=
ChatOpenAI
(
model
=
"deepseek-v4-pro"
,
openai_api_key
=
"Your_DEEPSEEK_API_KEY"
,
openai_api_base
=
"https://api.deepseek.com"
)
2. Define the prompt template (Prompt)
system: Set the AI's role
user: User's specific input
prompt
=
ChatPromptTemplate.
from_messages
(
[
(
"system"
,
"You are a senior technical expert skilled at explaining complex technological concepts in plain, easy-to-understand language. Your explanation should include a vivid analogy."
)
,
(
"user"
,
"{concept}"
)
]
)
3. Define the Output Parser
Convert the model's Message object directly to a pure string
parser
=
StrOutputParser
(
)
4. Building the Chain - Connecting with the pipe operator |
Workflow: Input dictionary -> Fill Prompt -> Send to LLM -> Parse output
chain
=
prompt | llm |
parser
5. Call Chain
concept_to_explain
=
"Quantum Entanglement"
(
f
"Explaining concept: {concept_to_explain} (streaming output)...\n"
)
The chunk here is the segment generated each time
for
chunk
in
chain.
stream
(
{
"concept"
:
"Recurrent Neural Network"
}
)
:
(
chunk
,
end
=
""
,
flush
=
True
)
Code structure
Prompt
ChatPromptTemplateClearly distinguishsystem / user- Prompt isa structured input function, not a string
LLM
ChatOpenAIis just a unified interface- LangChain does not enhance model capabilities, only enhancescontrollability
OutputParser
- Model output is always
Message StrOutputParserisexplicit type casting- Without a Parser, the engineering is uncontrollable
Detailed explanation of core components
1. Models
LangChain provides a unified abstract interface, and we now mainly recommend usingChat ModelsBecause current models (such as DeepSeek, GPT-4) are mostly optimized for conversation.
- Chat Models: Input and output are structured messages.
SystemMessage: Setting the AI role.HumanMessage: Messages sent by the user.AIMessage: Messages returned by the AI.
2. Prompts
In the new version, it is recommended to useChatPromptTemplateto build conversational prompts, as it aligns better with the current mainstream LLM calling habits.
Original prompt (Chinese, left untranslated)
from langchain_core.prompts import ChatPromptTemplate
# Use from_messages to build structured templates
prompt_template = ChatPromptTemplate.from_messages([
("system", "你是一位专业的{role}。"),
("user", "{content}")
])
# Dynamically populate variables
prompt = prompt_template.invoke({"role": "美食评论家", "content": "评价一下这碗炸酱面"})
# Output: list containing SystemMessage and HumanMessage
3. Chains & LCEL
Important update: LLMChainHas been deprecated. Now useLCEL (pipe operator|)syntax. This method is more flexible and supports asynchronous and streaming output.
Original prompt (Chinese, left untranslated)
# 现代写法:Prompt | Model | OutputParser
from langchain_core.output_parsers import StrOutputParser
# The llm here is an instance of ChatOpenAI(model="deepseek-v4-pro")
chain = prompt_template | llm | StrOutputParser()
# 调用链
result = chain.invoke({"role": "导游", "content": "介绍一下故宫"})
print(result) # 直接输出字符串
4. Indexes & Retrieval
This isthe core of RAG (Retrieval-Augmented Generation). The new version emphasizes the process of converting documents into a "retriever."Process
- :(Load) ->
DocumentLoaders(Chunk) ->TextSplitter(Slice)Embeddings(Vectorization)VectorStore(Storage). - Retriever: It is no longer just database search; it is a component that can be integrated into a chain.
Original prompt (Chinese, left untranslated)
# 将向量库转为检索器
retriever = vectorstore.as_retriever()
# Reference in the new chain
# chain = {"context": retriever, "question": RunnablePassthrough()} | prompt | llm
Complete RAG practical example
Below, we will implement a complete RAG application. First, you need to install additional dependencies:
pip install langchain-community faiss-cpu sentence-transformers -i https://mirrors.aliyun.com/pypi/simple/
Instance
import
os
from
dotenv
import
load_dotenv
from
langchain_openai
import
ChatOpenAI
from
langchain_community.
embeddings
import
HuggingFaceEmbeddings
from
langchain_core.
prompts
import
ChatPromptTemplate
from
langchain_core.
output_parsers
import
StrOutputParser
from
langchain_core.
runnables
import
RunnablePassthrough
from
langchain_community.
vectorstores
import
FAISS
from
langchain.
text_splitter
import
RecursiveCharacterTextSplitter
Load environment variables
load_dotenv
(
)
Initialize model and Embedding
llm
=
ChatOpenAI
(
model
=
os
.
getenv
(
'DEEPSEEK_MODEL'
,
'deepseek-v4-pro'
)
,
openai_api_key
=
os
.
getenv
(
'DEEPSEEK_API_KEY'
)
,
openai_api_base
=
os
.
getenv
(
'DEEPSEEK_BASE_URL'
,
'https://api.deepseek.com'
)
,
)
Use a free local Embedding model (will download automatically on first run)
embeddings
=
HuggingFaceEmbeddings
(
model_name
=
"sentence-transformers/all-MiniLM-L6-v2"
)
--- 1. Prepare knowledge documents ---
In actual projects, these documents can be loaded from files, web pages, databases, etc.
documents
=
[
"LangChain is an open-source framework for building large language model applications, created by Harrison Chase in 2022."
,
"LangChain's core components include: model interfaces, prompt templates, chains, memory, retrieval, and agents."
,
"LCEL (LangChain Expression Language) is the next-generation chain building syntax for LangChain, which uses the pipe operator | to connect various components."
,
RAG (Retrieval-Augmented Generation) allows LLMs to answer questions outside of their training data by retrieving relevant documents before generation.
,
LangGraph is a new framework launched by the LangChain team, specifically designed for building complex, multi-step AI agent workflows.
,
LangSmith is LangChain's observability platform, used for debugging, testing, and monitoring LLM applications.
,
]
--- 2. Text Splitting ---
text_splitter
=
RecursiveCharacterTextSplitter
(
chunk_size
=
100
,
chunk_overlap
=
20
)
The document is relatively short here; in actual scenarios, long documents will be split into multiple chunks
texts
=
text_splitter.
create_documents
(
documents
)
--- 3. Vectorize and store in FAISS ---
vectorstore
=
FAISS.
from_documents
(
texts
,
embeddings
)
--- 4. Create Retriever ---
retriever
=
vectorstore.
as_retriever
(
search_kwargs
=
{
"k"
:
2
}
)
--- 5. Building the RAG Chain ---
rag_prompt
=
ChatPromptTemplate.
from_messages
(
[
(
"system"
,
"You are a knowledge assistant. Answer the question based on the retrieved context below. If the context does not have the answer, say that you do not know.\n\nContext: {context}"
)
,
(
"human"
,
"{question}"
)
]
)
Helper function: Concatenate retrieved documents into a string
def
format_docs
(
docs
)
:
return
"\n"
.
join
(
doc.
page_content
for
doc
in
docs
)
rag_chain
=
(
{
"context"
: retriever | format_docs
,
"question"
: RunnablePassthrough
(
)
}
| rag_prompt
| llm
| StrOutputParser
(
)
)
--- 6. Test RAG ---
question
=
"What are the core components of LangChain?"
(
f
"Question: {question}"
)
(
f
"Answer: {rag_chain.invoke(question)}"
)
RAG technical points explanation:
- FAISSIt is an open-source vector similarity search library from Facebook, suitable for local development and testing, with data stored in memory.
- Production environmentIt is recommended to use professional vector databases such as Pinecone, Milvus, Chroma, or Weaviate, which support persistence and distribution.
- Embedding model: This example uses HuggingFace's
all-MiniLM-L6-v2Model, the first run will automatically download (about 80MB) - If you have an OpenAI API Key, you can also use it
OpenAIEmbeddingsto get better Chinese results - For domestic Chinese scenarios, it is recommended to use
BAAI/bge-small-zh-v1.5Chinese Embedding models - chunk_sizeandchunk_overlapTuning is required based on the actual document characteristics; too large may lose precision, and too small may lose context
5. Memory
Important updates:TraditionalConversationBufferMemoryIt is difficult to integrate into complex LCEL chains. The latest recommendation is to useChatMessageHistoryin combination withRunnableWithMessageHistory.
- Core logic: Memory is no longer an attribute of a chain, but an independent message store
session_iddistinguishing between different users. - Persistence: Supports storage in Redis, PostgreSQL, or memory.
6. Agents
Agents are one of the most powerful features of LangChain. Unlike chains, agents canautonomously decide based on user inputwhich tools to call and in what order to execute, making them true "intelligent agents."
Agent's core loop: receive task -> think (select tool) -> execute tool -> observe results -> continue thinking or provide final answer.
Usage@toolA decorator can turn any Python function into a tool callable by an LLM. LangChain will automatically pass the function name and docstring to the model, letting the model know when and how to use this tool.
Below is a complete practical example of an Agent, including three tools: weather query, mathematical calculation, and knowledge search.
Instance
import
os
from
dotenv
import
load_dotenv
from
langchain_openai
import
ChatOpenAI
from
langchain_core.
prompts
import
ChatPromptTemplate
,
MessagesPlaceholder
from
langchain_core.
tools
import
tool
from
langchain.
agents
import
AgentExecutor
,
create_tool_calling_agent
Load environment variables
load_dotenv
(
)
Initialize DeepSeek model
llm
=
ChatOpenAI
(
model
=
os
.
getenv
(
'DEEPSEEK_MODEL'
,
'deepseek-v4-pro'
)
,
openai_api_key
=
os
.
getenv
(
'DEEPSEEK_API_KEY'
)
,
openai_api_base
=
os
.
getenv
(
'DEEPSEEK_BASE_URL'
,
'https://api.deepseek.com'
)
,
)
--- Define tools ---
Using the @tool decorator, LangChain will automatically inform the model of the function name and docstring
@
tool
def
get_current_weather
(
city:
str
)
str
:
"""Get the current weather information for a specified city. Use this tool when the user asks about the weather."""
In actual applications, this will call a real weather API
weather_data
=
{
"Beijing"
:
"Sunny, temperature 28°C, humidity 45%"
,
"Shanghai"
:
"Cloudy, temperature 25°C, humidity 70%"
,
"Shenzhen"
:
"Thunderstorm, temperature 30°C, humidity 85%"
,
}
return
weather_data.
get
(
city
,
f
"Sorry, there is no weather data for {city}"
)
@
tool
def
calculate
(
expression:
str
)
str
:
"""Calculates mathematical expressions. Use this tool when the user needs to perform mathematical calculations.
Supports basic arithmetic operations, such as '2 + 3 * 4'."""
import
ast
import
operator
Safe operator map
ops
=
{
ast.
Add
:
operator
.
add
,
ast.
Sub
:
operator
.
sub
,
ast.
Mult
:
operator
.
mul
,
ast.
Div
:
operator
.
truediv
,
ast.
Pow
:
operator
.
pow
,
ast.
USub
:
operator
.
neg
,
}
def
safe_eval
(
node
)
:
if
isinstance
(
node
,
ast.
Expression
)
:
return
safe_eval
(
node.
body
)
elif
isinstance
(
node
,
ast.
Constant
)
:
return
node.
value
elif
isinstance
(
node
,
ast.
BinOp
)
:
left
=
safe_eval
(
node.
left
)
right
=
safe_eval
(
node.
right
)
return
ops
[
type
(
node.
op
)
]
(
left
,
right
)
elif
isinstance
(
node
,
ast.
UnaryOp
)
:
operand
=
safe_eval
(
node.
operand
)
return
ops
[
type
(
node.
op
)
]
(
operand
)
else
:
raise
ValueError
(
f
"Unsupported expression type: {type(node)}"
)
try
:
tree
=
ast.
parse
(
expression
,
mode
=
'eval'
)
result
=
safe_eval
(
tree
)
return
f
"Calculation result: {expression} = {result}"
except
Exception
as
e:
return
f
"Calculation error: {e}"
@
tool
def
search_knowledge
(
query:
str
)
str
:
Search the knowledge base to obtain relevant information. Use this tool when the user asks factual questions.
In practical applications, this will connect to a vector database or search engine
knowledge
=
{
"LangChain"
:
"LangChain is an open-source framework for building LLM applications, supporting chained calls, memory management, and tool integration."
,
"Python"
:
"Python is a high-level programming language known for its simplicity and readability, widely used in fields such as AI and data science."
,
}
for
key
,
value
in
knowledge.
items
(
)
:
if
key.
lower
(
)
in
query.
lower
(
)
:
return
value
return
f
"No information found related to '{query}'"
--- Tool list assembly ---
tools
=
[
get_current_weather
,
calculate
,
search_knowledge
]
--- Prompt for creating an Agent ---
prompt
=
ChatPromptTemplate.
from_messages
(
[
(
"system"
,
"You are a powerful AI assistant that can use tools to help users. Based on the user's question, determine whether a tool needs to be used and select the most appropriate tool to get information."
)
,
(
"human"
,
"{input}"
)
,
MessagesPlaceholder
(
variable_name
=
"agent_scratchpad"
)
,
]
)
--- Create Agent ---
agent
=
create_tool_calling_agent
(
llm
,
tools
,
prompt
)
--- Create AgentExecutor ---
verbose=True can show the Agent's complete thought process
agent_executor
=
AgentExecutor
(
agent
=
agent
,
tools
=
tools
,
verbose
=
True
)
--- Test Agent ---
Test 1: Weather query
(
"="
50
)
response
=
agent_executor.
invoke
(
{
"input"
:
"What is the weather like in Beijing today?"
}
)
(
f
"\nFinal Answer: {response['output']}"
)
Test 2: Mathematical Calculation
(
"\n"
"="
50
)
response
=
agent_executor.
invoke
(
{
"input"
:
"Help me calculate what (15 * 37 + 228) / 3 equals"
}
)
(
f
"\nFinal Answer: {response['output']}"
)
Test 3: Comprehensive Question (Agent needs to decide which tool to use)
(
"\n"
"="
50
)
response
=
agent_executor.
invoke
(
{
"input"
:
"What is LangChain? Also, help me calculate 2 to the power of 10."
}
)
(
f
"\nFinal Answer: {response['output']}"
)
When you run the code above, you will see(the chain-of-thought output when verbose=True):
Original prompt (Chinese, left untranslated)
==================================================
> Entering new AgentExecutor chain...
Invoking: `get_current_weather` with `{'city': '北京'}`
晴天,气温 28°C,湿度 45%
根据查询结果,北京今天的天气是晴天,气温 28°C,湿度 45%。
> Finished chain.
最终回答: 北京今天天气晴朗,气温 28°C,湿度 45%,适合外出活动。
==================================================
> Entering new AgentExecutor chain...
Invoking: `calculate` with `{'expression': '(15 * 37 + 228) / 3'}`
计算结果:(15 * 37 + 228) / 3 = 261.0
> Finished chain.
最终回答: (15 * 37 + 228) / 3 的计算结果是 261.0
==================================================
> Entering new AgentExecutor chain...
Invoking: `search_knowledge` with `{'query': 'LangChain'}`
Invoking: `calculate` with `{'expression': '2 ** 10'}`
LangChain 是一个用于构建 LLM 应用的开源框架...
计算结果:2 ** 10 = 1024
> Finished chain.
最终回答: LangChain 是一个用于构建 LLM 应用的开源框架,支持链式调用、记忆管理和工具集成。另外,2 的 10 次方等于 1024。
Security Tip:
This example uses safe AST parsing instead of eval(). In real projects, never use eval() directly on user input, as this poses a severe remote code execution risk.
Understanding the Agent's "thinking process":
verbose=TrueLet's see the Agent's complete decision chain to facilitate debugging and understanding its behavior- The Agent will automatically determine which tools to call, without requiring manual specification of the calling order
- If the question does not require tools (such as simple chatting), the Agent will answer directly using its own knowledge
- For complex questions, the Agent may call tools multiple times, or even call multiple tools in parallel
Quick Start: Build your first LangChain application
Let's experience the convenience of LangChain through a simple example.
In actual development, we can store the API-related information in a file in the project root directory.envfor convenience.
Original prompt (Chinese, left untranslated)
# .env file content
DEEPSEEK_API_KEY=sk-xxx
DEEPSEEK_BASE_URL=https://api.deepseek.com
DEEPSEEK_MODEL=deepseek-v4-pro
When using ChatOpenAI with LangChain, it is recommended to configure openai_api_base as https://api.deepseek.com; no need to manually add /v1, as LangChain will automatically construct the path.
Example 1: Basic Q&A Chain
Instance
import
os
from
dotenv
import
load_dotenv
correct import path
from
langchain_core.
prompts
import
PromptTemplate
from
langchain_core.
output_parsers
import
StrOutputParser
from
langchain_openai
import
ChatOpenAI
Load environment variables
load_dotenv
(
)
llm
=
ChatOpenAI
(
model
=
os
.
getenv
(
'DEEPSEEK_MODEL'
)
,
openai_api_key
=
os
.
getenv
(
'DEEPSEEK_API_KEY'
)
,
openai_api_base
=
os
.
getenv
(
'DEEPSEEK_BASE_URL'
)
,
)
Create prompt template
template
=
"""
You are a friendly assistant.
Please answer the following question:
Question: {question}
Answer:
"""
prompt
=
PromptTemplate.
from_template
(
template
)
Create a chain using LCEL syntax (recommended way)
Structure: Prompt -> LLM -> Parse to string
chain
=
prompt | llm | StrOutputParser
(
)
Run chain
question
=
"What is LangChain? What are its main uses?"
response
=
chain.
invoke
(
{
"question"
: question
}
)
(
"Question:"
,
question
)
(
"-"
20
)
(
"Answer:"
,
response
)
Example 2: Conversation Chain with Memory
Let's create a simple chatbot that can remember the conversation history.
Instance
import
os
from
dotenv
import
load_dotenv
from
langchain_openai
import
ChatOpenAI
from
langchain_core.
prompts
import
ChatPromptTemplate
,
MessagesPlaceholder
from
langchain_community.
chat_message_histories
import
ChatMessageHistory
from
langchain_core.
chat_history
import
BaseChatMessageHistory
from
langchain_core.
runnables
.
history
import
RunnableWithMessageHistory
1. Load configuration
load_dotenv
(
)
2. Initialize DeepSeek model
llm
=
ChatOpenAI
(
model
=
os
.
getenv
(
'DEEPSEEK_MODEL'
,
'deepseek-v4-pro'
)
,
openai_api_key
=
os
.
getenv
(
'DEEPSEEK_API_KEY'
)
,
openai_api_base
=
os
.
getenv
(
'DEEPSEEK_BASE_URL'
,
'https://api.deepseek.com'
)
,
)
3. Define prompt template
MessagesPlaceholder will be filled with conversation history at runtime
prompt
=
ChatPromptTemplate.
from_messages
(
[
(
"system"
,
"You are a helpful AI assistant."
)
,
MessagesPlaceholder
(
variable_name
=
"history"
)
,
(
"human"
,
"{question}"
)
,
]
)
4. Build chain
chain
=
prompt | llm
5. Memory Management: Create a dictionary to store history for different users
store
=
{
}
def
get_session_history
(
session_id:
str
)
BaseChatMessageHistory:
if
session_id
not
in
store:
store
[
session_id
]
=
ChatMessageHistory
(
)
return
store
[
session_id
]
6. Wrap our chain with RunnableWithMessageHistory
This allows LangChain to automatically handle the reading and updating of history
with_message_history
=
RunnableWithMessageHistory
(
chain
,
get_session_history
,
input_messages_key
=
"question"
,
history_messages_key
=
"history"
,
)
7. Enter the conversation loop
(
"--- Entered DeepSeek chat mode (type 'exit' to quit) ---"
)
session_config
=
{
"configurable"
:
{
"session_id"
:
"user_001"
}
}
ID to distinguish different sessions
while
True
:
user_input
=
input
(
"You: "
)
if
user_input.
lower
(
)
in
[
"exit"
,
"quit"
,
"exit"
]
:
break
Call a chain with memory
response
=
with_message_history.
invoke
(
{
"question"
: user_input
}
,
config
=
session_config
)
(
f
"AI: {response.content}\n"
)
Running the above code, you will see:
Original prompt (Chinese, left untranslated)
--- 已进入 DeepSeek 聊天模式 (输入 'exit' 退出) ---
你: 你好
AI: 你好!很高兴见到你! 有什么我可以帮助你的吗?无论是回答问题、聊天,还是协助解决问题,我都很乐意为你提供帮助!
你: 我叫小明
AI: 你好,小明!很高兴认识你!
如果你有任何问题、想法,或者需要帮助的地方,随时告诉我哦~
你: 我叫什么记得吗?
AI: 当然记得!你刚刚告诉我你叫**小明**~
我会认真记住我们的对话内容,在之后的交流中尽量保持上下文连贯。不过如果对话过长或间隔太久,我可能需要你提醒一下哦~
有什么想聊的或需要帮助的吗?
Summary
This article introduces the core concepts and practical applications of the LangChain framework. LangChain allows developers to quickly build powerful AI applications through standardized components and chained calls.
The table below summarizes the core knowledge points covered in this article:
| Concept | Description | Key Code |
|---|---|---|
| LCEL Chain | Connect Prompt, Model, Parser with the pipe operator | | chain = prompt \| llm \| parser |
| Prompt Template | Structured Prompt, distinguishing system/user roles | ChatPromptTemplate.from_messages() |
| Streaming Output | Character-by-character output to enhance user experience | chain.stream() |
| Conversation memory | Managing multi-turn conversation history via session_id | RunnableWithMessageHistory |
| RAG retrieval augmentation | External knowledge integration to break through LLM knowledge boundaries | retriever \| format_docs |
| Agent | Autonomous tool invocation for core advanced functionality | create_tool_calling_agent() |