LangChain与DeepSeek大模型实战:手把手教你打造智能问答Agent
1. 为什么选择LangChain和DeepSeek构建智能问答Agent
如果你正在寻找一个既强大又灵活的AI开发框架来构建智能问答系统,LangChain绝对是当前最热门的选择。作为一个专门为大语言模型应用设计的开源框架,LangChain提供了模块化的组件和丰富的工具集成,让开发者能够快速搭建功能完善的AI应用。
而DeepSeek作为国产大模型中的佼佼者,凭借其中英文双语支持、128k超长上下文处理能力和实时知识更新等优势,成为构建智能问答系统的理想选择。我在实际项目中测试过多个大模型,DeepSeek在中文理解和生成任务上的表现确实令人印象深刻,特别是对于需要处理复杂上下文的企业级应用场景。
LangChain与DeepSeek的结合,就像给一辆高性能跑车配备了顶级导航系统——LangChain提供了完善的开发框架和工具链,而DeepSeek则提供了强大的语言理解和生成能力。这种组合让开发者能够专注于业务逻辑的实现,而不必在底层技术上花费过多精力。
2. 环境准备与基础配置
2.1 安装必要依赖
在开始构建智能问答Agent之前,我们需要先搭建好开发环境。我推荐使用Python 3.10或更高版本,因为这个版本在性能和稳定性方面都有不错的表现。
首先创建一个干净的虚拟环境是个好习惯:
python -m venv agent-env
source agent-env/bin/activate # Linux/Mac
agent-env\Scripts\activate # Windows
然后安装核心依赖包:
pip install langchain langchain-core langchain-community
pip install langchain-deepseek python-dotenv
这里我特意选择了python-dotenv包,因为它能帮助我们更安全地管理API密钥等敏感信息。在实际项目中,直接硬编码API密钥是非常危险的做法,我曾经因为疏忽导致密钥泄露,不得不重新生成,给项目带来了不必要的麻烦。
2.2 配置DeepSeek API密钥
获取到DeepSeek API密钥后,我们需要将其安全地存储在环境变量中。创建一个.env文件:
touch .env
然后在.env文件中添加你的API密钥:
DEEPSEEK_API_KEY=你的API密钥
记得将.env文件添加到.gitignore中,避免意外提交到版本控制系统:
echo ".env" >> .gitignore
在Python代码中,我们可以这样加载环境变量:
import os
from dotenv import load_dotenv
load_dotenv(override=True)
DEEPSEEK_API_KEY = os.getenv("DEEPSEEK_API_KEY")
3. 构建基础问答Agent
3.1 初始化DeepSeek聊天模型
有了环境配置,我们就可以开始构建第一个简单的问答Agent了。首先初始化DeepSeek聊天模型:
from langchain.chat_models import init_chat_model
from langchain_deepseek import ChatDeepSeek
# 使用init_chat_model初始化
model = init_chat_model(
"deepseek:deepseek-chat",
temperature=0.5,
timeout=10,
max_tokens=1000
)
# 或者直接使用ChatDeepSeek类
model = ChatDeepSeek(
model="deepseek-chat",
temperature=0.5,
timeout=10,
max_tokens=1000
)
这里的temperature参数控制生成文本的随机性,值越高输出越有创造性,值越低输出越确定。对于问答系统,我通常设置为0.5左右,在准确性和创造性之间取得平衡。
3.2 创建简单问答链
现在我们可以创建一个最基本的问答链:
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
prompt = ChatPromptTemplate.from_messages([
("system", "你是一个知识渊博的助手,能回答各种问题。"),
("human", "{input}")
])
chain = prompt | model | StrOutputParser()
response = chain.invoke({"input": "量子计算的基本原理是什么?"})
print(response)
这个简单的例子已经能够回答各种知识性问题。我在测试时发现,DeepSeek对于科技类问题的回答尤其准确,能够提供相当专业的解释。
3.3 添加对话历史记忆
真正的对话系统需要记住之前的对话内容。LangChain提供了多种记忆机制,最简单的是ConversationBufferMemory:
from langchain.memory import ConversationBufferMemory
memory = ConversationBufferMemory(
memory_key="history",
return_messages=True
)
prompt = ChatPromptTemplate.from_messages([
("system", "你是一个专业的问答助手,回答要简洁准确。"),
MessagesPlaceholder(variable_name="history"),
("human", "{input}")
])
conversation_chain = (
RunnablePassthrough.assign(
history=RunnableLambda(memory.load_memory_variables)
)
| prompt
| model
| StrOutputParser()
)
# 测试对话
response = conversation_chain.invoke(
{"input": "什么是神经网络?"},
config={"callbacks": [memory]}
)
print(response)
response = conversation_chain.invoke(
{"input": "能再简单点解释吗?"},
config={"callbacks": [memory]}
)
print(response)
这样,Agent就能记住之前的对话内容,实现连贯的多轮对话。在实际应用中,我发现这种记忆机制对于构建自然流畅的对话体验至关重要。
4. 增强问答Agent的功能
4.1 添加工具调用能力
真正的智能Agent不仅能回答问题,还能执行任务。我们可以通过添加工具来扩展Agent的能力:
from langchain.agents import tool
@tool
def get_weather(city: str) -> str:
"""获取指定城市的天气信息"""
# 这里可以接入真实天气API
return f"{city}当前天气:25℃,晴"
tools = [get_weather]
from langchain.agents import create_tool_calling_agent
agent_prompt = ChatPromptTemplate.from_messages([
("system", """你是一个全能助手,可以回答问题和使用工具。
当用户询问天气时,必须使用get_weather工具。
其他问题请直接回答。"""),
MessagesPlaceholder("chat_history"),
("human", "{input}"),
MessagesPlaceholder("agent_scratchpad")
])
agent = create_tool_calling_agent(model, tools, agent_prompt)
这个Agent现在既能回答问题,又能查询天气。我在一个客户项目中实现了类似的工具调用功能,大大提升了产品的实用性。
4.2 实现结构化输出
对于企业级应用,我们往往需要更结构化的输出。LangChain支持定义响应格式:
from dataclasses import dataclass
@dataclass
class QAResponse:
"""问答响应结构"""
answer: str
confidence: float
sources: list[str] | None = None
structured_chain = (
prompt
| model.with_structured_output(QAResponse)
)
response = structured_chain.invoke({"input": "解释一下区块链技术"})
print(f"回答: {response.answer}")
print(f"置信度: {response.confidence}")
if response.sources:
print(f"参考来源: {', '.join(response.sources)}")
这种结构化输出特别适合需要进一步处理AI响应的场景,比如在企业知识库系统中。
4.3 添加检索增强生成(RAG)功能
要让Agent回答特定领域的问题,我们可以实现检索增强生成:
from langchain_community.document_loaders import WebBaseLoader
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_community.vectorstores import FAISS
from langchain_deepseek import DeepSeekEmbeddings
# 加载文档
loader = WebBaseLoader("https://example.com/your-knowledge-base")
docs = loader.load()
# 分割文档
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
splits = text_splitter.split_documents(docs)
# 创建向量存储
embeddings = DeepSeekEmbeddings()
vectorstore = FAISS.from_documents(splits, embeddings)
# 创建检索器
retriever = vectorstore.as_retriever()
# 创建RAG链
from langchain_core.runnables import RunnablePassthrough
rag_prompt = ChatPromptTemplate.from_template("""
根据以下上下文回答问题。如果不知道就说不知道。
上下文:
{context}
问题: {input}
""")
rag_chain = (
{"context": retriever, "input": RunnablePassthrough()}
| rag_prompt
| model
| StrOutputParser()
)
response = rag_chain.invoke("你们公司的退货政策是什么?")
print(response)
在实际项目中,RAG功能可以显著提升Agent在特定领域的回答准确性。我曾经用这种方法为一个电商客户构建了客服系统,准确率提升了40%以上。
5. 部署与优化
5.1 使用Gradio创建Web界面
为了让非技术人员也能使用我们的Agent,可以用Gradio快速构建一个Web界面:
import gradio as gr
def respond(message, history):
response = conversation_chain.invoke(
{"input": message, "history": history}
)
return response
demo = gr.ChatInterface(
fn=respond,
title="DeepSeek智能问答助手",
description="体验AI助手的强大能力"
)
if __name__ == "__main__":
demo.launch()
这个简单的界面已经包含了聊天历史、输入框和发送按钮,非常适合快速演示和内部测试。
5.2 性能优化技巧
在生产环境中,我们还需要考虑性能优化:
from langchain.cache import InMemoryCache
from langchain.globals import set_llm_cache
# 启用缓存
set_llm_cache(InMemoryCache())
# 使用流式响应提升用户体验
for chunk in chain.stream({"input": "请解释机器学习"}):
print(chunk, end="", flush=True)
缓存可以显著减少重复查询的响应时间,而流式响应则能改善用户体验,特别是在生成长文本时。
5.3 安全防护
最后,别忘了添加基本的安全防护:
from langchain_community.chat_models import SafetySettings
safety_config = SafetySettings(
hate_speech_filter=True,
self_harm_filter=True
)
model = ChatDeepSeek(
model="deepseek-chat",
safety_settings=safety_config
)
这可以过滤掉不当内容,特别是在面向公众的应用中非常重要。
更多推荐


所有评论(0)