0.1 Python 环境搭建与现代工具链
引言:工欲善其事,必先利其器
在构建 AI Agent 之前,我们需要一个强大、现代化的开发环境。这不仅仅是安装 Python 那么简单——专业的 AI 开发者会使用虚拟环境隔离项目、使用现代包管理工具、配置高效的代码编辑器。
本节将带你搭建一个与 LangChain/LangGraph 开发团队相同标准的开发环境。
🎯 小白理解:什么是"开发环境"?
想象你要在家里开一个烘焙工坊:
- Python = 你的烤箱(核心工具)
- 虚拟环境 = 不同的工作台(做蛋糕用一个台,做面包用另一个,互不干扰)
- 包管理工具 = 食材供应商(帮你自动采购需要的材料)
- VS Code = 你的厨房布局(各种工具摆放得井井有条,用起来顺手)
"搭建开发环境"就是把这些工具准备好,让你可以舒服地"做菜"(写代码)。
学习目标
学完本节后,你将能够:
- ✅ 安装 Python 3.11+ 并验证安装
- ✅ 理解虚拟环境的重要性并创建你的第一个虚拟环境
- ✅ 使用 pip 和 poetry 管理包依赖
- ✅ 配置 VS Code 进行 Python 开发
- ✅ 编写并运行你的第一个 Python 程序
- ✅ 理解为什么这些工具在 AI 开发中至关重要
第一部分:安装 Python 3.11+
为什么选择 Python 3.11+?
LangChain 和 LangGraph 1.0.2 要求 Python 3.9+,但我们推荐 Python 3.11 或更高版本,原因如下:
- 性能提升:Python 3.11 比 3.10 快 10-60%
- 更好的错误提示:错误信息更清晰,调试更容易
- 现代特性:支持最新的类型注解语法
- 长期支持:活跃维护至 2027 年
💡 关键概念:AI Agent 经常需要处理大量的 API 调用和数据转换,性能很重要。
安装步骤
macOS 系统
# 方法 1:使用 Homebrew(推荐)
brew install python@3.11
# 验证安装
python3.11 --version
# 输出:Python 3.11.x
# 方法 2:从官网下载
# 访问 https://www.python.org/downloads/Windows 系统
# 方法 1:使用 Microsoft Store(推荐)
# 打开 Microsoft Store,搜索 "Python 3.11"
# 方法 2:使用 Chocolatey
choco install python311
# 验证安装
python --version
# 输出:Python 3.11.xLinux 系统
# Ubuntu/Debian
sudo apt update
sudo apt install python3.11 python3.11-venv python3-pip
# Fedora
sudo dnf install python3.11
# 验证安装
python3.11 --version配置 PATH 环境变量
⚠️ 常见陷阱:安装后无法在终端中运行
python?这是 PATH 配置问题。
macOS/Linux:在 ~/.zshrc 或 ~/.bashrc 中添加:
alias python=python3.11
alias pip=pip3Windows:安装时勾选 "Add Python to PATH"
第二部分:虚拟环境——AI 项目的隔离沙盒
什么是虚拟环境?
想象你在同时开发三个项目:
- 项目 A 需要 LangChain 0.1.0
- 项目 B 需要 LangChain 0.2.0
- 项目 C 需要 LangChain 0.3.0
如果所有包都安装在全局环境,就会产生冲突。虚拟环境为每个项目创建独立的 Python 环境,互不干扰。
🎯 小白理解:虚拟环境就像"独立的房间"
想象你和三个室友合租一套公寓:
- 没有虚拟环境 = 大家共用一个冰箱。你买的牛奶可能被别人喝掉,别人的臭豆腐也会影响你的食物。
- 有虚拟环境 = 每人有自己的小冰箱。你的东西只有你能用,互不干扰。
在编程中:
- 包 = 食材(别人写好的代码工具)
- 版本冲突 = 你需要的是新鲜牛奶,但室友已经把冰箱塞满了过期牛奶
- 虚拟环境 = 你自己的小冰箱,想放什么版本就放什么版本
为什么这么重要? 因为不同的 AI 项目可能需要不同版本的工具。虚拟环境让你可以安全地尝试新东西,不会搞坏已有的项目。
🔗 与 Agent 的联系:在生产环境中,每个 Agent 应用都应该有自己的虚拟环境,确保依赖版本的一致性。
创建你的第一个虚拟环境
# 1. 创建项目文件夹
mkdir my-first-agent
cd my-first-agent
# 2. 创建虚拟环境
python3.11 -m venv .venv
# 3. 激活虚拟环境
# macOS/Linux:
source .venv/bin/activate
# Windows:
.venv\Scripts\activate
# 激活后,你的命令行提示符会显示 (.venv)虚拟环境的生命周期
# 激活虚拟环境
source .venv/bin/activate # macOS/Linux
.venv\Scripts\activate # Windows
# 在虚拟环境中安装包
pip install langchain
# 查看已安装的包
pip list
# 退出虚拟环境
deactivate💡 最佳实践:
- 虚拟环境文件夹命名为
.venv(以点开头表示隐藏)- 将
.venv/添加到.gitignore(不要提交到 Git)- 每次开发前先激活虚拟环境
第三部分:包管理工具
🎯 小白理解:什么是"包"?
包(Package) 就是别人写好的代码工具,你可以直接拿来用,不用自己从零开始写。
举个例子:
- 你想让 Python 能和 ChatGPT 对话 → 安装
openai包- 你想让 Python 能做数据分析 → 安装
pandas包- 你想让 Python 能构建 AI Agent → 安装
langchain和langgraph包包管理器 就像手机上的"应用商店":
- App Store / Google Play = pip / Poetry
- 下载 App = 安装包 (
pip install xxx)- 更新 App = 升级包 (
pip install --upgrade xxx)- 卸载 App = 卸载包 (
pip uninstall xxx)全世界的 Python 开发者都把自己写的好用工具分享到 PyPI(Python Package Index,Python 包索引),就像一个巨大的免费工具仓库!
pip:Python 的包管理器
# 安装单个包
pip install langchain
# 安装特定版本
pip install langchain==0.3.0
# 从 requirements.txt 安装
pip install -r requirements.txt
# 导出已安装的包
pip freeze > requirements.txt
# 升级包
pip install --upgrade langchain
# 卸载包
pip uninstall langchainPoetry:现代 Python 项目管理(推荐)
Poetry 是现代 Python 项目的首选工具,它提供:
- 依赖管理
- 虚拟环境管理
- 打包发布
- 锁定依赖版本
安装 Poetry
# macOS/Linux/WSL
curl -sSL https://install.python-poetry.org | python3 -
# Windows (PowerShell)
(Invoke-WebRequest -Uri https://install.python-poetry.org -UseBasicParsing).Content | py -
# 验证安装
poetry --version使用 Poetry 创建项目
# 创建新项目
poetry new my-agent-project
cd my-agent-project
# 项目结构:
# my-agent-project/
# ├── pyproject.toml # 项目配置文件
# ├── README.md
# ├── my_agent_project/ # 源代码目录
# │ └── __init__.py
# └── tests/ # 测试目录
# └── __init__.py
# 添加依赖
poetry add langchain langgraph
# 安装所有依赖
poetry install
# 运行 Python 脚本
poetry run python script.py
# 进入虚拟环境
poetry shellpyproject.toml 配置示例
[tool.poetry]
name = "my-agent-project"
version = "0.1.0"
description = "My first AI Agent"
authors = ["Your Name <your.email@example.com>"]
[tool.poetry.dependencies]
python = "^3.11"
langchain = "^0.3.0"
langgraph = "^1.0.2"
openai = "^1.0.0"
[tool.poetry.dev-dependencies]
pytest = "^7.0"
black = "^23.0"
mypy = "^1.0"
[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"🔗 与 Agent 的联系:LangChain 和 LangGraph 的官方项目都使用 Poetry 管理依赖,学会使用它能让你更容易理解开源代码。
第四部分:配置 VS Code
安装 VS Code
- 访问 https://code.visualstudio.com/
- 下载并安装对应平台的版本
- 安装以下必备扩展:
必装扩展
1. Python (Microsoft)
- 提供 IntelliSense、调试、格式化等功能
2. Pylance (Microsoft)
- 强大的类型检查和代码补全
3. Black Formatter (Microsoft)
- 自动格式化代码
4. autoDocstring (Nils Werner)
- 自动生成文档字符串
5. Error Lens (Alexander)
- 实时显示错误和警告VS Code 配置文件
在项目根目录创建 .vscode/settings.json:
{
"python.defaultInterpreterPath": ".venv/bin/python",
"python.formatting.provider": "black",
"python.formatting.blackArgs": ["--line-length", "88"],
"python.linting.enabled": true,
"python.linting.pylintEnabled": false,
"python.linting.flake8Enabled": true,
"python.analysis.typeCheckingMode": "basic",
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.organizeImports": true
},
"[python]": {
"editor.defaultFormatter": "ms-python.black-formatter",
"editor.tabSize": 4
}
}选择 Python 解释器
- 按
Cmd+Shift+P(macOS) 或Ctrl+Shift+P(Windows/Linux) - 输入 "Python: Select Interpreter"
- 选择你的虚拟环境中的 Python(
.venv/bin/python)
第五部分:你的第一个 Python 程序
🎯 小白理解:写代码就像写菜谱
Python 代码其实就是一份"详细菜谱",告诉计算机一步一步该做什么:
普通菜谱: Python 代码: 1. 准备一个碗 1. 创建一个变量 2. 打两个鸡蛋进去 2. 给变量赋值 3. 加点盐搅拌 3. 调用函数处理数据 4. 倒进锅里煎 4. 输出结果接下来的代码看起来可能有点陌生,但别担心!你现在只需要:
- 照着敲一遍(不要复制粘贴,手动打字能帮你记忆)
- 运行看看结果
- 大概理解每行在干嘛(详细解释在代码后面)
Hello, AI Agent!
创建文件 hello_agent.py:
"""
我的第一个 Python 程序
这个程序展示了 Python 的基本语法和 AI Agent 的核心概念
"""
def greet_agent(name: str) -> str:
"""
向 AI Agent 打招呼
Args:
name: Agent 的名称
Returns:
格式化的问候语
"""
greeting = f"Hello, {name}! Welcome to the world of AI Agents."
return greeting
def main() -> None:
"""主函数:程序的入口点"""
# 定义 Agent 的名称
agent_name: str = "ResearchBot"
# 调用函数获取问候语
message: str = greet_agent(agent_name)
# 打印结果
print(message)
print(f"\nYou are now ready to build intelligent agents with LangGraph!")
if __name__ == "__main__":
main()运行程序
# 方法 1:直接运行
python hello_agent.py
# 方法 2:使用 Poetry
poetry run python hello_agent.py
# 预期输出:
# Hello, ResearchBot! Welcome to the world of AI Agents.
#
# You are now ready to build intelligent agents with LangGraph!代码解析
让我们逐行分析这个程序:
"""...""" # 模块级文档字符串,描述整个文件的作用def greet_agent(name: str) -> str:
# def: 定义函数的关键字
# greet_agent: 函数名(使用 snake_case 命名法)
# name: str: 参数名及其类型注解
# -> str: 返回值类型注解 """...""" # 函数文档字符串(docstring)
# 格式遵循 Google 风格,包含:
# - 简短描述
# - Args: 参数说明
# - Returns: 返回值说明 greeting = f"Hello, {name}! ..."
# f"...": f-string,Python 3.6+ 的字符串格式化方式
# {name}: 在字符串中插入变量if __name__ == "__main__":
# 只有直接运行此文件时才执行 main()
# 如果被其他文件导入,则不执行💡 关键概念:这个简单的程序已经包含了专业代码的要素:
- 类型注解(Type Hints)
- 文档字符串(Docstrings)
- 函数封装
- 主函数模式
第六部分:安装 AI 开发必备包
创建一个 AI Agent 项目
# 使用 Poetry 创建项目
poetry new ai-agent-basics
cd ai-agent-basics
# 添加 AI 开发核心依赖
poetry add langchain langgraph langchain-openai python-dotenv
# 添加开发工具
poetry add --group dev pytest black mypy ruff
# 安装所有依赖
poetry install验证安装
创建 test_installation.py:
"""验证 LangChain 和 LangGraph 安装"""
def test_imports() -> None:
"""测试核心包是否正确安装"""
try:
import langchain
import langgraph
from langchain_openai import ChatOpenAI
print("✅ LangChain 版本:", langchain.__version__)
print("✅ LangGraph 已安装")
print("✅ 所有依赖安装成功!")
except ImportError as e:
print(f"❌ 导入错误: {e}")
print("请运行: poetry install")
if __name__ == "__main__":
test_imports()运行测试:
poetry run python test_installation.py实战练习:搭建你的开发环境
练习 1:环境配置检查清单
完成以下任务,并在终端截图验证:
# 1. 检查 Python 版本
python --version # 应该显示 3.11.x 或更高
# 2. 创建并激活虚拟环境
python -m venv test_env
source test_env/bin/activate # macOS/Linux
# 或
test_env\Scripts\activate # Windows
# 3. 安装 LangChain
pip install langchain
# 4. 验证安装
python -c "import langchain; print(langchain.__version__)"
# 5. 清理
deactivate
rm -rf test_env练习 2:使用 Poetry 创建项目
# 1. 创建新项目
poetry new weather-agent
# 2. 添加依赖
cd weather-agent
poetry add langchain langgraph httpx
# 3. 创建一个简单的 Agent 框架
# 在 weather_agent/main.py 中编写代码
# 4. 运行项目
poetry run python -m weather_agent.main常见问题与解决方案
Q1: 虚拟环境激活后,pip 仍然安装到全局?
解决方案:确保使用 python -m pip install 而不是直接 pip install
# 推荐方式
python -m pip install langchain
# 而不是
pip install langchainQ2: Poetry 安装速度很慢?
解决方案:配置国内镜像源
# 配置 PyPI 镜像
poetry source add tsinghua https://pypi.tuna.tsinghua.edu.cn/simple/Q3: VS Code 无法识别虚拟环境中的包?
解决方案:
- 重新选择 Python 解释器(
Cmd+Shift+P→ "Python: Select Interpreter") - 重启 VS Code
- 确保
.vscode/settings.json中的路径正确
Q4: 在 Windows 上无法执行激活脚本?
解决方案:修改 PowerShell 执行策略
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser本节总结
你已经掌握了:
✅ Python 3.11+ 的安装与配置
✅ 虚拟环境的创建和管理
✅ pip 和 Poetry 的使用
✅ VS Code 的专业配置
✅ 编写和运行第一个 Python 程序
✅ 安装 LangChain 和 LangGraph
关键要点回顾:
1. 始终使用虚拟环境
每个项目一个独立环境,避免依赖冲突
2. Poetry 是现代 Python 的标准
特别是在开发 AI Agent 等复杂项目时
3. 类型注解从第一天起就使用
这会让你的代码更接近 LangChain 的标准
4. 配置好的开发环境能提升 10 倍效率
花时间在工具链上是值得的投资