> ## 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.

# NVIDIA

> 使用 LangChain Python 与 NVIDIA 集成。

LangChain 和 NVIDIA 在智能体堆栈领域达成合作：

1. [组件](#组件)
2. [基于 OpenShell 的沙箱化智能体](#带有-openshell-的沙箱化智能体)
3. [LangGraph 加速基础组件](#使用-nvidia-加速-langgraph)
4. [NeMo 智能体工具包优化](#基于langsmith-telemetry的nvidia-nemo智能体工具优化)
5. [训练后智能体工作流](#基于训练后的智能体工作流)
6. [基于 NeMo Switchyard 的模型路由](#模型路由与-nemo-switchyard)
7. [完整技术栈蓝图](#全栈架构蓝图)

## 组件

`langchain-nvidia-ai-endpoints` 包提供 LangChain 对话、嵌入、重排序和检索的集成，基于 NVIDIA AI 实现——包括 [Nemotron](https://www.nvidia.com/en-us/ai-data-science/foundation-models/nemotron/)（NVIDIA 为智能体AI设计的开源模型家族）和 [NVIDIA API 目录](https://build.nvidia.com/) 上的数百个社区模型。

模型运行在 NVIDIA NIM 微服务上：通过 TensorRT-LLM 优化的容器镜像，提供符合 OpenAI 兼容标准的 API 接口，在 NVIDIA 硬件上实现峰值吞吐量。可通过托管 API 目录或自建本地化部署访问。

| 组件 | 类型 | 描述 |
| :- | :- | :- |
| 对话 | [`ChatNVIDIA`](#对话：chatnvidia) | 使用 NVIDIA 托管模型或本地 NIM 的对话生成 |
| 对话（Dynamo） | [`ChatNVIDIADynamo`](#对话：chatnvidiadynamo) | 为 Dynamo 部署添加 KV 缓存路由提示的 `ChatNVIDIA` |
| 嵌入 | [`NVIDIAEmbeddings`](#嵌入：nvidiaembeddings) | 用于语义搜索和检索增强生成的密集向量嵌入 |
| 重排序 | [`NVIDIARerank`](#重排序：nvidiarerank) | 根据查询相关性对文档进行重排序 |
| 检索 | [`NVIDIARAGRetriever`](#检索：nvidia-rag检索器) | 从 NVIDIA 检索增强生成蓝图服务器获取检索 |

### 对话：ChatNVIDIA

`ChatNVIDIA` 支持在 NVIDIA 托管模型和本地 NIM 部署上实现对话生成，提供工具调用、结构化输出、图像输入和流式输出功能。

#### 安装

```bash theme={null}
pip install -qU langchain-nvidia-ai-endpoints
```

#### 访问 NVIDIA API 目录

1. 在 [NVIDIA API 目录](https://build.nvidia.com/) 创建免费账户并登录。
2. 点击个人头像，选择 **API Key** > **生成 API Key**。
3. 复制并保存 API Key 为 `NVIDIA_API_KEY`。

```python theme={null}
import getpass
import os

if os.environ.get("NVIDIA_API_KEY", "").startswith("nvapi-"):
    print("Valid NVIDIA_API_KEY already in environment. Delete to reset")
else:
    nvapi_key = getpass.getpass("NVAPI Key (starts with nvapi-): ")
    assert nvapi_key.startswith(
        "nvapi-"
    ), f"{nvapi_key[:5]}... is not a valid key"
    os.environ["NVIDIA_API_KEY"] = nvapi_key
```

#### Nemotron：智能体AI的明星模型

[Nemotron](https://www.nvidia.com/en-us/ai-data-science/foundation-models/nemotron/) 是 NVIDIA 设计的开源模型家族，采用混合 Mamba-Transformer 架构，支持高达 1M Token 的上下文窗口，在基准测试中表现优异。模型权重、训练数据及实现方案已按 NVIDIA 开源模型许可公开。

```python theme={null}
from langchain_nvidia_ai_endpoints import ChatNVIDIA

# Nemotron 3 Ultra - frontier reasoning and agentic workflows
llm = ChatNVIDIA(model="nvidia/nemotron-3-ultra-550b-a55b")
result = llm.invoke("Plan a three-step research workflow for competitive analysis.")
print(result.content)
```

查看 [`ChatNVIDIA` 集成页面](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/chat/nvidia_ai_endpoints) 获取完整文档，包括工具调用、多模态输入和 Nemotron 专用示例。

关于 Nemotron 3.5 Super VL，请参考 [`ChatNVIDIA` Super VL 示例](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/chat/nvidia_ai_endpoints#使用-nemotron-3-5-super-vl)。

### 对话：ChatNVIDIADynamo

`ChatNVIDIADynamo` 是 `ChatNVIDIA` 的 drop-in 替代方案，专为 [NVIDIA Dynamo](https://developer.nvidia.com/dynamo) 部署设计。该组件自动为每个请求注入 KV 缓存路由提示，使 Dynamo 调度器能优化内存分配、负载路由和请求优先级。

```python theme={null}
from langchain_nvidia_ai_endpoints import ChatNVIDIADynamo

llm = ChatNVIDIADynamo(
    base_url="http://localhost:8099/v1",
    model="nvidia/nemotron-3-ultra-550b-a55b",
    osl=512,             # expected output sequence length (tokens)
    iat=250,             # expected inter-arrival time (ms)
    latency_sensitivity=1.0,
    priority=1,
)
result = llm.invoke("Summarize KV cache routing in one sentence.")
print(result.content)
```

查看 [`ChatNVIDIA` 集成页面](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/chat/nvidia_ai_endpoints#与-nvidia-dynamo-配合使用) 获取完整 `ChatNVIDIADynamo` 参考文档，包括单次调用覆盖和流式输出。

### 嵌入：NVIDIAEmbeddings

`NVIDIAEmbeddings` 生成用于语义搜索和检索增强生成的密集向量嵌入。

```python theme={null}
from langchain_nvidia_ai_endpoints import NVIDIAEmbeddings

embedder = NVIDIAEmbeddings(model="NV-Embed-QA")
embedder.embed_query("What's the temperature today?")
```

查看 [`NVIDIAEmbeddings` 集成页面](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/embeddings/nvidia_ai_endpoints) 获取完整文档。

### 重排序：NVIDIARerank

`NVIDIARerank` 使用 NeMo 检索增强生成蓝图服务器中的 NIM 微服务对文档列表进行重排序。

```python theme={null}
from langchain_core.documents import Document
from langchain_nvidia_ai_endpoints import NVIDIARerank

ranker = NVIDIARerank(model="nvidia/llama-3.2-nv-rerankqa-1b-v1")
docs = ranker.compress_documents(
    query="What is GPU memory bandwidth?",
    documents=[Document(page_content=p) for p in passages],
)
```

### 检索：NVIDIA RAG检索器

`NVIDIARAGRetriever` 将 LangChain 连接到正在运行的 [NVIDIA RAG Blueprint](https://docs.nvidia.com/rag/latest/index.html) 服务器，并通过 `/v1/search` 端点检索相关文档。它支持重排序、查询重写和元数据过滤。

```python theme={null}
from langchain_nvidia_ai_endpoints import NVIDIARAGRetriever

retriever = NVIDIARAGRetriever(base_url="http://localhost:8081", k=4)
docs = retriever.invoke("What is NVIDIA NIM?")
```

见 [`NVIDIARAGRetriever` 集成页面](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/retrievers/nvidia) 获取完整文档。

### 使用 NVIDIA NIM 微服务自托管

当您准备好部署 AI 应用程序时，可以通过 NVIDIA NIM 自托管模型。更多详情请参考 [NVIDIA NIM 微服务](https://www.nvidia.com/en-us/ai-data-science/products/nim-microservices/)。

```python theme={null}
from langchain_nvidia_ai_endpoints import ChatNVIDIA, NVIDIAEmbeddings, NVIDIARerank

# connect to a chat NIM running at localhost:8000, specifying a model
llm = ChatNVIDIA(base_url="http://localhost:8000/v1", model="nvidia/nemotron-3-ultra-550b-a55b")

# connect to an embedding NIM running at localhost:8080
embedder = NVIDIAEmbeddings(base_url="http://localhost:8080/v1")

# connect to a reranking NIM running at localhost:2016
ranker = NVIDIARerank(base_url="http://localhost:2016/v1")
```

## 带有 OpenShell 的沙箱化智能体

[OpenShell](https://github.com/NVIDIA/OpenShell) 为 LangChain 智能体提供受策略约束的 Linux 沙箱环境，支持代码执行、文件访问、进程权限和网络出站。这对需要检查数据、编写代码、运行命令或使用工具与本地资源交互的深度智能体非常有用，同时保持执行环境与宿主隔离。

为 LangChain 应用适配 OpenShell 的 [`langchain-nvidia-openshell`](https://github.com/langchain-ai/langchain-nvidia/tree/main/libs/openshell) 包支持深度智能体的沙箱接口。智能体可在宿主上通过 `ChatNVIDIA` 运行，而工具执行则通过 `OpenShellSandbox` 后端调度至 OpenShell 沙箱。

资源：

* [LangChain NVIDIA 示例](https://github.com/langchain-samples/langchain-nvidia-samples) 包含可运行的 NVIDIA 示例，包括 OpenShell 事件分析智能体。
* [OpenShell 深度智能体](https://github.com/langchain-ai/openshell-deepagent) 是基于 NVIDIA Nemotron 的参考编码智能体，在 OpenShell 沙箱内由深度智能体编排运行。
* [`langchain-nvidia-openshell`](https://github.com/langchain-ai/langchain-nvidia/tree/main/libs/openshell) 提供 Python 适配器、配置说明、策略指南和沙箱化深度智能体的笔记本操作指南。

```python theme={null}
import openshell
from deepagents import create_deep_agent
from langchain_nvidia_ai_endpoints import ChatNVIDIA
from langchain_nvidia_openshell import OpenShellSandbox

with openshell.Sandbox() as sandbox:
    backend = OpenShellSandbox(sandbox=sandbox)
    agent = create_deep_agent(
        model=ChatNVIDIA(model="nvidia/nemotron-3-ultra-550b-a55b"),
        system_prompt="You are a careful coding agent.",
        backend=backend,
    )
```

## 使用 NVIDIA 加速 LangGraph

`langchain-nvidia-langgraph` 包为 LangGraph 图提供 NVIDIA 优化执行策略，编译时应用两种互补优化：

* **并行执行**：自动识别并并行运行独立节点，消除不必要的顺序瓶颈。
* **推测执行**：条件分支的两个分支同时执行，根据路由条件决议后丢弃错误分支。

两种优化均无需修改节点逻辑或图边定义。

### 安装

```bash theme={null}
pip install -qU langchain-nvidia-langgraph
```

### 并行执行

将 LangGraph 的 `StateGraph` 替换为 `StateGraph`（来自 `langchain_nvidia_langgraph.graph`）。其余图定义保持不变。

```python theme={null}
from langchain_nvidia_langgraph.graph import StateGraph, OptimizationConfig
from langgraph.graph import END
from typing import TypedDict

class AgentState(TypedDict):
  ...

graph = StateGraph(AgentState)
app = graph.compile(optimization=OptimizationConfig(enable_parallel=True))
```

或对现有 `StateGraph` 进行封装：

```
from langgraph.graph import StateGraph as LangGraphStateGraph
graph = LangGraphStateGraph(AgentState)
app = with_app_compile(graph).compile(optimization=OptimizationConfig(enable_parallel=True))
```

装饰器可显式控制参与优化的节点：

```python theme={null}
from langchain_nvidia_langgraph.graph import sequential, depends_on, speculation_unsafe

# Prevent a node from being parallelized (e.g., it writes to shared state)
@sequential
def write_to_db(state):
    ...

# Declare a dependency not expressed in graph edges
@depends_on("write_to_db")
def next_action(state):
    ...
```

### 推测执行

编译时通过 `OptimizationConfig` 启用推测。执行器并行运行条件分支，仅保留符合路由决议的结果。

```python theme={null}
app = graph.compile(optimization=OptimizationConfig(enable_speculation=True))
```

## 基于LangSmith Telemetry的NVIDIA NeMo智能体工具优化

NVIDIA NeMo 智能体工具包是开源 AI 工具包，用于构建、 профилирование（注：此处原文为俄语，根据上下文推测应为“分析”或“监控”）和优化智能体。开发者可通过 LangChain 与 NeMo 智能体工具包进行最小化代码修改，启用性能分析、评估、GPU 资源规划及自动化优化。NeMo 智能体工具包与 LangSmith 兼容。

* [使用 NeMo Agent 工具包和 LangChain 启动](https://github.com/NVIDIA/NeMo-Agent-Toolkit/blob/develop/examples/frameworks/auto_wrapper/langchain_deep_research/langgraph_deep_research.ipynb)

* [通过 NeMo Agent 工具包和 LangSmith 优化 LangChain](https://github.com/NVIDIA/NeMo-Agent-Toolkit/blob/develop/docs/source/run-workflows/observe/observe-workflow-with-langsmith.md)

## 基于训练后的智能体工作流

NVIDIA NeMo Gym 提供了针对训练后智能体系统的后训练工作流，包含 LangGraph 智能体与响应 API 风格的训练数据和评估循环示例。当您希望通过提示词优化和调优来提升智能体行为表现（特别是工具调用和多步推理任务）时，请使用这些工作流。

* [NeMo Gym LangGraph 智能体示例](https://github.com/NVIDIA-NeMo/Gym/tree/main/responses_api_agents/langgraph_agent)

## 模型路由与 NeMo Switchyard

实验性 [`langchain-nvidia-switchyard`](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/middleware/nvidia#使用nemo-switchyard进行模型路由) 包使用 [NeMo Switchyard](https://github.com/NVIDIA-NeMo/Switchyard) 算法，允许深度智能体将每个模型调用路由到现有的 LangChain 对话模型中。通过该集成，可以在单个智能体后端整合高效且功能强大的模型，同时由 Deep Agents 继续管理智能体循环、工具、状态和中间件。

该集成提供以下功能：

* **模型无关的目标**：将任何 LangChain `BaseChatModel` 转换为 Switchyard 目标
* **可插拔的路由**：通过安装的 `nemo-switchyard` Python 绑定提供任意路由算法，包括 LLM 任务分类和信号驱动阶段路由
* **智能体兼容的中间件**：在路由模型调用时保留 Deep Agents 工具绑定、回调、LangChain 追踪和结构化输出
* **决策元数据**：检查选中的模型并记录每条路由返回的 `AIMessage` 的完整顺序路由轨迹

### 从源码安装

需要 Python 3.12 或更高版本。从 Switchyard 源码树构建 `libsy` Python 绑定，然后通过安装 OpenRouter 和 Deep Agents 依赖项来集成：

```bash theme={null}
git clone https://github.com/NVIDIA-NeMo/Switchyard.git
python -m pip install -e ./Switchyard

git clone https://github.com/langchain-ai/langchain-nvidia.git
python -m pip install -e "./langchain-nvidia/libs/switchyard[openrouter]"
```

### 路由深度智能体

创建两个 LangChain 对话模型，将其封装为 Switchyard 目标，并通过 `SwitchyardRoutingMiddleware` 传递路由算法。传递给 `stage_router` 的目标顺序至关重要：先传递功能强大的目标，再传递高效的目标。

```python theme={null}
from deepagents import create_deep_agent
from langchain_openrouter import ChatOpenRouter

from switchyard.libsy import LlmTarget, algorithms
from langchain_nvidia_switchyard import LangChainLlmClient, SwitchyardRoutingMiddleware

efficient_model = ChatOpenRouter(model="nvidia/nemotron-3-ultra-550b-a55b")
capable_model = ChatOpenRouter(model="anthropic/claude-sonnet-4.6")

router = algorithms.stage_router(
    LlmTarget("capable", LangChainLlmClient(capable_model)),
    LlmTarget("efficient", LangChainLlmClient(efficient_model)),
    picker="efficient_first",
    confidence_threshold=0.5,
    recent_window=3,
)

agent = create_deep_agent(
    model=efficient_model,
    middleware=[SwitchyardRoutingMiddleware(router)],
)

result = await agent.ainvoke({
    "messages": [
        {
            "role": "user",
            "content": "Summarize the important files in this project.",
        }
    ]
})
```

对于高级路由配置、支持的请求/响应数据以及当前限制，请参考 [`langchain-nvidia-switchyard` 包 README](https://github.com/langchain-ai/langchain-nvidia/tree/main/libs/switchyard#readme)。

## 全栈架构蓝图

NVIDIA 和 LangChain 合作开发了 [完整架构示例](https://github.com/langchain-ai/deepagents/tree/main/examples)，展示了这些组件在两个企业级用例中的整合方案，重点关注生产就绪性：

* [NVIDIA AI-Q](https://github.com/NVIDIA-AI-Blueprints/aiq/tree/develop) 是使用 LangChain Deep Agents 在企业数据源中进行深度研究的架构蓝图
* [NVIDIA VSS](https://github.com/NVIDIA-AI-Blueprints/video-search-and-summarization) 是使用 LangChain 和 LangGraph 实现视频搜索与摘要的架构蓝图

## 其他资源

* [`langchain-nvidia-ai-endpoints` 包 README](https://github.com/langchain-ai/langchain-nvidia/blob/main/libs/ai-endpoints/README.md)
* [`langchain-nvidia-langgraph` 包](https://github.com/langchain-ai/langchain-nvidia/tree/main/libs/langgraph)
* [`langchain-nvidia-switchyard` 包](https://github.com/langchain-ai/langchain-nvidia/tree/main/libs/switchyard)
* [Nemotron 模型家族](https://www.nvidia.com/en-us/ai-data-science/foundation-models/nemotron/)
* [`langchain-nvidia-openshell` 包](https://github.com/langchain-ai/langchain-nvidia/tree/main/libs/openshell)
* [LangChain NVIDIA 示例](https://github.com/langchain-samples/langchain-nvidia-samples)
* [OpenShell 深度智能体](https://github.com/langchain-ai/openshell-deepagent)
* [NeMo Gym LangGraph 智能体示例](https://github.com/NVIDIA-NeMo/Gym/tree/main/responses_api_agents/langgraph_agent)
* [NVIDIA NIM 大语言模型（LLM）概述](https://docs.nvidia.com/nim/large-language-models/latest/introduction.html)
* [NeMo 检索嵌入 NIM 概述](https://docs.nvidia.com/nim/nemo-retriever/text-embedding/latest/overview.html)
* [NeMo 检索重排序 NIM 概述](https://docs.nvidia.com/nim/nemo-retriever/text-reranking/latest/overview.html)
* [`ChatNVIDIA` 模型](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/chat/nvidia_ai_endpoints)
* [`NVIDIAEmbeddings` RAG 工作流模型](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/embeddings/nvidia_ai_endpoints)
* [`NVIDIARAGRetriever`](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/retrievers/nvidia)
* [NVIDIA Dynamo](https://developer.nvidia.com/dynamo)

***

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


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