admin管理员组文章数量:1444822
基于LangChain和DeepSeek的Agent开发指南
在人工智能技术飞速发展的今天,开发专属的AI对话机器人不再是十分困难的事情。本文将以DeepSeek最新大语言模型为基础,结合LangChain框架,手把手教你构建一个具备完整对话能力的AI Agent。无需机器学习背景,只需基本Python知识即可完成!
一、环境准备与工具介绍
1.1 必要环境
- Python 3.8+(推荐3.10)
- pip 23.0+
- 开发工具:VSCode/PyCharm/Jupyter
1.2 核心工具介绍
LangChain:当前最流行的AI应用开发框架,提供模块化组件:
- 模型抽象层
- 记忆管理
- 工具调用
- 流程编排
DeepSeek:国产顶尖大语言模型,具有以下优势:
- 中英文双语支持
- 128k超长上下文
- 实时知识更新
- API调用便捷
二、项目搭建全流程
2.1 环境配置
代码语言:bash复制# 创建虚拟环境
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 deepseek-api python-dotenv
2.2 获取DeepSeek API密钥
- 访问DeepSeek官网DEEPSEEK_API_KEY=sk-your-key-here
- 注册/登录后进入控制台
- 创建新应用并获取API Key
- 保存到
.env
文件:
三、基础对话机器人开发
3.1 初始化对话链
代码语言:python代码运行次数:0运行复制from langchain_community.chat_models import ChatDeepSeek
from langchain_core.prompts import ChatPromptTemplate
from dotenv import load_dotenv
load_dotenv()
# 初始化模型
model = ChatDeepSeek(
model_name="deepseek-chat",
temperature=0.5,
max_tokens=1024
)
# 创建提示模板
prompt = ChatPromptTemplate.from_messages([
("system", "你是一个乐于助人的AI助手"),
("human", "{input}")
])
# 构建基础链
chain = prompt | model
3.2 进行首次对话
代码语言:python代码运行次数:0运行复制response = chain.invoke({
"input": "请用Python写一个快速排序算法"
})
print(response.content)
四、添加记忆功能
4.1 实现对话历史管理
代码语言:python代码运行次数:0运行复制from langchain.memory import ConversationBufferMemory
memory = ConversationBufferMemory(
memory_key="history",
return_messages=True
)
# 更新提示模板
prompt = ChatPromptTemplate.from_messages([
("system", """你是一个专业的技术顾问,具有以下特点:
1. 回答简洁明确
2. 会主动追问细节
3. 使用Markdown格式"""),
MessagesPlaceholder(variable_name="history"),
("human", "{input}")
])
# 构建带记忆的链
conversation_chain = (
RunnablePassthrough.assign(
history=RunnableLambda(memory.load_memory_variables)
)
| prompt
| model
)
4.2 持续对话示例
代码语言:python代码运行次数:0运行复制while True:
user_input = input("你:")
if user_input.lower() == 'exit':
break
response = conversation_chain.invoke(
{"input": user_input},
config={"callbacks": [memory]}
)
print(f"AI:{response.content}")
五、高级功能扩展
5.1 添加工具调用能力
代码语言:python代码运行次数:0运行复制from langchain.agents import tool
@tool
def get_weather(city: str):
"""获取指定城市的实时天气"""
# 这里可以接入真实天气API
return f"{city}当前天气:25℃,晴"
# 创建工具包
tools = [get_weather]
# 构建Agent
agent = create_tool_calling_agent(
model,
tools,
prompt
)
5.2 自定义提示模板
代码语言:python代码运行次数:0运行复制advanced_prompt = ChatPromptTemplate.from_messages([
("system", """你是一个全能助手,请遵守以下规则:
1. 当涉及天气查询时,必须使用工具
2. 技术问题回答需包含示例代码
3. 保持回答在3句话以内"""),
MessagesPlaceholder("history"),
("human", "{input}"),
MessagesPlaceholder("agent_scratchpad")
])
六、部署应用
6.1 使用Gradio创建Web界面
代码语言:python代码运行次数:0运行复制import gradio as gr
def chat(message, history):
response = agent.invoke({
"input": message,
"history": history
})
return response.content
demo = gr.ChatInterface(
fn=chat,
title="DeepSeek AI助手",
description="体验智能对话"
)
if __name__ == "__main__":
demo.launch()
七、优化与调试技巧
7.1 性能优化
- 设置合理的max_tokens限制
- 使用流式响应提升体验
- 添加缓存机制
from langchain.cache import InMemoryCache
langchain.llm_cache = InMemoryCache()
7.2 安全防护
代码语言:python代码运行次数:0运行复制from langchain_community.chat_models import SafetySettings
safety_config = SafetySettings(
hate_speech_filter=True,
self_harm_filter=True
)
model = ChatDeepSeek(..., safety_settings=safety_config)
八、项目完整结构
代码语言:shell复制/my-agent
├── main.py
├── utils/
│ ├── tools.py
│ └── config.py
├── .env
├── requirements.txt
└── README.md
下一步学习建议
- 接入更多API工具(邮件发送、数据分析)
- 尝试RAG增强知识库
- 实现多Agent协作系统
- 探索模型微调
立即动手尝试吧! 如果在实现过程中遇到任何问题,欢迎在评论区留言交流。下期我们将探讨如何为Agent添加视觉能力,敬请期待!
本文标签: 基于LangChain和DeepSeek的Agent开发指南
版权声明:本文标题:基于LangChain和DeepSeek的Agent开发指南 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/biancheng/1748209794a2826632.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论