Skip to main content
Open In ColabOpen on GitHub

英伟达

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

概览

The langchain-nvidia-ai-endpoints 包包含用于在NVIDIA NIM推理微服务上使用模型构建应用程序的LangChain集成。这些模型由NVIDIA优化,可在NVIDIA加速基础设施上提供最佳性能,并作为NIM部署;NIM是易于使用、预构建的容器,只需一条命令即可在NVIDIA加速基础设施上的任意位置部署。

NVIDIA hosted deployments of NIMs are available to test on the NVIDIA API catalog. After testing, NIMs can be exported from NVIDIA’s API catalog using the NVIDIA AI Enterprise license and run on-premises or in the cloud, giving enterprises ownership and full control of their IP and AI application.

NIMs是以单个模型为基础打包为容器镜像,并通过NVIDIA NGC目录分发为NGC容器镜像。 在核心层面,NIMs提供了运行AI模型推理的简单、一致且熟悉的API接口。

此示例介绍了如何使用LangChain与NVIDIA支持的通过NVIDIA类进行交互的方法。

通过此API访问LLM模型的更多信息,请查看 NVIDIA 文档。

集成细节

Class本地序列化JS支持Package downloadsPackage 最新版本
NVIDIAlangchain_nvidia_ai_endpointsbetaPyPI - DownloadsPyPI - Version

模型特性

JSON 模式图像输入音频输入视频输入Token级流式传输原生异步Token 使用对数概率

设置

要开始使用:

  1. 创建一个免费账户,使用托管NVIDIA AI基础模型的NVIDIA

  2. 点击您喜欢的模型。

  3. Input 下选择 Python 选项卡,然后点击 Get API Key。接着点击 Generate Key

  4. 将生成的密钥复制并保存为NVIDIA_API_KEY。之后,您应该可以访问相关的端点。

Credentials

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

安装

The LangChain NVIDIA AI Endpoints 整合存在于 langchain_nvidia_ai_endpoints 包中:

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

Instantiation

请参阅 LLM 以获取完整功能。

from langchain_nvidia_ai_endpoints import NVIDIA
API 参考:英伟达
llm = NVIDIA().bind(max_tokens=256)
llm

Invocation

prompt = "# Function that does quicksort written in Rust without comments:"
print(llm.invoke(prompt))

流式、批量处理和异步处理

这些模型原生支持流式处理,就像所有LangChain大语言模型一样,它们暴露了批处理方法以处理并发请求,以及用于调用、流式传输和批处理的异步方法。下面是几个示例。

for chunk in llm.stream(prompt):
print(chunk, end="", flush=True)
llm.batch([prompt])
await llm.ainvoke(prompt)
async for chunk in llm.astream(prompt):
print(chunk, end="", flush=True)
await llm.abatch([prompt])
async for chunk in llm.astream_log(prompt):
print(chunk)
response = llm.invoke(
"X_train, y_train, X_test, y_test = train_test_split(X, y, test_size=0.1) #Train a logistic regression model, predict the labels on the test set and compute the accuracy score"
)
print(response)

支持的模型

查询available_models仍将返回您API凭证提供的所有其他模型。

NVIDIA.get_available_models()
# llm.get_available_models()

链式调用

我们可以通过以下方式将模型与提示模板进行链接

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 参考

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