蓝色天空.知识 · 实践 · 创造
我的收藏
LangChain 教程目录 37章
LangChain / LEARN BY DOING

LangChain 环境搭建

讲解 Python 3.10+ 环境核对、核心包与提供商包模块化安装、.env 与 .gitignore 密钥安全实践,离线实测 python-dotenv 加载脱敏与 OpenAI/DeepSeek 客户端配置。

学完这一章,你能够

  • 讲解 Python 3.10+ 环境核对、核心包与提供商包模块化安装、.env 与 .gitignore 密钥安全实践,离线实测 python-dotenv 加载脱敏与 OpenAI/DeepSeek 客户端配置。

运行环境要求与 Python 检查

搭建 LangChain 开发环境前,需确认本地满足表 1 的基础版本要求:Python 最低 3.10(推荐 3.11 或 3.12)、pip 最低 22.0,macOS / Linux / Windows 均可运行。终端执行 python --version 即可检查解释器版本;包与虚拟环境管理也可结合 uv 等现代工具。本站离线隔离环境实测为 CPython 3.12.14,完全满足要求。

模块化安装 LangChain 核心包与提供商包

LangChain 采用核心与集成解耦的模块化架构。执行 pip install langchain 会安装主包(包含 init_chat_model()、create_agent() 等高层入口),并自动拉取底层抽象依赖 langchain-core。

主包本身不包含各厂商 SDK 实现,需按实际选用的大模型单独安装对应的集成包(详见下表 2,覆盖 OpenAI、Anthropic、DeepSeek、Google、Ollama、xAI 与 Mistral)。

初学者推荐一条命令安装核心组合:pip install langchain langchain-openai python-dotenv。其中 python-dotenv 用于从项目根目录的 .env 文件读取 API Key,避免将敏感密钥硬编码进源码文件。

API Key 安全管理与 .env 配置

以 OpenAI 为例,需在官网控制台(https://platform.openai.com)登录进入 API Keys 页面点击 Create new secret key,立即妥善保存仅展示一次的 sk- 开头密钥,严禁提交至 Git 仓库或泄露给他人;其余模型厂商的密钥申请流程类似。

规范做法是在项目根目录建立 .env 文件存放 OPENAI_API_KEY、ANTHROPIC_API_KEY 或 DEEPSEEK_API_KEY,并立即将 .env、__pycache__/ 与 *.pyc 写入 .gitignore。程序启动时调用 load_dotenv() 注入环境变量,日志核验时仅打印前 8 位与后 4 位脱敏片段。本站离线在临时目录实测 load_dotenv(override=True) 准确加载占位密钥,脱敏输出 sk-test-...abcd,且 .env 规则已受 .gitignore 保护。

安装验证、国内 DeepSeek 兼容接入与项目目录建议

安装完成后应按步骤校验:(1)导入 langchain 并打印版本号;(2)导入对应集成包;(3)核对环境变量非空并脱敏输出;(4)发起最小模型调用。若联网测试最后一步失败,应依次排查 API Key 有效性、网络代理设置与账户可用额度。本站在离线环境中已验证 langchain 1.4.9、langchain-core 1.7.6、langchain-openai、langchain-deepseek 与 python-dotenv 均可正常导入,并用 GenericFakeChatModel 完成本地冒烟调用。

国内开发者可选用 DeepSeek API(在 https://platform.deepseek.com/api_keys 创建密钥并参阅官方中文文档 https://api-docs.deepseek.com/zh-cn/)。如需统一多厂商网关可另行了解 litellm(pip install -U litellm),但在本节示例中直接复用 ChatOpenAI 并设置 openai_api_base="https://api.deepseek.com" 即可对接 DeepSeek,无需额外安装 LiteLLM。本站离线实例化验证:ChatOpenAI(model='deepseek-v4-pro', openai_api_base='https://api.deepseek.com', temperature=0.7, max_tokens=1024) 与 init_chat_model('deepseek:deepseek-flash') 均可正确完成本地对象构造。

推荐按模块组织学习工程目录:根目录放置 .env、.gitignore 与公共配置加载模块 config.py,按章节顺序编号管理 01_hello_world.py、02_first_agent.py 等独立脚本,便于复用配置与隔离依赖。

LangChain 开发环境最低与推荐要求

项目最低版本推荐版本
Python3.103.11 或 3.12(本站实测 3.12.14)
pip22.0当前最新稳定版(亦可选用 uv 管理环境)
操作系统macOS / Linux / Windows 均可跨平台一致支持(本站于 Windows x64 实测)

常见模型提供商 LangChain 集成包安装命令

模型提供商安装命令使用的模型
OpenAIpip install langchain-openaiGPT-4o、GPT-4.1 / GPT-5 等系列
Anthropicpip install langchain-anthropicClaude 系列模型
DeepSeekpip install langchain-deepseekDeepSeek-V3、R1、Flash / V4 系列
Googlepip install langchain-google-genaiGemini 系列模型
Ollama(本地模型)pip install langchain-ollamaLlama、Qwen 等本地推理模型
xAIpip install langchain-xaiGrok 系列模型
Mistralpip install langchain-mistralaiMistral / Mixtral 系列模型

离线校验 Python/LangChain 安装状态、.env 密钥脱敏与客户端配置

含完整源码 · 224 行
展开查看收起
python
"""Independent offline lab for LangChain Ch 03: Environment Setup & Configuration."""
import json
import os
import platform
import sys
import tempfile
from pathlib import Path

import dotenv
import langchain
import langchain_core
import langchain_deepseek
import langchain_openai
from dotenv import dotenv_values, load_dotenv
from langchain.chat_models import init_chat_model
from langchain_core.language_models.fake_chat_models import GenericFakeChatModel
from langchain_core.messages import AIMessage
from langchain_openai import ChatOpenAI


def mask_api_key(key: str) -> str:
    return f"{key[:8]}...{key[-4:]}"


def main():
    cases = []

    # 1. Python version >= 3.10 and core/provider packages check
    py_ok = sys.version_info >= (3, 10)
    pkg_versions = dict(
        python=platform.python_version(),
        langchain=langchain.__version__,
        langchain_core=langchain_core.__version__,
        has_openai=hasattr(langchain_openai, "ChatOpenAI"),
        has_deepseek=hasattr(langchain_deepseek, "ChatDeepSeek"),
        has_dotenv=hasattr(dotenv, "load_dotenv"),
    )
    c1_ok = py_ok and pkg_versions["has_openai"] and pkg_versions["has_deepseek"] and pkg_versions["has_dotenv"]
    cases.append(
        dict(
            name="python_and_packages_verification",
            inputs=dict(min_python="3.10"),
            prerequisites="核对当前离线隔离环境满足 Python 3.10+ 要求,且 langchain、langchain-openai、langchain-deepseek、python-dotenv 均可导入。",
            action="检查 sys.version_info 与各模块版本和关键导出符号。",
            expected=dict(python_ge_310=True, all_packages_importable=True),
            actual=dict(
                python_ge_310=py_ok,
                all_packages_importable=(
                    pkg_versions["has_openai"]
                    and pkg_versions["has_deepseek"]
                    and pkg_versions["has_dotenv"]
                ),
            ),
            measurements=pkg_versions,
            passed=c1_ok,
        )
    )

    # 2. .env loading, key masking & .gitignore protection in an isolated temp dir
    saved_openai = os.environ.get("OPENAI_API_KEY")
    saved_deepseek = os.environ.get("DEEPSEEK_API_KEY")
    try:
        with tempfile.TemporaryDirectory() as tmp:
            root = Path(tmp)
            env_file = root / ".env"
            env_file.write_text(
                "# 教学占位配置\n"
                "OPENAI_API_KEY=sk-test-demo-1234567890abcd\n"
                "DEEPSEEK_API_KEY=sk-ds-demo-9876543210wxyz\n",
                encoding="utf-8",
            )
            gitignore_file = root / ".gitignore"
            gitignore_file.write_text(".env\n__pycache__/\n*.pyc\n", encoding="utf-8")

            parsed_env = dotenv_values(env_file)
            loaded = load_dotenv(dotenv_path=env_file, override=True)
            oa_key = os.getenv("OPENAI_API_KEY", "")
            ds_key = os.getenv("DEEPSEEK_API_KEY", "")
            oa_masked = mask_api_key(oa_key)
            ds_masked = mask_api_key(ds_key)
            gitignore_rules = [ln.strip() for ln in gitignore_file.read_text(encoding="utf-8").splitlines() if ln.strip()]
    finally:
        if saved_openai is None:
            os.environ.pop("OPENAI_API_KEY", None)
        else:
            os.environ["OPENAI_API_KEY"] = saved_openai
        if saved_deepseek is None:
            os.environ.pop("DEEPSEEK_API_KEY", None)
        else:
            os.environ["DEEPSEEK_API_KEY"] = saved_deepseek

    c2_ok = (
        loaded is True
        and parsed_env.get("OPENAI_API_KEY") == "sk-test-demo-1234567890abcd"
        and oa_masked == "sk-test-...abcd"
        and ds_masked == "sk-ds-de...wxyz"
        and ".env" in gitignore_rules
    )
    cases.append(
        dict(
            name="dotenv_env_loading_and_masking",
            inputs=dict(env_keys=["OPENAI_API_KEY", "DEEPSEEK_API_KEY"]),
            prerequisites="在临时目录写入占位 .env 与 .gitignore,通过 python-dotenv 加载并执行脱敏展示后恢复进程环境变量。",
            action="验证 load_dotenv 正确注入密钥、mask_api_key 仅显示前 8 位与后 4 位且 .gitignore 包含 .env。",
            expected=dict(
                load_dotenv_ok=True,
                openai_masked="sk-test-...abcd",
                deepseek_masked="sk-ds-de...wxyz",
                env_in_gitignore=True,
            ),
            actual=dict(
                load_dotenv_ok=loaded,
                openai_masked=oa_masked,
                deepseek_masked=ds_masked,
                env_in_gitignore=(".env" in gitignore_rules),
            ),
            measurements=dict(
                gitignore_entries=gitignore_rules,
                parsed_key_count=len(parsed_env),
            ),
            passed=c2_ok,
        )
    )

    # 3. Offline provider client configuration (OpenAI & OpenAI-compatible DeepSeek)
    m_oa = init_chat_model("openai:gpt-4o-mini", api_key="sk-offline-dummy")
    m_ds_compat = ChatOpenAI(
        model="deepseek-v4-pro",
        openai_api_key="sk-offline-dummy",
        openai_api_base="https://api.deepseek.com",
        temperature=0.7,
        max_tokens=1024,
    )
    m_ds_native = init_chat_model("deepseek:deepseek-flash", api_key="sk-offline-dummy")

    c3_ok = (
        m_oa.model_name == "gpt-4o-mini"
        and m_ds_compat.model_name == "deepseek-v4-pro"
        and m_ds_compat.openai_api_base == "https://api.deepseek.com"
        and m_ds_compat.temperature == 0.7
        and m_ds_compat.max_tokens == 1024
        and type(m_ds_native).__name__ == "ChatDeepSeek"
    )
    cases.append(
        dict(
            name="provider_client_offline_configuration",
            inputs=dict(openai_model="gpt-4o-mini", compat_model="deepseek-v4-pro", base_url="https://api.deepseek.com"),
            prerequisites="离线构造 init_chat_model('openai:gpt-4o-mini')、ChatOpenAI(openai_api_base=...) 与 init_chat_model('deepseek:deepseek-flash')。",
            action="核对模型名称、兼容接口 base_url、temperature 与 max_tokens 配置均按预期生效且未发起外网请求。",
            expected=dict(
                oa_model="gpt-4o-mini",
                compat_model="deepseek-v4-pro",
                compat_base="https://api.deepseek.com",
                native_class="ChatDeepSeek",
            ),
            actual=dict(
                oa_model=m_oa.model_name,
                compat_model=m_ds_compat.model_name,
                compat_base=m_ds_compat.openai_api_base,
                native_class=type(m_ds_native).__name__,
            ),
            measurements=dict(
                compat_temperature=m_ds_compat.temperature,
                compat_max_tokens=m_ds_compat.max_tokens,
            ),
            passed=c3_ok,
        )
    )

    # 4. Offline smoke invocation and recommended project layout check
    smoke_llm = GenericFakeChatModel(
        messages=iter([AIMessage(content="蓝色天空网(mbsky.com)提供系统化编程与 AI 开发教程。")])
    )
    smoke_resp = smoke_llm.invoke("用一句话介绍蓝色天空网")
    with tempfile.TemporaryDirectory() as tmp:
        proj = Path(tmp) / "langchain-learning"
        proj.mkdir()
        expected_files = [".env", ".gitignore", "config.py", "01_hello_world.py", "02_first_agent.py"]
        for fname in expected_files:
            (proj / fname).write_text("# placeholder\n", encoding="utf-8")
        created_names = sorted(p.name for p in proj.iterdir())

    c4_ok = (
        isinstance(smoke_resp, AIMessage)
        and "蓝色天空网" in smoke_resp.content
        and created_names == sorted(expected_files)
    )
    cases.append(
        dict(
            name="offline_smoke_invocation_and_project_layout",
            inputs=dict(layout_files=expected_files),
            prerequisites="使用 GenericFakeChatModel 演练本地连通验证脚本结构,并在临时目录创建推荐项目结构。",
            action="验证 invoke 返回 AIMessage 文本,且项目根目录包含 .env、.gitignore、config.py 与示例脚本。",
            expected=dict(
                smoke_resp_type="ai",
                layout_complete=True,
            ),
            actual=dict(
                smoke_resp_type=smoke_resp.type,
                layout_complete=(created_names == sorted(expected_files)),
            ),
            measurements=dict(
                smoke_reply=smoke_resp.content,
                created_files=created_names,
            ),
            passed=c4_ok,
        )
    )

    print(
        json.dumps(
            dict(
                version=platform.python_version(),
                system=platform.system(),
                cases=cases,
            ),
            ensure_ascii=False,
        )
    )


if __name__ == "__main__":
    main()
确认 Python 3.12.14 >= 3.10、关键集成包导入成功、load_dotenv 注入与脱敏展示 sk-test-...abcd,以及 OpenAI/DeepSeek 客户端本地初始化参数准确。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a509.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:LangChain

课程关联工程包(登记关联37章) · 含当前章节或实例 · mbskycom202612a509.zip

下载课程关联工程包:LangChain

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a516.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

硬编码密钥极易随代码共享或版本提交泄露并导致盗刷;使用 python-dotenv 从项目根目录 .env 加载环境变量时,必须同步在 .gitignore 中添加 .env 规则防止其进入 Git 历史。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习