langchain-nvidia-ai-endpoints 包包含基于 NVIDIA AI Foundation Models 并托管在 NVIDIA API Catalog 的对话模型和嵌入的 LangChain 整合。
langchain-nvidia-ai-endpoints 包包含基于 NVIDIA AI Foundation Models 并托管在 NVIDIA API Catalog 的对话模型和嵌入的 LangChain 整合。NVIDIA AI Foundation models 是社区和 NVIDIA 共同构建的模型,针对 NVIDIA 加速基础设施进行了性能优化。您可以通过 NVIDIA API 调用 NVIDIA API Catalog 上的实时端点,快速从 DGX 托管的云计算环境中获取结果,或使用 NVIDIA NIM(随 NVIDIA AI Enterprise 许可证提供)从 NVIDIA API 目录下载模型。在本地部署模型的能力使企业能够拥有定制化内容,并对知识产权和 AI 应用实现完全控制。NIM 微服务以每个模型/模型家族为基础打包为容器镜像,通过 NVIDIA NGC Catalog 分发为 NGC 容器镜像。本质上,NIM 微服务是提供 AI 模型推理交互 API 的容器。本示例说明如何使用 LangChain 通过 NVIDIAEmbeddings 类与支持的 NVIDIA Retrieval QA Embedding Model 进行交互,实现 retrieval-augmented generation。要获取通过此 API 访问对话模型的更多信息,请参考 ChatNVIDIA 文档。
准备部署 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 modelllm = ChatNVIDIA(base_url="http://localhost:8000/v1", model="meta/llama3-8b-instruct")# connect to an embedding NIM running at localhost:8080embedder = NVIDIAEmbeddings(base_url="http://localhost:8080/v1")# connect to a reranking NIM running at localhost:2016ranker = NVIDIARerank(base_url="http://localhost:2016/v1")
print("\nSequential Embedding: ")q_embeddings = [ embedder.embed_query("What's the weather like in Komchatka?"), embedder.embed_query("What kinds of food is Italy known for?"), embedder.embed_query("What's my name? I bet you don't remember..."), embedder.embed_query("What's the point of life anyways?"), embedder.embed_query("The point of life is to have fun :D"),]print("Shape:", (len(q_embeddings), len(q_embeddings[0])))
print("\nBatch Document Embedding: ")d_embeddings = embedder.embed_documents( [ "Komchatka's weather is cold, with long, severe winters.", "Italy is famous for pasta, pizza, gelato, and espresso.", "I can't recall personal names, only provide information.", "Life's purpose varies, often seen as personal fulfillment.", "Enjoying life's moments is indeed a wonderful approach.", ])print("Shape:", (len(d_embeddings), len(d_embeddings[0])))
在生成嵌入后,我们可以对结果进行简单的相似度检查,以确定哪些文档在检索任务中会触发合理的答案:
pip install -qU matplotlib scikit-learn
import matplotlib.pyplot as pltimport numpy as npfrom sklearn.metrics.pairwise import cosine_similarity# Compute the similarity matrix between q_embeddings and d_embeddingscross_similarity_matrix = cosine_similarity( np.array(q_embeddings), np.array(d_embeddings),)# Plotting the cross-similarity matrixplt.figure(figsize=(8, 6))plt.imshow(cross_similarity_matrix, cmap="Greens", interpolation="nearest")plt.colorbar()plt.title("Cross-Similarity Matrix")plt.xlabel("Query Embeddings")plt.ylabel("Document Embeddings")plt.grid(True)plt.show()
vectorstore = FAISS.from_texts( ["harrison worked at kensho"], embedding=NVIDIAEmbeddings(model="NV-Embed-QA"),)retriever = vectorstore.as_retriever()prompt = ChatPromptTemplate.from_messages( [ ( "system", "Answer solely based on the following context:\n<Documents>\n{context}\n</Documents>", ), ("user", "{question}"), ])model = ChatNVIDIA(model="ai-mixtral-8x7b-instruct")chain = ( {"context": retriever, "question": RunnablePassthrough()} | prompt | model | StrOutputParser())chain.invoke("where did harrison work?")
prompt = ChatPromptTemplate.from_messages( [ ( "system", "Answer using information solely based on the following context:\n<Documents>\n{context}\n</Documents>" "\nSpeak only in the following language: {language}", ), ("user", "{question}"), ])chain = ( { "context": itemgetter("question") | retriever, "question": itemgetter("question"), "language": itemgetter("language"), } | prompt | model | StrOutputParser())chain.invoke({"question": "where did harrison work", "language": "italian"})