"""Independent offline lab for LangChain Ch 04: LangChain + DeepSeek Integration."""
import json
import os
import platform
import tempfile
from pathlib import Path
from typing import Any
import langchain_deepseek
from dotenv import load_dotenv
from langchain.chat_models import init_chat_model
from langchain_core.language_models.chat_models import BaseChatModel
from langchain_core.messages import AIMessage, AIMessageChunk, HumanMessage, SystemMessage
from langchain_core.outputs import ChatGeneration, ChatGenerationChunk, ChatResult
from langchain_core.prompts import ChatPromptTemplate
from langchain_deepseek import ChatDeepSeek
from pydantic import Field
class RecordingOfflineChatModel(BaseChatModel):
"""Offline chat model recording normalized LangChain messages and supporting stream()."""
recorded_batches: list[Any] = Field(default_factory=list)
reply_text: str = "我喜欢编程。"
stream_tokens: list[str] = Field(default_factory=lambda: ["Python ", "是一门", "简洁高效的编程语言。"])
@property
def _llm_type(self) -> str:
return "recording-offline-deepseek"
def _generate(self, messages, stop=None, run_manager=None, **kwargs):
self.recorded_batches.append([(m.type, m.content) for m in messages])
return ChatResult(generations=[ChatGeneration(message=AIMessage(content=self.reply_text))])
def _stream(self, messages, stop=None, run_manager=None, **kwargs):
self.recorded_batches.append([(m.type, m.content) for m in messages])
for tok in self.stream_tokens:
yield ChatGenerationChunk(message=AIMessageChunk(content=tok))
def classify_api_error(exc: Exception) -> str:
msg = str(exc)
if isinstance(exc, ModuleNotFoundError):
return "reinstall_dependency"
if "401" in msg or "Unauthorized" in msg:
return "check_deepseek_api_key"
if "429" in msg or "Rate Limit" in msg:
return "reduce_request_rate"
if isinstance(exc, TimeoutError) or "Timeout" in msg:
return "increase_timeout"
return "unknown_error"
def main():
cases = []
# 1. ChatDeepSeek and init_chat_model offline instantiation
llm_flash = ChatDeepSeek(
api_key="sk-offline-dummy",
model="deepseek-v4-flash",
temperature=0,
max_tokens=None,
timeout=None,
max_retries=2,
)
llm_pro = ChatDeepSeek(
api_key="sk-offline-dummy",
model="deepseek-v4-pro",
temperature=0.7,
max_tokens=1024,
timeout=60,
max_retries=3,
)
llm_init = init_chat_model("deepseek:deepseek-v4-flash", temperature=0.7, api_key="sk-offline-dummy")
c1_ok = (
isinstance(llm_flash, ChatDeepSeek)
and llm_flash.model_name == "deepseek-v4-flash"
and llm_flash.temperature == 0.0
and llm_flash.max_tokens is None
and llm_flash.max_retries == 2
and llm_pro.model_name == "deepseek-v4-pro"
and llm_pro.max_tokens == 1024
and llm_pro.request_timeout == 60.0
and llm_pro.max_retries == 3
and isinstance(llm_init, ChatDeepSeek)
and llm_init.temperature == 0.7
)
cases.append(
dict(
name="chat_deepseek_offline_config_and_init",
inputs=dict(models=["deepseek-v4-flash", "deepseek-v4-pro"]),
prerequisites="使用本地已安装的 langchain-deepseek 离线构造 ChatDeepSeek 与 init_chat_model('deepseek:...') 实例。",
action="验证 api_key、model、temperature、max_tokens、timeout、max_retries 参数映射以及两种初始化方式均返回 ChatDeepSeek。",
expected=dict(
flash_model="deepseek-v4-flash",
pro_model="deepseek-v4-pro",
pro_timeout=60.0,
init_returns_chat_deepseek=True,
),
actual=dict(
flash_model=llm_flash.model_name,
pro_model=llm_pro.model_name,
pro_timeout=llm_pro.request_timeout,
init_returns_chat_deepseek=isinstance(llm_init, ChatDeepSeek),
),
measurements=dict(
default_api_base=llm_flash.api_base,
flash_max_retries=llm_flash.max_retries,
pro_max_tokens=llm_pro.max_tokens,
has_langchain_deepseek=hasattr(langchain_deepseek, "ChatDeepSeek"),
),
passed=c1_ok,
)
)
# 2. .env default path, custom dotenv_path, and optional LangSmith env flags
saved = {k: os.environ.get(k) for k in ("DEEPSEEK_API_KEY", "LANGSMITH_TRACING")}
try:
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
(root / ".env").write_text('DEEPSEEK_API_KEY="sk-root-1111"\n', encoding="utf-8")
cfg_dir = root / "config"
cfg_dir.mkdir()
(cfg_dir / ".env").write_text('DEEPSEEK_API_KEY="sk-custom-2222"\n', encoding="utf-8")
load_dotenv(dotenv_path=root / ".env", override=True)
k_root = os.getenv("DEEPSEEK_API_KEY")
load_dotenv(dotenv_path=cfg_dir / ".env", override=True)
k_custom = os.getenv("DEEPSEEK_API_KEY")
os.environ["LANGSMITH_TRACING"] = "true"
tracing_on = os.getenv("LANGSMITH_TRACING") == "true"
finally:
for k, v in saved.items():
if v is None:
os.environ.pop(k, None)
else:
os.environ[k] = v
c2_ok = k_root == "sk-root-1111" and k_custom == "sk-custom-2222" and tracing_on
cases.append(
dict(
name="dotenv_default_and_custom_path",
inputs=dict(paths=[".env", "config/.env"]),
prerequisites="在临时目录测试默认根目录 .env、自定义 config/.env 路径加载及可选 LANGSMITH_TRACING 环境变量设置。",
action="验证 load_dotenv 按路径依次注入 DEEPSEEK_API_KEY 并自动剥离引号。",
expected=dict(
root_key="sk-root-1111",
custom_key="sk-custom-2222",
tracing_flag=True,
),
actual=dict(
root_key=k_root,
custom_key=k_custom,
tracing_flag=tracing_on,
),
measurements=dict(
env_restored=True,
),
passed=c2_ok,
)
)
# 3. Tuple messages, explicit SystemMessage/HumanMessage, and ChatPromptTemplate LCEL chain
rec_model = RecordingOfflineChatModel(reply_text="我喜欢编程。")
tuple_resp = rec_model.invoke(
[
("system", "You are a helpful assistant that translates English to Chinese."),
("human", "I love programming."),
]
)
msg_resp = rec_model.invoke(
[
SystemMessage(content="你是一名专业 Python 教师。"),
HumanMessage(content="请解释什么是 LangChain,并给出简单示例。"),
]
)
prompt = ChatPromptTemplate.from_template("请详细解释:{topic}")
chain = prompt | rec_model
chain_resp = chain.invoke({"topic": "Transformer"})
c3_ok = (
tuple_resp.content == "我喜欢编程。"
and rec_model.recorded_batches[0] == [
("system", "You are a helpful assistant that translates English to Chinese."),
("human", "I love programming."),
]
and rec_model.recorded_batches[1][0][0] == "system"
and rec_model.recorded_batches[1][1][0] == "human"
and rec_model.recorded_batches[2] == [("human", "请详细解释:Transformer")]
and isinstance(msg_resp, AIMessage)
and isinstance(chain_resp, AIMessage)
)
cases.append(
dict(
name="messages_tuple_and_prompt_chain_offline",
inputs=dict(topic="Transformer"),
prerequisites="使用可记录输入消息的离线 BaseChatModel 验证元组消息、显式消息类及 ChatPromptTemplate | llm 链。",
action="核对元组自动转为 (system, human) 消息、SystemMessage/HumanMessage 正常传递且模板变量准确替换。",
expected=dict(
tuple_normalized_types=["system", "human"],
explicit_msg_types=["system", "human"],
prompt_rendered="请详细解释:Transformer",
translation_reply="我喜欢编程。",
),
actual=dict(
tuple_normalized_types=[t for t, _ in rec_model.recorded_batches[0]],
explicit_msg_types=[t for t, _ in rec_model.recorded_batches[1]],
prompt_rendered=rec_model.recorded_batches[2][0][1],
translation_reply=tuple_resp.content,
),
measurements=dict(
total_recorded_calls=len(rec_model.recorded_batches),
),
passed=c3_ok,
)
)
# 4. Streaming output chunks and common error diagnosis rules
stream_model = RecordingOfflineChatModel()
chunks = list(stream_model.stream("请介绍 Python"))
non_empty_chunks = [c for c in chunks if c.content]
joined = "".join(c.content for c in chunks)
error_map = {
"401": classify_api_error(RuntimeError("401 Unauthorized")),
"missing_pkg": classify_api_error(ModuleNotFoundError("langchain_deepseek")),
"rate_limit": classify_api_error(RuntimeError("429 Rate Limit")),
"timeout": classify_api_error(TimeoutError("Request Timeout")),
}
c4_ok = (
len(non_empty_chunks) == 3
and all(isinstance(c, AIMessageChunk) for c in chunks)
and joined == "Python 是一门简洁高效的编程语言。"
and error_map == {
"401": "check_deepseek_api_key",
"missing_pkg": "reinstall_dependency",
"rate_limit": "reduce_request_rate",
"timeout": "increase_timeout",
}
)
cases.append(
dict(
name="streaming_and_error_classification_offline",
inputs=dict(prompt="请介绍 Python", error_types=["401", "missing_pkg", "rate_limit", "timeout"]),
prerequisites="验证模型 .stream() 逐块产生 AIMessageChunk,并对四类常见调用错误进行本地诊断分类。",
action="核对 3 个非空文本流式片段拼接为完整句子(langchain-core 1.7 末尾自动附带空结束块),并确认四类错误映射正确。",
expected=dict(
non_empty_chunk_count=3,
all_ai_chunks=True,
joined_text="Python 是一门简洁高效的编程语言。",
error_actions={
"401": "check_deepseek_api_key",
"missing_pkg": "reinstall_dependency",
"rate_limit": "reduce_request_rate",
"timeout": "increase_timeout",
},
),
actual=dict(
non_empty_chunk_count=len(non_empty_chunks),
all_ai_chunks=all(isinstance(c, AIMessageChunk) for c in chunks),
joined_text=joined,
error_actions=error_map,
),
measurements=dict(
total_chunks_including_stop=len(chunks),
chunk_texts=[c.content for c in chunks],
),
passed=c4_ok,
)
)
print(
json.dumps(
dict(
version=platform.python_version(),
system=platform.system(),
cases=cases,
),
ensure_ascii=False,
)
)
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14、LangChain 本地离线隔离依赖。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、LangChain 本地离线隔离依赖。
入口文件:projects/langchain-deepseek-lab/explore-deepseek.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-deepseek.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、LangChain 本地离线隔离依赖。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联37章) · 含当前章节或实例 · mbskycom202612a509.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a514.zip