欢迎贡献代码!无论您是在修复错误、添加功能还是提升性能,您的贡献都将帮助成千上万的开发者获得更好的开发体验。
入门指南
如果您正在寻找可以参与的工作,请查看我们仓库中标记为"需要帮助"的问题:
LangChain
标签
LangGraph
标签
Deep Agents
标签
快速修复:提交错误修复
对于简单的错误修复,您可以立即开始:
Reproduce the issue
在克隆仓库之前,请确保您可以可靠地复现该错误。这有助于确认问题,并为您的修复提供起点。维护者和其他贡献者应该能够根据您的描述复现问题,而无需额外的设置或修改。
Fork the repository
将 LangChain, LangGraph, or Deep Agents 仓库分叉到您的 个人 GitHub 账户
Clone and setup
git clone https://github.com/your-username/name-of-forked-repo.git
# For instance, for LangChain:
git clone https://github.com/parrot123/langchain.git
# Inside your repo, initialize environment and install dependencies
uv venv && source .venv/bin/activate
uv sync --all-groups
# or, to install a specific group only:
uv sync --group test
您需要安装 uv 如果您之前没有安装过
Create a branch
为您的修复创建一个新分支。这有助于保持您的更改井然有序,并使以后提交拉取请求更加容易。
git checkout -b your-username/short-bugfix-name
Write failing tests
添加 单元测试 来确保修复后能通过。这样我们可以验证问题已解决并防止回归
Make your changes
修复错误时遵循我们的 代码质量标准。进行 **最小必要更改** 来解决问题。我们强烈鼓励贡献者在开始编码之前先在问题上评论。例如:
> *"我想处理这个问题。我的预期方法是[...简要描述...]。这是否符合维护者的期望?"*
30 秒的评论通常可以防止在您最初的方法错误时浪费精力。
Verify the fix
确保测试通过且没有引入回归。在提交您的 PR 之前,确保所有测试在本地通过
make format
make lint
make test
# For bugfixes involving integrations, also run:
make integration_tests
# (You may need to set up API testing credentials)
Document the change
Update docstrings and/or inline comments if behavior changes
Submit a pull request
请遵循提供的 PR 模板。如果适用,请使用 关闭关键字 (e.g. Fixes #ISSUE_NUMBER以便在您的PR合并时自动关闭该问题。
完整开发环境设置
对于持续开发或较大的贡献:
贡献指南
在您开始为LangChain项目做贡献之前,请花点时间想想您为什么要这样做。如果您唯一的目标是在简历上添加一个"首次贡献"(或者您只是在寻找一个快速的成功),那么您可能更适合参加训练营或在线教程。
为开源项目做贡献需要时间和精力,但这也可以帮助您成为更好的开发者并学习新技能。但是,重要的是要知道,这可能比参加培训课程更难、更慢。也就是说,如果您愿意花时间把事情做好,开源贡献是值得的!
向后兼容性
通过以下方式保持兼容性:
Stable interfaces
始终保留:
- 函数签名和参数名称 - 类接口和方法名称 - 返回值结构和类型 - 公共API的导入路径
Safe changes
可接受的修改:
- - 添加新的可选参数
- 向类添加新方法 - 在不改写行为的情况下提高性能 - 添加新模块或函数
Before making changes
- 这会破坏现有用户代码吗?
- - 检查您的目标是否是公共的
- - 如果需要,它是否在以下位置导出
__init__.py?
- 测试中是否有现有的使用模式?
新功能
我们对新功能保持高标准。我们通常不接受外部贡献者提出的新核心抽象,除非存在一个证明迫切需要的现有问题。这也适用于对基础设施和依赖项的更改。
一般来说,功能贡献要求包括:
Design discussion
打开一个问题描述:
- 您要解决的问题 - 拟议的API设计 - 预期的使用模式
Implementation
- 遵循现有的代码模式 - 包含全面的测试和文档 - 考虑安全影响
Integration considerations
- - 这如何与现有功能交互?
- - 是否有性能影响?
- - 这是否引入新的依赖项?
我们将拒绝可能导致安全漏洞或报告的功能。
安全指南
安全检查清单:
Input validation
- - 验证并清理所有用户输入
- - 正确转义模板和查询中的数据
- - 切勿使用
eval(),exec(), orpickle处理用户数据,因为这可能导致任意代码执行漏洞
Error handling
- 使用特定的异常类型 - 不要在错误消息中暴露敏感信息 - 实施适当的资源清理
Dependencies
- 避免添加硬依赖 - 将可选依赖项保持在最少 - 检查第三方包的安全问题
开发环境
我们的 Python 项目使用 uv 进行依赖管理。请确保您已安装最新版本。
查看完 贡献指南后,在下面的 仓库结构 部分找到您正在处理的组件的包目录。
仓库结构
LangChain
LangChain 被组织为一个包含多个包的单体仓库:
Core packages
- - **
langchain** (位于libs/langchain/):包含链、代理和检索逻辑的主包 - - **
langchain-core** (位于libs/core/):基础接口和核心抽象
Partner packages
位于 libs/partners/,这些是针对特定集成的独立版本包。例如: - **langchain-openai**: OpenAI 集成 - **langchain-anthropic**: Anthropic 集成 - **langchain-google-genai**: Google Generative AI 集成
许多合作伙伴包位于外部仓库中。请查看 集成列表 了解更多详情。
Supporting packages
- - **
langchain-text-splitters**:文本分割工具 - - **
langchain-standard-tests**:集成的标准测试套件
LangGraph
LangGraph 采用多包 monorepo 结构组织:
Core packages
- **langgraph** (位于 libs/langgraph/):用于构建有状态、多角色代理的核心框架 - **langgraph-prebuilt** (位于 libs/prebuilt/):用于创建和运行代理及工具的高级 API
Checkpoint packages
- **langgraph-checkpoint** (位于 libs/checkpoint/):检查点保存器的基础接口 - **langgraph-checkpoint-postgres** (位于 libs/checkpoint-postgres/):Postgres 实现 - **langgraph-checkpoint-sqlite** (位于 libs/checkpoint-sqlite/):SQLite 实现
SDK and CLI
- **langgraph-sdk** (位于 libs/sdk-py/):Agent Server API 的 Python SDK - **langgraph-cli** (位于 libs/cli/):官方命令行界面
Deep Agents
Deep Agents 采用多包 monorepo 结构组织:
Core packages
- **deepagents** (位于 libs/deepagents/):用于构建具有规划、文件系统和子代理能力的深度代理的核心框架 - **deepagents-code** (位于 libs/code/):Deep Agents Code — 具有对话恢复、网络搜索和沙箱功能的交互式终端界面 - **deepagents-cli** (位于 libs/cli/):部署工具(deepagents deploy, deepagents init, deepagents dev)用于将代理部署到 LangSmith Deployments
Integration packages
- **deepagents-harbor** (位于 libs/harbor/):Harbor 与 LangSmith 追踪的集成 - **deepagents-acp** (位于 libs/acp/):Agent Client Protocol 集成
开发工作流程
预提交钩子
这些 LangChain 和 Deep Agents 仓库包含 pre-commit 钩子,可在每次提交前自动运行格式化、代码检查和验证检查。请从仓库根目录安装它们:
pip install pre-commit # or: uv tool install pre-commit
pre-commit install
这些钩子强制执行: - 不允许直接提交到受保护分支 - YAML 和 TOML 语法验证 - 尾部空格和文件末尾修复 - 智能引号和非标准空格规范化 - Per-package make format 和 make lint
运行测试
我们尽可能优先使用单元测试而非集成测试。单元测试在每次 pull request 时运行,因此应该快速且可靠。集成测试按计划运行,需要更多设置,因此应保留用于确认与外部服务的接口点。
单元测试
位置: tests/unit_tests/
Unit tests cover modular logic that does not require calls to outside APIs. If you add new logic, you should add a unit test. In unit tests, check pre/post processing and mock external dependencies.
要求: - 不允许网络调用 - 测试所有代码路径,包括边缘情况 - 使用 mock 来处理外部依赖
运行单元测试:
make test
# Or directly:
uv run --group test pytest tests/unit_tests
# To run a specific test:
TEST_FILE=tests/unit_tests/test_imports.py make test
集成测试
位置: tests/integration_tests/
集成测试覆盖需要调用外部 API 的逻辑(通常是与其他服务的集成)。
Integration tests require access to external services/provider APIs (which can cost money) and therefore are not run by default.
Not every code change will require an integration test, but keep in mind that we'll require/run integration tests separately as part of our review process.
要求: - 测试与外部服务的真实集成 - 使用环境变量存储 API 密钥 - 如果凭证不可用则优雅地跳过
运行集成测试:
make integration_tests
# Or directly:
uv run --group test --group test_integration pytest --retries 3 --retry-delay 1 tests/integration_tests
# To run a specific test:
TEST_FILE=tests/integration_tests/test_openai.py make integration_tests
代码质量标准
贡献必须符合以下质量要求:
Type hints
必需:为所有函数提供完整的类型注解
def process_documents(
docs: list[Document],
processor: DocumentProcessor,
*,
batch_size: int = 100
) -> ProcessingResult:
"""Process documents in batches.
Args:
docs: List of documents to process.
processor: Document processing instance.
batch_size: Number of documents per batch.
Returns:
Processing results with success/failure counts.
"""
Documentation
必需: Google 风格的文档字符串 用于所有公共函数。
指导原则:文档字符串描述"是什么";此站点的文档解释"如何"和"为什么"。
| 内容类型 | 位置 | 用途 |
|---|---|---|
| 参数类型 | 签名 | 自动生成到 API 参考文档 |
| 参数描述 | 文档字符串 | 自动生成到 API 参考文档 |
| 返回类型和异常 | 文档字符串 | API 参考文档 |
| 最小使用示例 | 文档字符串 | 展示基本实例化模式 |
| 功能教程 | 本站点 | 深入演练 |
| 端到端示例 | 本站点 | 真实使用模式 |
| 概念解释 | 本站点 | 理解和上下文 |
文档字符串应包含:
- One-line summary of what the class/function does
- 链接到本站点以获取教程、指南和使用模式
- 包含类型和描述的参数文档
- 返回值描述
- 可能引发的异常
- Single minimal example showing basic instantiation/usage as necessary
Good docstring example
class ChatAnthropic(BaseChatModel):
"""Interface to Claude chat models.
See the [usage guide](https://docs.langchain.com/oss/python/integrations/chat/anthropic)
for tutorials, feature walkthroughs, and examples.
Args:
model: Model identifier (e.g., `'claude-sonnet-4-6'`).
temperature: Sampling temperature between `0` and `1`.
max_tokens: Maximum number of tokens to generate.
api_key: Anthropic API key.
If not provided, reads from the `ANTHROPIC_API_KEY`
environment variable.
timeout: Request timeout in seconds.
max_retries: Maximum number of retries for failed requests.
Returns:
A chat model instance that can be invoked with messages.
Raises:
ValueError: If the model identifier is not recognized.
AuthenticationError: If the API key is invalid.
Example:
python
from langchain_anthropic import ChatAnthropic
model = ChatAnthropic(model="claude-sonnet-4-6") response = model.invoke("Hello!")
"""
` What does NOT belong in docstrings
避免重复文档字符串中应包含的内容:
- 参数类型:这些位于函数签名中,并自动生成到API参考中。
- 功能教程:不要包含冗长的逐步操作指南,而是链接到本站:
"""
...
See the [extended thinking guide](https://docs.langchain.com/oss/integrations/chat/anthropic#extended-thinking)
for configuration options.
"""
- 多个示例变体:包含一个最小示例,然后链接到综合指南:
"""
Example:
\`\`\`python
message = HumanMessage(content=[
{"type": "image", "url": "https://example.com/image.jpg"}
])
\`\`\`
See the [multimodal guide](https://docs.langchain.com/oss/integrations/chat/anthropic#multimodal)
for all supported input formats.
"""
- 概念性解释:仅保留事实性的参数描述,链接到文档以获取更深入的背景信息。
- **MkDocs特定语法**:避免使用 ???+、折叠面板或标签页在文档字符串中,它们不会在IDE中呈现。
Code style
自动化:通过以下方式进行格式化和检查 ruff
make format # Apply formatting
make lint # Check style and types
标准: - 描述性变量名 - 拆分复杂函数(目标少于20行) - 遵循代码库中现有的模式
依赖项
LangChain 包区分 **硬依赖** 和 **可选依赖** 以保持包的轻量化并减少用户的安装开销。
Optional dependencies
几乎所有新依赖都应该是可选的。使用可选依赖的场景:
- - 该依赖仅在特定集成或功能时才需要
- - 用户可以在没有此依赖的情况下有意义地使用该包
- - 该依赖很大或有很多传递依赖
Requirements:
- - 未安装该依赖的用户必须能够 **导入** 你的代码而没有任何副作用(无警告、无错误、无异常)
- -
pyproject.toml并且uv.lock是 **不** 被修改
添加可选依赖:
1. 将依赖添加到相应的测试依赖文件中(例如, extended_testing_deps.txt) 2. 添加一个至少尝试导入新代码的单元测试。理想情况下,该单元测试使用轻量级 fixture 来测试代码逻辑。 3. 使用 @pytest.mark.requires("package_name") 装饰器来处理需要该依赖的单元测试。
Hard dependencies
硬依赖在用户安装包时会自动安装。仅在以下情况下使用硬依赖:
- - 此包在没有该依赖的情况下根本无法运行
- - 该依赖很小,且具有最少的传递依赖
- - 没有合理的方法使该功能变为可选
添加硬依赖:
1. 提交一个问题或讨论,解释为什么该依赖必须是硬依赖而非可选依赖 2. 将依赖添加到 pyproject.toml 下的相应部分 3. 运行 uv lock 来更新 lockfile 4. 包含覆盖新功能的全面测试
测试编写指南
为了编写有效的测试,需要遵循一些最佳实践:
- - 在文档字符串中使用自然语言描述测试
- - 使用描述性变量名
- - 穷尽地进行断言
Unit tests
def test_document_processor_handles_empty_input():
"""Test processor gracefully handles empty document list."""
processor = DocumentProcessor()
result = processor.process([])
assert result.success
assert result.processed_count == 0
assert len(result.errors) == 0
Integration tests
@pytest.mark.requires("openai")
def test_openai_chat_integration():
"""Test OpenAI chat integration with real API."""
chat = ChatOpenAI()
response = chat.invoke("Hello")
assert isinstance(response.content, str)
assert len(response.content) > 0
Mock usage
def test_retry_mechanism(mocker):
"""Test retry mechanism handles transient failures."""
mock_client = mocker.Mock()
mock_client.call.side_effect = [
ConnectionError("Temporary failure"),
{"result": "success"}
]
service = APIService(client=mock_client)
result = service.call_with_retry()
assert result["result"] == "success"
assert mock_client.call.call_count == 2
提交您的 PR
一旦您的测试通过且代码符合质量标准:
- 推送您的分支并打开拉取请求
- 遵循提供的 PR 模板
- 使用 关闭关键字 (e.g.,
Fixes #123) - 等待 CI 检查完成