以编程方式使用文档

这将帮助您开始使用 NVIDIA 聊天模型。有关所有 ChatNVIDIA 功能和配置的详细文档,请访问 API 参考.

概述

langchain-nvidia-ai-endpoints 包包含由 NVIDIA AI 基础模型驱动的聊天模型和嵌入的 LangChain 集成,托管于 NVIDIA API 目录.

一个很好的起点是 Nemotron,NVIDIA 为代理 AI 专门构建的开源模型系列。Nemotron 模型采用混合 Mamba-Transformer 混合专家架构,在保持领先精度的同时,吞吐量比同类模型高高达 3 倍,上下文窗口最长可达 1M token。模型权重、训练数据和实现配方根据 NVIDIA 开源模型许可证公开发布。

NVIDIA AI 基础模型运行在 NIM 微服务上:通过 NVIDIA NGC 目录 分发的容器镜像暴露标准 OpenAI 兼容 API,并使用 TensorRT-LLM 优化以实现最大吞吐量。可通过托管的 NVIDIA API 目录 访问,或使用 NVIDIA AI Enterprise 许可证进行本地部署。

本页面介绍如何通过 ChatNVIDIA与 NVIDIA 模型交互,包括 Nemotron 和 API 目录中的其他模型。

有关通过此 API 访问嵌入模型的更多信息,请参阅 NVIDIAEmbeddings documentation.

集成详情

可序列化JS 支持下载量版本
ChatNVIDIAlangchain-nvidia-ai-endpointsbeta!PyPI - 下载量!PyPI - 版本

模型功能

工具调用结构化输出图像输入音频输入视频输入Token 级流式输出原生异步Token 使用量对数概率

安装包

pip install -qU langchain-nvidia-ai-endpoints

访问 NVIDIA API 目录

要获取 NVIDIA API 目录的访问权限,请执行以下操作:

  1. NVIDIA API 目录 上创建一个免费账户并登录。
  2. 点击您的个人资料图标,然后点击 **API 密钥**。将显示 **API 密钥** 页面。
  3. 点击 **生成 API 密钥**. **生成 API 密钥** 窗口出现。
  4. 点击 **生成密钥**。您应该看到 **API 密钥已授予**,您的密钥会出现。
  5. 复制并保存密钥为 NVIDIA_API_KEY.
  6. 要验证您的密钥,请使用以下代码。
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

您现在可以使用您的密钥访问 NVIDIA API 目录上的端点。

要启用模型调用的自动化追踪,请设置您的 LangSmith API 密钥:

os.environ["LANGSMITH_TRACING"] = "true"
os.environ["LANGSMITH_API_KEY"] = getpass.getpass("Enter your LangSmith API key: ")

实例化

现在我们可以访问 NVIDIA API 目录中的模型。 Nemotron 模型是代理和推理工作负载的推荐起点:

from langchain_nvidia_ai_endpoints import ChatNVIDIA

# Nemotron 3 Nano — efficient reasoning and agentic tasks
llm = ChatNVIDIA(model="nvidia/nemotron-3-super-120b-a12b")

通过传递模型 ID,可以使用 API 目录中的任何其他模型:

llm = ChatNVIDIA(model="mistralai/mixtral-8x7b-instruct-v0.1")

调用

result = llm.invoke("Write a ballad about LangChain.")
print(result.content)

启用思考模式

某些 NVIDIA 推理模型支持可配置的思考模式。通过传递 thinking_mode=True to invoke:

from langchain_nvidia_ai_endpoints import ChatNVIDIA

model = ChatNVIDIA(model="nvidia/nemotron-3-nano-30b-a3b")

response = model.invoke("Solve this step by step: 17 * 23", thinking_mode=True)
print(response.content_blocks)

在单次请求中启用思考: with_thinking_mode 当您需要一个启用思考的可复用可运行对象时使用:

thinking_model = model.with_thinking_mode(enabled=True)
response = thinking_model.invoke("Solve this step by step: 17 * 23")

要列出已知支持思考模式的模型,请调用 get_available_models 并检查 supports_thinking。这会查询 NVIDIA 模型列表 API,然后过滤返回的模型元数据:

thinking_models = [
    model for model in ChatNVIDIA.get_available_models() if model.supports_thinking
]

ChatNVIDIAthinking_mode=True 转换为所选模型所需的控制机制。某些模型使用请求参数,例如 chat_template_kwargs={"enable_thinking": True}。其他模型使用基于提示的控制,LangChain 会将模型特定的思考前缀附加到系统消息,或在不存在系统消息时创建一个。如果为模型同时配置了两种机制,则请求参数优先。

不要在构造 thinking_mode=True 时传递 ChatNVIDIA。未知的构造函数参数会变成原始 model_kwargs,这些参数会直接合并到 API 请求负载中。思考模式转换仅对调用 kwargs 或绑定 kwargs 生效,因此请改用以下形式之一:

response = model.invoke("Solve this step by step: 17 * 23", thinking_mode=True)
thinking_model = model.with_thinking_mode(enabled=True)
response = thinking_model.invoke("Solve this step by step: 17 * 23")

使用 NVIDIA NIM 微服务自托管

当您准备好部署 AI 应用程序时,可以使用 NVIDIA NIM 自托管模型。有关更多信息,请参阅 NVIDIA NIM 微服务.

以下代码连接到本地托管的 NIM 微服务。

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-super-120b-a12b")

# 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")

流式、批量和异步

这些模型原生支持流式处理,与所有 LangChain LLM 一样,它们暴露了一个批量方法来处理并发请求,以及用于 invoke、stream 和 batch 的异步方法。以下是一些示例。

print(llm.batch(["What's 2*3?", "What's 2*6?"]))
# Or via the async API
# await llm.abatch(["What's 2*3?", "What's 2*6?"])
stream = llm.stream_events("How far can a seagull fly in one day?", version="v3")
for token in stream.text:
    # Show the token separations
    print(token, end="|")
stream = await llm.astream_events(
    "How long does it take for monarch butterflies to migrate?", version="v3"
)
async for token in stream.text:
    print(token, end="|")

支持的模型

查询 available_models 仍会为您提供 API 凭证提供的所有其他模型。

前缀是可选的。 playground_

ChatNVIDIA.get_available_models()
# llm.get_available_models()

模型类型

以上所有这些模型都受支持,可以通过 ChatNVIDIA.

某些模型类型支持独特的提示技术和聊天消息。我们将在下面回顾几个重要的。

**要了解特定模型的更多信息,请导航至 AI Foundation 模型的 API 部分 如链接所示.**

用于代理 AI 的 Nemotron 模型

Nemotron 是 NVIDIA 为代理工作流构建的开源模型家族。主要特点:

  • 高效性:混合 Mamba-Transformer MoE 架构可提供高达 3 倍于可比密集模型的吞吐量
  • 长上下文:原生支持高达 100 万 token 的上下文窗口
  • 代理推理:专为多步骤规划、工具使用和自主软件工程任务训练
  • 开源:权重、训练配方和精选数据集以 NVIDIA 开源模型许可证发布
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_nvidia_ai_endpoints import ChatNVIDIA

prompt = ChatPromptTemplate.from_messages(
    [
        ("system", "You are a helpful research assistant. Think step by step."),
        ("user", "{input}"),
    ]
)
chain = prompt | ChatNVIDIA(model="nvidia/nemotron-3-super-120b-a12b") | StrOutputParser()

for txt in chain.stream({"input": "What are the key considerations when designing a multi-agent RAG system?"}):
    print(txt, end="")

通用聊天

诸如 meta/llama3-8b-instructmistralai/mixtral-8x22b-instruct-v0.1 是优秀的全能模型,可用于任何 LangChain 聊天消息。如下示例。

from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_nvidia_ai_endpoints import ChatNVIDIA

prompt = ChatPromptTemplate.from_messages(
    [("system", "You are a helpful AI assistant named Fred."), ("user", "{input}")]
)
chain = prompt | ChatNVIDIA(model="nvidia/nemotron-3-super-120b-a12b") | StrOutputParser()

for txt in chain.stream({"input": "What's your name?"}):
    print(txt, end="")

代码生成

这些模型接受与常规聊天模型相同的参数和输入结构,但在代码生成和结构化代码任务上表现更好。这方面的一个示例是 meta/codellama-70b.

prompt = ChatPromptTemplate.from_messages(
    [
        (
            "system",
            "You are an expert coding AI. Respond only in valid python; no narration whatsoever.",
        ),
        ("user", "{input}"),
    ]
)
chain = prompt | ChatNVIDIA(model="meta/codellama-70b") | StrOutputParser()

for txt in chain.stream({"input": "How do I solve this fizz buzz problem?"}):
    print(txt, end="")

多模态

NVIDIA 还支持多模态输入,这意味着您可以同时提供图像和文本供模型推理。支持多模态输入的示例模型是 nvidia/neva-22b.

以下是使用示例:

image_url = "https://www.nvidia.com/content/dam/en-zz/Solutions/research/ai-playground/nvidia-picasso-3c33-p@2x.jpg"  ## Large Image
image_content = requests.get(image_url).content

IPython.display.Image(image_content)
from langchain_nvidia_ai_endpoints import ChatNVIDIA

llm = ChatNVIDIA(model="nvidia/neva-22b")

将图像作为 URL 传递

from langchain.messages import HumanMessage

llm.invoke(
    [
        HumanMessage(
            content=[
                {"type": "text", "text": "Describe this image:"},
                {"type": "image_url", "image_url": {"url": image_url}},
            ]
        )
    ]
)

将图像作为 base64 编码字符串传递

目前,客户端会进行一些额外处理以支持更大的图像。但对于较小的图像(为了更好地说明底层发生的过程),我们可以直接传入图像,如下所示:

image_url = "https://picsum.photos/seed/kitten/300/200"
image_content = requests.get(image_url).content

IPython.display.Image(image_content)
from langchain.messages import HumanMessage

## Works for simpler images. For larger images, see actual implementation
b64_string = base64.b64encode(image_content).decode("utf-8")

llm.invoke(
    [
        HumanMessage(
            content=[
                {"type": "text", "text": "Describe this image:"},
                {
                    "type": "image_url",
                    "image_url": {"url": f"data:image/png;base64,{b64_string}"},
                },
            ]
        )
    ]
)

直接嵌入字符串中

NVIDIA API 独特地接受嵌入在 <img/> HTML 标签内的 base64 图像。虽然这与其他 LLM 不兼容,但您可以直接相应地提示模型。

base64_with_mime_type = f"data:image/png;base64,{b64_string}"
llm.invoke(f'What\'s in this image?\n<img src="{base64_with_mime_type}" />')

RunnableWithMessageHistory

与任何其他集成一样, ChatNVIDIA 可以很好地支持聊天工具,如 RunnableWithMessageHistory,这类似于使用 ConversationChain。下面,我们展示 LangChain RunnableWithMessageHistory 示例在 mistralai/mixtral-8x22b-instruct-v0.1 model.

pip install -qU langchain
from langchain_core.chat_history import InMemoryChatMessageHistory
from langchain_core.runnables.history import RunnableWithMessageHistory

# store is a dictionary that maps session IDs to their corresponding chat histories.
store = {}  # memory is maintained outside the chain


# A function that returns the chat history for a given session ID.
def get_session_history(session_id: str) -> InMemoryChatMessageHistory:
    if session_id not in store:
        store[session_id] = InMemoryChatMessageHistory()
    return store[session_id]


chat = ChatNVIDIA(
    model="nvidia/nemotron-3-super-120b-a12b",
    temperature=0.1,
    max_tokens=100,
    top_p=1.0,
)

#  Define a RunnableConfig object, with a `configurable` key. session_id determines thread
config = {"configurable": {"session_id": "1"}}

conversation = RunnableWithMessageHistory(
    chat,
    get_session_history,
)

conversation.invoke(
    "Hi I'm Srijan Dubey.",  # input or query
    config=config,
)
conversation.invoke(
    "I'm doing well! Just having a conversation with an AI.",
    config=config,
)
conversation.invoke(
    "Tell me about yourself.",
    config=config,
)

工具调用

从 v0.2 开始, ChatNVIDIA 支持 bind_tools.

ChatNVIDIA 提供了与 build.nvidia.com 上各种模型的集成,以及本地 NIM。并非所有这些模型都经过工具调用训练。请确保为您的实验和应用程序选择支持工具调用的模型。

您可以通过以下方式获取已知支持工具调用的模型列表,

tool_models = [
    model for model in ChatNVIDIA.get_available_models() if model.supports_tools
]
tool_models

使用支持工具的模型,

from langchain.tools import tool
from pydantic import Field


@tool
def get_current_weather(
    location: str = Field(description="The location to get the weather for."),
):
    """Get the current weather for a location."""
    ...


llm = ChatNVIDIA(model=tool_models[0].id).bind_tools(tools=[get_current_weather])
response = llm.invoke("What is the weather in Boston?")
response.tool_calls

请参阅 如何使用聊天模型调用工具 了解更多示例。

与 NVIDIA Dynamo 配合使用

NVIDIA Dynamo 是一个分布式推理服务框架,专为在数据中心规模的多节点环境中部署模型而构建。它通过将推理的各个阶段分离到不同的 GPU 上,智能地将请求路由到适当的 GPU 以避免冗余计算,并通过数据缓存将 GPU 内存扩展到经济高效的存储层,从而简化和自动化了分布式服务的复杂性。

ChatNVIDIADynamoChatNVIDIA 的直接替代品,会自动将 nvext.agent_hints 注入到每个请求中。这些提示告诉 Dynamo 部署:

  • - **osl** (输出序列长度)— 预期生成的 token 数量,以便调度器规划内存分配
  • - **iat** (请求间隔时间)— 请求到达的速度,以便路由器预测负载
  • - **latency_sensitivity** — 请求对延迟的敏感程度,以便交互式调用获得优先路由
  • - **priority** — 请求优先级,以便后台工作让位于关键路径请求

一个唯一的 prefix_id 会为每个请求自动生成,使路由器能够跟踪 KV 缓存亲和性。

基本用法

ChatNVIDIA 替换为 ChatNVIDIADynamo ,每个请求自动包含路由提示。所有标准 ChatNVIDIA 参数均受支持。

from langchain_nvidia_ai_endpoints import ChatNVIDIA, ChatNVIDIADynamo

BASE_URL = "http://localhost:8099/v1"
MODEL = "your-model-name"

# Standard ChatNVIDIA — no Dynamo hints
llm_standard = ChatNVIDIA(base_url=BASE_URL, model=MODEL)

# ChatNVIDIADynamo — identical interface, automatically injects agent_hints
llm = ChatNVIDIADynamo(base_url=BASE_URL, model=MODEL)

result = llm.invoke("What is KV cache optimization?")
print(result.content)

ChatNVIDIADynamo 除了支持 ChatNVIDIA:

参数类型默认值描述
oslint512预期输出序列长度(token 数)
iatint250预期请求间隔时间(毫秒)
latency_sensitivityfloat1.0更高的延迟敏感度获得优先路由
priorityint1更低的优先级设置获得更多调度优先级

在构造时设置默认值

在创建模型实例时配置 Dynamo 提示。当模型实例始终担任特定角色时这很有用,例如高优先级交互式助手与低优先级后台摘要生成器。

# High-priority: short responses, latency-critical
llm_critical = ChatNVIDIADynamo(
    base_url=BASE_URL,
    model=MODEL,
    osl=20,
    priority=0,
    latency_sensitivity=10.0,
)

# Low-priority: long responses, latency-tolerant
llm_background = ChatNVIDIADynamo(
    base_url=BASE_URL,
    model=MODEL,
    osl=512,
    priority=10,
    latency_sensitivity=0,
)

在每次调用时覆盖

Dynamo 参数也可以在每次调用时覆盖。当同一模型实例处理具有不同特征的请求时,这很有用。

result = llm.invoke(
    "Classify this as positive or negative: 'I love this product!'",
    osl=10,
    iat=100,
    latency_sensitivity=1.0,
    priority=10,
)
print(result.content)

使用 Dynamo 提示进行流式传输

Dynamo 提示包含在初始流式请求中。Dynamo 使用它们在 token 开始流动之前选择最佳工作节点。

stream = llm_critical.stream_events("Give a one-sentence summary of GPU computing.", version="v3")
for token in stream.text:
    print(token, end="", flush=True)

检查有效载荷

为了调试,请检查 ChatNVIDIADynamo 发送到 NIM 端点的确切有效载荷,使用内部 _get_payload method.

payload = llm_critical._get_payload(
    inputs=[{"role": "user", "content": "Hello!"}],
    stop=None,
)
print(json.dumps(payload["nvext"], indent=2))

这会输出 nvext.agent_hints section:

{
  "agent_hints": {
    "prefix_id": "langchain-dynamo-a1b2c3d4e5f6",
    "osl": 20,
    "iat": 250,
    "latency_sensitivity": 1.0,
    "priority": 10
  }
}

API 参考

有关所有 ChatNVIDIA 功能和配置的详细文档,请访问 API 参考.

相关主题