本教程将以实际代码案例为基础,带您掌握 LangChain 的核心概念与开发流程。我们将使用 LangChain 0.2.17 和 langchain-openai 0.1.25 版本,结合 DeepSeek 的 deepseek-chat 模型,构建一个完整的意图识别-响应生成系统。结合Jupyter进行实践效果更佳。需申请deepseek的API-KEY,充值10元可以玩好久。
一、环境准备
# 安装必要依赖
!pip install langchain==0.2.17 langchain-community==0.2.19 langchain-openai==0.1.25
二、代码结构解析
1. 核心组件初始化
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(
model="deepseek-chat",
api_key="sk-b247cb47eff84e9694f383c09682xxxx", # todo 替换deepseek API Key https://platform.deepseek.com/api_keys
temperature=0.7,
max_tokens=512,
timeout=30,
max_retries=3,
base_url="https://api.deepseek.com"
)
按shift+enter进行执行操作。
关键参数说明:
model
: 指定使用 DeepSeek 的 deepseek-chat 模型temperature
: 控制输出随机性(0-1 范围)base_url
: DeepSeek API 的基础地址max_retries
: 网络重试次数
2. 流程链式构建
(1)意图识别链
intent_prompt = PromptTemplate(
input_variables=["input_text"],
template="请根据以下输入识别用户意图:{input_text}"
)