> ## Documentation Index
> Fetch the complete documentation index at: https://langchain-docs-zh.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# 贡献代码

> 欢迎代码贡献！无论你是修复 Bug、添加功能还是提升性能，你的贡献都将帮助为成千上万的开发者提供更好的开发者体验。

欢迎代码贡献！无论你是修复 Bug、添加功能还是提升性能，你的贡献都将帮助为成千上万的开发者提供更好的开发者体验。

## 入门指南

如果你在寻找可以着手的工作，请查看我们仓库中标记为 "help wanted" 的问题：

:::python

> [card] [LangChain](https://github.com/langchain-ai/langchain/labels?q=help+wanted)
>
> 标签

> [card] [LangGraph](https://github.com/langchain-ai/langgraph/labels?q=help+wanted)
>
> 标签

> [card] [Deep Agents](https://github.com/langchain-ai/deepagents/labels?q=help+wanted)
>
> 标签

:::
:::js

> [card] [LangChain](https://github.com/langchain-ai/deepagents/labels?q=help+wanted)
>
> 标签

> [card] [LangGraph](https://github.com/langchain-ai/langgraphjs/labels?q=help+wanted)
>
> 标签

> [card] [Deep Agents](https://github.com/langchain-ai/deepagentsjs/labels?q=help+wanted)
>
> 标签

:::

> [!NOTE]
>
> 在提交大型 **新功能或重构** 之前，请先打开一个问题或发布到 [论坛](https://forum.langchain.com/) 进行讨论。这确保了与项目目标的保持一致，并防止重复工作。

### 快速修复：提交 Bug 修复

对于简单的 Bug 修复，你可以立即开始：

**1. Reproduce the issue**

在克隆仓库之前，请确保你能可靠地复现 Bug。这有助于确认问题并提供修复的起点。维护者和其他贡献者应该能够根据你的描述复现问题，而无需额外的设置或修改。

**2. Fork the repository**

:::python
将 [LangChain](https://github.com/langchain-ai/langchain)、[LangGraph](https://github.com/langchain-ai/langgraph) 或 [Deep Agents](https://github.com/langchain-ai/deepagents) 仓库 fork 到你的 个人 GitHub 账户 (If you fork to an organization account, maintainers will be unable to make edits, which may significantly delay acceptance.)
:::
:::js
将 [LangChain](https://github.com/langchain-ai/langchainjs)、[LangGraph](https://github.com/langchain-ai/langgraphjs) 或 [Deep Agents](https://github.com/langchain-ai/deepagentsjs) 仓库 fork 到你的 个人 GitHub 账户 (If you fork to an organization account, maintainers will be unable to make edits, which may significantly delay acceptance)
:::

**3. Clone and setup**

:::python

```bash theme={null}
git clone https://github.com/your-username/name-of-forked-repo.git

# For instance, for LangChain:
git clone https://github.com/parrot123/langchain.git
```

> [!WARNING]
>
> LangChain Python 仓库是一个 **单体仓库** — 仓库根目录下没有 `pyproject.toml`。每个包都有自己的 `libs/`（例如 `libs/core/`、`libs/langchain/`、`libs/partners/openai/`）。在运行 `uv` 命令之前，你必须 `cd` 到相关的包目录。

```bash theme={null}
# Navigate into the package you want to work on, then install dependencies
cd libs/core          # or libs/langchain, libs/partners/openai, etc.
uv sync --all-groups

# or, to install a specific group only:
uv sync --group test
```

如果你之前没有安装 [`uv`](https://docs.astral.sh/uv/)，则需要安装。请参阅 [仓库结构](#仓库结构) 部分以获取所有包及其位置的完整列表。
:::
:::js

```bash theme={null}
git clone https://github.com/your-username/name-of-forked-repo.git

# For instance, for LangChain:
git clone https://github.com/parrot123/langchainjs.git

# For LangGraph:
git clone https://github.com/parrot123/langgraphjs.git
```

```bash theme={null}
# Inside your repo, install dependencies
pnpm install
# Create a build for all packages to resolve workspace dependencies
pnpm build
```

:::

**4. Create a branch**

为你的修复创建一个新的分支。这有助于组织你的更改，并使后续提交拉取请求变得更容易。

```bash theme={null}
git checkout -b your-username/short-bugfix-name
```

**5. Write failing tests**

添加 [单元测试](#测试编写规范)，这些测试在没有你的修复的情况下会失败。这允许我们验证 Bug 是否已解决，并防止回归

**6. Make your changes**

在遵循我们 [代码质量标准](#代码质量标准) 的情况下修复 Bug。进行 **最小必要的更改** 以解决问题。我们强烈建议贡献者在开始编码之前在问题下评论。例如：

> *"我想处理这个问题。我的预期方法是 \[...简短描述...]。这符合维护者的期望吗？"*\*

一句 30 秒的评论通常可以防止如果你最初的方案是错误的情况下浪费精力。

:::js

**7. Run build**

运行构建命令以确保包仍然可以正常构建

```bash theme={null}
pnpm build
# or build a specific workspace package
pnpm --filter @langchain/core build
```

:::

**8. Verify the fix**

确保测试通过且没有引入回归。在提交 PR 之前，请确保本地所有测试都通过

:::python

```bash theme={null}
make format
make lint
make test

# For bugfixes involving integrations, also run:
make integration_tests
# (You may need to set up API testing credentials)
```

:::
:::js

```bash theme={null}
pnpm lint
pnpm test

# For bugfixes involving integrations, also run:
pnpm test:int

# Or run tests in a specific workspace package
cd libs/langchain-core
pnpm test
pnpm lint

# Or run tests for a specific package from the root of the repo
pnpm --filter @langchain/core test
pnpm --filter @langchain/core lint
```

:::

**9. Document the change**

如果行为发生变化，请更新 docstrings 和/或行内注释

**10. Submit a pull request**

遵循提供的 PR 模板。如果适用，使用 [关闭关键词](https://docs.github.com/en/issues/tracking-your-work-with-issues/using-issues/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword)（例如 `Fixes #ISSUE_NUMBER`）引用你正在修复的问题，以便在 PR 合并时自动关闭该问题。

### 完整开发环境设置

对于持续开发或更大的贡献：

1. 查看我们的 [贡献指南](#贡献指南)，了解功能、Bug 修复和集成
2. 按照 [设置指南](#开发环境) 下方我们的指南设置你的环境
3. 了解 [仓库结构](#仓库结构) 和包组织
4. 学习我们的 [开发工作流](#开发流程)，包括测试和代码检查

***

## 贡献指南

在为LangChain项目贡献之前，请花时间思考你贡献的目的。如果你的唯一目标只是为简历添加一个"首次贡献"（或只是寻找快速胜利），你可能更适合参加训练营或在线教程。

为开源项目做贡献需要时间和精力，但也能帮助你成为更好的开发者并学习新技能。不过需要知道，这可能会比参加培训课程更难更慢。但只要愿意投入时间做好每件事，贡献开源项目就值得！

### 向后兼容性

> [!WARNING]
>
> 公共API的破坏性变更仅允许在关键安全修复时进行。
>
> 关于主要版本发布的详细信息，请参见我们的[版本政策](https://langchain-docs-zh.mintlify.site/langchain/oss/versioning.md)。

通过以下方式保持兼容性：

> [accordion] Stable interfaces
>
> **必须始终保留**：
>
> * 函数签名和参数名称
> * 类接口和方法名称
> * 返回值结构和类型
> * 公共API的导入路径

> [accordion] Safe changes
>
> **可接受修改**：
>
> :::python
>
> * 添加新的可选参数
>   :::
>   :::js
> * 添加新的可选参数/类型参数
>   :::
> * 为类添加新方法
> * 不改变行为的前提下优化性能
> * 添加新模块或函数

> [accordion] Before making changes
>
> * **这会破坏现有用户代码吗？**
> * 检查目标是否为公共的
>   :::python
> * 如果需要，是否在`__init__.py`中导出？
>   :::
> * 是否存在测试中的现有使用模式？

### 新功能

我们致力于保持新功能的准入门槛。通常不接受外部贡献者提出的核心抽象类新功能，除非已有明确需求的问题报告。此规则同样适用于基础设施和依赖项变更。

功能贡献要求包括：

**1. Design discussion**

在问题报告中描述：

* 解决的问题
* 建议的API设计
* 预期使用模式

**2. Implementation**

* 遵循现有代码模式
* 提供完整测试和文档
* 考虑安全影响

**3. Integration considerations**

* 与现有功能如何交互？
* 是否有性能影响？
* 是否引入新依赖？

我们会拒绝可能导致安全漏洞或报告的功能。

### 安全指南

> [!WARNING]
>
> 安全至高无上。切勿引入漏洞或危险模式。

安全检查清单：

> [accordion] Input validation
>
> * 验证并净化所有用户输入
> * 正确转义模板和查询中的数据
>   :::python
> * 用户数据中永不使用`eval()`、`exec()`或`pickle`，这可能导致任意代码执行漏洞
>   :::
>   :::js
> * 用户数据中永不使用`eval()`，这可能导致任意代码执行漏洞
>   :::

> [accordion] Error handling
>
> * 使用特定异常类型
> * 错误信息中不暴露敏感信息
> * 实现正确的资源清理

> [accordion] Dependencies
>
> * 避免添加硬依赖
> * 保持可选依赖最小化
> * 审查第三方包的安全问题

***

## 开发环境

> [!TIP]
>
> **使用AI编程代理？**
>
> * 安装[LangChain文档MCP服务器](https://langchain-docs-zh.mintlify.site/use-these-docs)，让代理访问最新LangChain文档和示例。
>
>   连接LangChain文档MCP服务器
>
>   将LangChain文档MCP服务器与我的编程智能体连接，使其能够查询最新的LangChain、LangGraph和LangSmith文档及API参考。
>
>   需添加的服务器：
>
>   * `docs-langchain`: [https://docs.langchain.com/mcp](https://docs.langchain.com/mcp)
>   * `reference-langchain`: [https://reference.langchain.com/mcp](https://reference.langchain.com/mcp)
>
>   检测我正在使用的智能体或编辑器（Claude代码、Cursor、Codex CLI、Claude桌面、Deep Agents代码、VS Code、Antigravity或其他MCP兼容客户端），并从[https://docs.langchain.com/use-these-docs.md获取对应配置：](https://docs.langchain.com/use-these-docs.md获取对应配置：)
>
>   * Claude代码：使用`claude mcp add --transport http`为每个服务器（默认项目级访问；仅在要求全局访问时使用`--scope user`）
>   * Codex CLI：使用`codex mcp add`与每个服务器URL
>   * Cursor、Deep Agents代码、VS Code或Antigravity：将两个条目合并到MCP设置JSON中，使用页面中显示的对应客户端字段名称
>   * Claude桌面：在Settings > Connectors下添加两个URL
>
>   不要编造MCP URL。配置完成后确认两个服务器均被列出且可访问。
> * 安装[LangChain技能](https://github.com/langchain-ai/langchain-skills)提升代理在LangChain生态中的任务处理性能，然后点击右上角**复制页面**按钮，将原始内容粘贴到代理中以自动配置环境。
>
>   安装 LangChain 技能
>
>   为我的编码智能体安装 LangChain 技能，以便它在 LangChain、LangGraph 和 Deep Agents 任务上表现更好。
>
>   使用 [https://github.com/langchain-ai/langchain-skills](https://github.com/langchain-ai/langchain-skills) 上的智能体技能安装程序：
>
>   ```bash theme={null}
>   npx skills add langchain-ai/langchain-skills --skill '*' --yes
>   ```
>
>   如果改为请求全局安装，请使用：
>
>   ```bash theme={null}
>   npx skills add langchain-ai/langchain-skills --skill '*' --yes --global
>   ```
>
>   检测您正在使用哪个智能体或编辑器。如果您使用 Claude Code 并偏好插件路径，请从该仓库的 README 文件中遵循市场安装方法（`/plugin marketplace add` 然后 `/plugin install`）。不要编造替代的技能包名称或安装 URL。安装完成后，确认这些技能对智能体可用。

:::python
我们的Python项目使用[`uv`](https://docs.astral.sh/uv/getting-started/installation/)进行依赖管理。请确保已安装最新版本。

> [!NOTE]
>
> 我们致力于保持Python包的配置一致性。从包目录运行：
>
> ```bash theme={null}
> uv sync --all-groups
> make test  # Verify unit tests pass before starting development
> ```

:::
:::js

> [!WARNING]
>
> 我们的JS/TS项目使用[`pnpm`](https://pnpm.io/)进行依赖管理。请确保已安装最新版本，或运行`corepack enable`（Node 24+）设置所需pnpm版本。

> [!NOTE]
>
> 我们致力于保持JS/TS包的配置一致性。从仓库根目录运行：
>
> ```bash theme={null}
> pnpm install
> pnpm --filter {package-name} test  # Verify tests pass before starting development
> ```

:::

在阅读[贡献指南](#贡献指南)后，在[仓库结构](#仓库结构)部分的下方找到你要工作的组件对应的包目录。

***

## 仓库结构

> [tab] LangChain
>
> LangChain采用单仓库多包组织方式：
>
> > [accordion] Core packages
> >
> > :::python
> >
> > * **[`langchain`](https://github.com/langchain-ai/langchain/tree/master/libs/langchain#readme)**（位于`libs/langchain/`）：主包包含链、智能体和检索逻辑
> > * **[`langchain-core`](https://github.com/langchain-ai/langchain/tree/master/libs/core#readme)**（位于`libs/core/`）：基础接口和核心抽象
> >   :::
> >   :::js
> > * **[`langchain`](https://github.com/langchain-ai/langchainjs/tree/main/libs/langchain#readme)**（位于`libs/langchain/`）：主包包含链、智能体和检索逻辑
> > * **[`@langchain/core`](https://github.com/langchain-ai/langchainjs/tree/main/libs/langchain-core#readme)**（位于`libs/langchain-core/`）：基础接口和核心抽象
> >   :::
>
> > [accordion] Partner packages
> >
> > 位于`libs/partners/`的独立版本包用于特定集成。例如：
> >
> > * **[`langchain-openai`](https://github.com/langchain-ai/langchain/tree/master/libs/partners/openai#readme)**：[OpenAI](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/providers/openai.md)集成
> > * **[`langchain-anthropic`](https://github.com/langchain-ai/langchain/tree/master/libs/partners/anthropic#readme)**：[Anthropic](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/providers/anthropic.md)集成
> > * **[`langchain-google-genai`](https://github.com/langchain-ai/langchain-google/)**：[Google Generative AI](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/chat/google_generative_ai.md)集成
> >
> > 许多合作伙伴包位于外部仓库中。请查阅 [集成列表](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/providers/overview.md) 获取详细信息。
> > :::
> > :::js
> > 这些位于 `libs/providers/` 的包为特定集成提供独立版本控制。例如：
> >
> > * **[`@langchain/openai`](https://github.com/langchain-ai/langchainjs/tree/main/libs/providers/langchain-openai#readme)**: [OpenAI](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/providers/openai.md) 集成
> > * **[`@langchain/anthropic`](https://github.com/langchain-ai/langchainjs/tree/main/libs/providers/langchain-anthropic#readme)**: [Anthropic](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/providers/anthropic.md) 集成
> > * **[`@langchain/google`](https://github.com/langchain-ai/langchainjs/tree/main/libs/providers/langchain-google#readme)**: [Google](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/providers/google.md) 集成
> >   :::
>
> > [accordion] Supporting packages
> >
> > :::python
> >
> > * **[`langchain-text-splitters`](https://github.com/langchain-ai/langchain/tree/master/libs/text-splitters#readme)**: 文本分割工具
> > * **[`langchain-standard-tests`](https://github.com/langchain-ai/langchain/tree/master/libs/standard-tests#readme)**: 集成标准测试套件
> >   :::
> >   :::js
> > * **[`@langchain/textsplitters`](https://github.com/langchain-ai/langchainjs/tree/main/libs/langchain-textsplitters#readme)**: 文本分割工具
> > * **[`@langchain/standard-tests`](https://github.com/langchain-ai/langchainjs/tree/main/internal/standard-tests#readme)**: 集成标准测试套件
> > * **[`@langchain/community`](https://github.com/langchain-ai/langchainjs-community/tree/main/libs/community)**: 社区维护的集成（独立仓库）
> >   :::

> [tab] LangGraph
>
> LangGraph 采用单一仓库多Python包架构：
>
> > [accordion] Core packages
> >
> > * **[`langgraph`](https://github.com/langchain-ai/langgraph/tree/main/libs/langgraph#readme)**（位于 `libs/langgraph/`）：构建状态感知、多智能体系统的核心框架
> > * **[`langgraph-prebuilt`](https://github.com/langchain-ai/langgraph/tree/main/libs/prebuilt#readme)**（位于 `libs/prebuilt/`）：创建和管理智能体与工具的高阶API
>
> > [accordion] Checkpoint packages
> >
> > * **[`langgraph-checkpoint`](https://github.com/langchain-ai/langgraph/tree/main/libs/checkpoint#readme)**（位于 `libs/checkpoint/`）：检查点保存器基础接口
> > * **[`langgraph-checkpoint-postgres`](https://github.com/langchain-ai/langgraph/tree/main/libs/checkpoint-postgres#readme)**（位于 `libs/checkpoint-postgres/`）：PostgreSQL实现
> > * **[`langgraph-checkpoint-sqlite`](https://github.com/langchain-ai/langgraph/tree/main/libs/checkpoint-sqlite#readme)**（位于 `libs/checkpoint-sqlite/`）：SQLite实现
>
> > [accordion] SDK and CLI
> >
> > * **[`langgraph-sdk`](https://github.com/langchain-ai/langgraph/tree/main/libs/sdk-py#readme)**（位于 `libs/sdk-py/`）：Agent Server API的Python SDK
> > * **[`langgraph-cli`](https://github.com/langchain-ai/langgraph/tree/main/libs/cli#readme)**（位于 `libs/cli/`）：官方命令行界面

> [tab] Deep Agents
>
> Deep Agents 采用单一仓库多Python包架构：
>
> > [accordion] Core packages
> >
> > * **[`deepagents`](https://github.com/langchain-ai/deepagents/tree/main/libs/deepagents#readme)**（位于 `libs/deepagents/`）：集成规划、文件系统和子智能体能力的核心框架
> > * **[`deepagents-code`](https://github.com/langchain-ai/deepagents/tree/main/libs/code#readme)**（位于 `libs/code/`）：Deep Agents代码——支持会话续传、网页搜索和沙盒的交互终端
> > * **[`deepagents-cli`](https://github.com/langchain-ai/deepagents/tree/main/libs/cli#readme)**（位于 `libs/cli/`）：部署工具（`deepagents deploy`, `deepagents init`, `deepagents dev`）用于将智能体部署至LangSmith
>
> > [accordion] Integration packages
> >
> > * **[`deepagents-evals`](https://github.com/langchain-ai/deepagents/tree/main/libs/evals#readme)**（位于 `libs/evals/`）：集成LangSmith追踪的评估套件与Harbor
> > * **[`deepagents-acp`](https://github.com/langchain-ai/deepagents/tree/main/libs/acp#readme)**（位于 `libs/acp/`）：Agent客户端协议集成

***

## 开发流程

### 预提交钩子

:::python
[LangChain](https://github.com/langchain-ai/langchain) 和 [Deep Agents](https://github.com/langchain-ai/deepagents) 仓库包含 [pre-commit](https://pre-commit.com/) 钩子，在每次提交前自动运行格式化、代码检查和验证。从仓库根目录安装：

```bash theme={null}
pip install pre-commit  # or: uv tool install pre-commit
pre-commit install
```

钩子强制要求：

* 禁止直接向受保护分支提交
* YAML和TOML语法验证
* 添加末尾空格和文件末尾修复
* 智能引号和非标准空格规范化
* 按包类型 `make format` 和 `make lint`
  :::

### 运行测试

> [!NOTE]
>
> 测试目录相对于您工作的包位置

我们优先使用单元测试而非集成测试。单元测试在每次拉取请求时运行，因此应快速且可靠。集成测试通过定期调度运行，需要更多环境配置，应保留用于验证与外部服务接口。

#### 单元测试

:::python
**位置**: `tests/unit_tests/`
:::
:::js
**位置**: `src/tests/FILENAME_BEING_TESTED.test.ts`
:::

单元测试覆盖不依赖外部API的模块逻辑。新增逻辑需补充单元测试，并在测试中验证预处理/后处理和模拟外部依赖。

**要求**：

* 禁止网络调用
* 覆盖所有代码路径（含边界情况）
* 使用依赖模拟

运行单元测试：

:::python

```bash theme={null}
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
```

:::
:::js

```bash theme={null}
# Run the entire test suite
pnpm test

# Or run a specific test file
pnpm test src/tests/FILENAME_BEING_TESTED.test.ts

# Or run a specific test function
pnpm test -t "the test that should be run"
```

:::

#### 集成测试

:::python
**位置**: `tests/integration_tests/`
:::
:::js
**位置**: `src/tests/FILENAME_BEING_TESTED.int.test.ts`
:::

集成测试覆盖依赖外部API的逻辑（通常涉及与其他服务集成）。

集成测试需要访问外部服务/API（可能产生费用），因此默认不运行。并非所有代码变更都需要集成测试，但需注意我们会在审核时单独运行集成测试。

**要求**：

* 验证真实外部服务集成
* 使用环境变量存储API密钥
* 密钥缺失时优雅降级

运行集成测试：
:::python

```bash theme={null}
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
```

:::
:::js

```bash theme={null}
pnpm test:int
```

:::

### 代码质量标准

贡献需符合以下要求：

> [tab] Type hints
>
> :::python
> **强制要求**: 所有函数需完整类型注解
>
> ```python theme={null}
> 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.
>     """
> ```
>
> :::
> :::js
> **强制要求**: 所有函数需完整类型定义
>
> ```typescript theme={null}
> function processDocuments(
>     docs: Document[],
>     processor: DocumentProcessor,
>     batchSize: number = 100
> ): ProcessingResult {
>     // ...
> }
> ```
>
> :::

> [tab] Documentation
>
> :::python
> **强制要求**: 所有公共函数需符合 [Google-style docstrings](https://google.github.io/styleguide/pyguide.html)
>
> **指导原则**: 文档字符串描述"是什么"；本站文档解释"如何"和"为什么"。
>
> | 内容类型 | 位置 | 目的 |
> | - | - | - |
> | 参数类型 | 签名 | 自动生成API参考 |
> | 参数描述 | 文档字符串 | 自动生成API参考 |
> | 返回类型和异常 | 文档字符串 | API参考 |
> | 最小使用示例 | 文档字符串 | 展示基础实例化模式 |
> | 功能教程 | 本站 | 深度操作指南 |
> | 端到端示例 | 本站 | 真实场景应用模式 |
> | 概念解释 | 本站 | 理解与上下文 |
>
> **文档字符串应包含:**
>
> 1. 一行总结类/函数的作用
>
> 2. 链接到本站获取教程、指南和使用模式
>
> 3. 参数文档（类型+描述）
>
> 4. 返回值说明
>
> 5. 可能抛出的异常
>
> 6. 必要时展示单个最小示例
>
> > [accordion] Good docstring example
> >
> > ````python theme={null}
> > 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!")
> >         ```
> >     """
> > ````
>
> > [accordion] What does NOT belong in docstrings
> >
> > 避免在文档字符串中重复以下内容：
> >
> > * **参数类型**: 已包含在函数签名并自动生成API参考
> >
> > * **功能教程**: 不包含扩展操作指南，改为链接本站：
> >
> >   ```python theme={null}
> >   """
> >   ...
> >
> >   See the [extended thinking guide](https://docs.langchain.com/oss/integrations/chat/anthropic#extended-thinking)
> >   for configuration options.
> >   """
> >   ```
> >
> > * **多个示例变体**: 包含单个最小示例，链接完整指南：
> >
> >   ```python theme={null}
> >   """
> >   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中不渲染
>
> :::
> :::js
> **必需**: 所有导出的函数和接口需包含[JSDocs](https://jsdoc.app/about-getting-started)
>
> ```typescript theme={null}
> /**
>  * Document processing instance.
>  */
> interface FooDocumentProcessor {
>     /**
>      * Process documents in batches.
>      *
>      * @param docs - List of documents to process.
>      * @returns Processing results with success/failure counts.
>      */
>     process(docs: Document[]): ProcessingResult;
> }
>
> /**
>  * Process documents in batches.
>  *
>  * @param docs - List of documents to process.
>  * @param processor - Document processing instance.
>  * @param batchSize - Number of documents per batch.
>  * @returns Processing results with success/failure counts.
>  */
> export function processDocuments(
>     docs: Document[],
>     processor: DocumentProcessor,
>     batchSize: number = 100
> ): ProcessingResult {
>     // ...
> }
> ```
>
> :::

> [tab] Code style
>
> :::python
> **自动化**: 格式化和类型检查通过[`ruff`](https://docs.astral.sh/ruff/)实现
>
> ```bash theme={null}
> make format  # Apply formatting
> make lint    # Check style and types
> ```
>
> :::
> :::js
> **自动化**: 格式化和类型检查：
>
> ```bash theme={null}
> pnpm lint    # Check style and types
> pnpm format  # Apply formatting
> ```
>
> :::
>
> **规范**:
>
> * 描述性变量名
> * 将复杂函数拆分（每函数少于20行）
> * 遵循代码库现有模式

:::python

### 依赖项

LangChain包通过**强依赖**和**可选依赖**区分，以保持包轻量并减少用户安装开销。

> [tab] Optional dependencies
>
> 大部分新依赖都应设置为可选。在以下情况使用可选依赖：
>
> * 依赖仅用于特定集成或功能
> * 用户无需该依赖仍可正常使用包
> * 依赖体积较大或包含过多传递依赖
>
> **要求：**
>
> * 未安装该依赖的用户必须能**导入**代码而**无任何副作用**（无警告、无错误、无异常）
> * `pyproject.toml` 和 `uv.lock` **未修改**
>
> **添加可选依赖的步骤：**
>
> 1. 将依赖添加到测试依赖文件（如 `extended_testing_deps.txt`）
> 2. 编写至少尝试导入新代码的单元测试。理想情况下，测试使用轻量级假数据验证逻辑
> 3. 对需要依赖的单元测试使用 `@pytest.mark.requires("package_name")` 装饰器

> [tab] Hard dependencies
>
> 硬依赖会在用户安装包时自动安装。仅在以下情况使用硬依赖：
>
> * 包**无法正常工作**
>
> * 依赖体积小且传递依赖极少
>
> * 无合理方式使功能可选项化
>
> > [!WARNING]
> >
> > 添加硬依赖会增加所有用户的安装时间和潜在版本冲突。\
> > 维护者会对硬依赖添加进行严格审查！
>
> **添加硬依赖的步骤：**
>
> 1. 提交议题或讨论说明为何必须使用硬依赖
> 2. 在 `pyproject.toml` 的适当章节添加依赖
> 3. 运行 `uv lock` 更新锁文件
> 4. 编写覆盖新功能的完整测试

:::

***

### 测试编写规范

编写有效测试需遵循以下最佳实践：

:::python

* 使用自然语言在文档字符串中描述测试
* 使用描述性变量名
* 完整覆盖断言\
  :::\
  :::js
* 将测试封装在 `describe` 块中（描述测试的组件）
* 使用自然语言命名测试
* 完整覆盖断言
* 仅对合理大小的数据对象使用快照\
  :::

> [tab] Unit tests
>
> :::python
>
> ```python theme={null}
> 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
> ```
>
> :::js
>
> ```typescript theme={null}
> describe("DocumentProcessor", () => {
>     it("Should handle empty document list", () => {
>         const processor = new DocumentProcessor();
>         const result = processor.process([]);
>
>         expect(result.success).toBe(true);
>         expect(result.processedCount).toBe(0);
>         expect(result.errors).toHaveLength(0);
>     });
> });
> ```
>
> :::

> [tab] Integration tests
>
> :::python
>
> ```python theme={null}
> @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
> ```
>
> :::js
>
> ```typescript theme={null}
> describe("ChatOpenAI", () => {
>     it("Should test with real API", () => {
>         const chat = new ChatOpenAI();
>         const response = chat.invoke("Hello");
>     });
> });
> ```
>
> :::

> [tab] Mock usage
>
> :::python
>
> ```python theme={null}
> 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
> ```
>
> :::js
>
> ```typescript theme={null}
> describe("APIService", () => {
>     it("Should call with retry", () => {
>         const mockClient = new MockClient();
>         const service = new APIService(client: mockClient);
>         const result = service.callWithRetry();
>     });
> });
> ```
>
> :::

### 提交 PR

测试通过且代码符合质量标准后：

1. 推送分支并打开 PR
2. 遵循提供的 PR 模板
3. 使用 [关闭关键词](https://docs.github.com/en/issues/tracking-your-work-with-issues/using-issues/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword) 关联相关议题（如 `Fixes #123`）
4. 等待 CI 检查完成

> [!NOTE]
>
> 若 PR 包含 AI 生成内容，必须遵守我们的 [LLM 可接受用途政策](https://langchain-docs-zh.mintlify.site/langchain/oss/contributing/overview.md#llm-的可接受使用方式)。低质量 AI 生成垃圾 PR 将直接关闭。

> [!WARNING]
>
> 及时修复 CI 失败。维护者可能关闭未通过 CI 的 PR。

## 获取帮助

我们的目标是实现开发者最友好的环境。若遇到初始化问题，请：

* 在 [社区 Slack](https://www.langchain.com/join-community) 中提问
* 在 [论坛发帖](https://forum.langchain.com/)

> [!TIP]
>
> 现在您已准备好为 LangChain 贡献高质量代码！

***

> 官方原文：[src/oss/contributing/code.mdx](https://github.com/langchain-ai/docs/blob/main/src/oss/contributing/code.mdx) · 非官方翻译，译文由 AI 生成，以英文原文为准。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.