Skip to main content
Open In ColabOpen on GitHub

ChatNVIDIA

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

概述

langchain-nvidia-ai-endpoints 包包含 LangChain 集成,用于构建基于 NVIDIA NIM 推理微服务上模型的应用程序。NIM 支持来自社区以及 NVIDIA 的聊天、嵌入和重排模型等领域内的模型。这些模型由 NVIDIA 优化,可在 NVIDIA 加速基础设施上提供最佳性能,并作为 NIM 部署。NIM 是易于使用的预构建容器,只需在 NVIDIA 加速基础设施上运行单个命令即可在任何地方进行部署。

NVIDIA 托管的 NIM 部署可在 NVIDIA API 目录 上进行测试。测试后,可以使用 NVIDIA AI Enterprise 许可证从 NVIDIA 的 API 目录导出 NIM,并在本地或云端运行,从而使企业能够拥有并完全控制其 IP 和 AI 应用程序。

NIM 按模型打包为容器镜像,并通过 NVIDIA NGC Catalog 分发为 NGC 容器镜像。从本质上讲,NIM 为运行 AI 模型推理提供了简单、一致且熟悉的 API。

此示例将介绍如何通过 ChatNVIDIA 类使用 LangChain 与 NVIDIA 进行交互。

有关通过此 API 访问聊天模型的更多信息,请查看 ChatNVIDIA 文档。

集成详情

本地可序列化JS 支持包下载量最新包版本
ChatNVIDIAlangchain_nvidia_ai_endpointsbetaPyPI - DownloadsPyPI - Version

模型功能

工具调用结构化输出JSON 模式图像输入音频输入视频输入Token 级别流式传输原生异步Token 使用量跟踪Logprobs

设置

开始之前:

  1. 创建一个免费的 NVIDIA 账户,该平台托管 NVIDIA AI Foundation 模型。

  2. 选择您想使用的模型。

  3. 输入 部分选择 Python 选项卡,然后点击 获取 API 密钥。接着点击 生成密钥

  4. 复制生成的密钥并另存为 NVIDIA_API_KEY。从这时起,您应该可以访问相应的端点。

凭证

import getpass
import os

if not os.getenv("NVIDIA_API_KEY"):
# Note: the API key should start with "nvapi-"
os.environ["NVIDIA_API_KEY"] = getpass.getpass("Enter your NVIDIA API key: ")

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

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

安装

LangChain NVIDIA AI Endpoints 集成位于 langchain_nvidia_ai_endpoints 包中:

%pip install --upgrade --quiet langchain-nvidia-ai-endpoints

实例化

现在我们可以访问 NVIDIA API 目录中的模型了:

## Core LC Chat Interface
from langchain_nvidia_ai_endpoints import ChatNVIDIA

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

调用

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

使用 NVIDIA NIM

准备部署时,您可以使用 NVIDIA NIM 自行托管模型。NVIDIA NIM 包含在 NVIDIA AI Enterprise 软件许可中,可以随处运行,让您完全拥有自己的定制内容以及知识产权 (IP) 和 AI 应用。

了解更多关于 NIM 的信息

from langchain_nvidia_ai_endpoints import ChatNVIDIA

# connect to an embedding NIM running at localhost:8000, specifying a specific model
llm = ChatNVIDIA(base_url="http://localhost:8000/v1", model="meta/llama3-8b-instruct")
API Reference:ChatNVIDIA

流式、批处理和异步

这些模型原生支持流式处理,并且正如 LangChain 所有 LLM 一样,它们暴露了 batch 方法来处理并发请求,以及用于 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?"])
for chunk in llm.stream("How far can a seagull fly in one day?"):
# Show the token separations
print(chunk.content, end="|")
async for chunk in llm.astream(
"How long does it take for monarch butterflies to migrate?"
):
print(chunk.content, end="|")

支持的模型

查询 available_models 将继续为您提供 API 凭证提供的所有其他模型。

playground_ 前缀是可选的。

ChatNVIDIA.get_available_models()
# llm.get_available_models()

模型类型

以上所有模型均受支持,并且可以通过 ChatNVIDIA 访问。

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

要了解特定模型的更多信息,请导航到 AI Foundation 模型 的 API 部分,链接在此

通用聊天

诸如 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="meta/llama3-8b-instruct") | 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

以下是一个使用示例:

import IPython
import requests

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")
API Reference:ChatNVIDIA

将图片作为 URL 传递

from langchain_core.messages import HumanMessage

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

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

目前,在客户端会进行一些额外的处理来支持像上面那样的大型图片。但对于小型图片(以及为了更好地说明底层正在进行的流程),我们可以直接传入图片,如下所示:

import IPython
import requests

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

IPython.display.Image(image_content)
import base64

from langchain_core.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}"},
},
]
)
]
)
API Reference:HumanMessage

直接嵌入字符串中

NVIDIA API 独特之处在于它接受以 base64 编码的图片,并将其内联在 <img/> HTML 标签中。虽然这与其他 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。下面,我们展示了应用于 mistralai/mixtral-8x22b-instruct-0.1 模型的 LangChain RunnableWithMessageHistory 示例。

%pip install --upgrade --quiet 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="mistralai/mixtral-8x22b-instruct-v0.1",
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_core.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
API Reference:tool

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

链式调用

我们可以像这样将模型与提示模板进行链式调用

from langchain_core.prompts import ChatPromptTemplate

prompt = ChatPromptTemplate(
[
(
"system",
"You are a helpful assistant that translates {input_language} to {output_language}.",
),
("human", "{input}"),
]
)

chain = prompt | llm
chain.invoke(
{
"input_language": "English",
"output_language": "German",
"input": "I love programming.",
}
)
API Reference:ChatPromptTemplate

API 参考

有关 ChatNVIDIA 所有功能和配置的详细文档,请访问 API 参考:https://python.langchain.com/api_reference/nvidia_ai_endpoints/chat_models/langchain_nvidia_ai_endpoints.chat_models.ChatNVIDIA.html