이 문서는 NVIDIA chat models 시작하기를 도와드립니다. 모든 ChatNVIDIA 기능과 구성에 대한 자세한 문서는 API reference를 참조하세요.

Overview

langchain-nvidia-ai-endpoints 패키지는 NVIDIA NIM inference microservice의 모델을 사용하여 애플리케이션을 구축하는 LangChain integration을 포함하고 있습니다. NIM은 커뮤니티와 NVIDIA의 chat, embedding, re-ranking 모델과 같은 다양한 도메인의 모델을 지원합니다. 이러한 모델들은 NVIDIA 가속 인프라에서 최고의 성능을 제공하도록 NVIDIA에 의해 최적화되었으며, NIM으로 배포됩니다. NIM은 NVIDIA 가속 인프라에서 단일 명령으로 어디서나 배포할 수 있는 사용하기 쉬운 사전 구축 컨테이너입니다. NVIDIA가 호스팅하는 NIM 배포는 NVIDIA API catalog에서 테스트할 수 있습니다. 테스트 후, NIM은 NVIDIA AI Enterprise 라이선스를 사용하여 NVIDIA의 API catalog에서 내보낼 수 있으며, 온프레미스 또는 클라우드에서 실행할 수 있어 기업이 IP와 AI 애플리케이션에 대한 소유권과 완전한 제어권을 가질 수 있습니다. NIM은 모델별로 컨테이너 이미지로 패키징되며 NVIDIA NGC Catalog을 통해 NGC 컨테이너 이미지로 배포됩니다. 핵심적으로 NIM은 AI 모델에서 inference를 실행하기 위한 쉽고 일관되며 친숙한 API를 제공합니다. 이 예제는 ChatNVIDIA 클래스를 통해 NVIDIA가 지원하는 모델과 상호작용하기 위해 LangChain을 사용하는 방법을 다룹니다. 이 API를 통해 chat 모델에 액세스하는 방법에 대한 자세한 내용은 ChatNVIDIA 문서를 확인하세요.

Integration details

ClassPackageLocalSerializableJS supportDownloadsVersion
ChatNVIDIAlangchain-nvidia-ai-endpointsbetaPyPI - DownloadsPyPI - Version

Model features

Tool callingStructured outputJSON modeImage inputAudio inputVideo inputToken-level streamingNative asyncToken usageLogprobs

Setup

시작하기:
  1. NVIDIA AI Foundation 모델을 호스팅하는 NVIDIA에서 무료 계정을 생성하세요.
  2. 원하는 모델을 클릭하세요.
  3. Input 아래에서 Python 탭을 선택하고 Get API Key를 클릭하세요. 그런 다음 Generate Key를 클릭하세요.
  4. 생성된 키를 NVIDIA_API_KEY로 복사하고 저장하세요. 그러면 endpoint에 액세스할 수 있습니다.

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: ")
모델 호출의 자동 추적을 활성화하려면 LangSmith API 키를 설정하세요:
os.environ["LANGSMITH_TRACING"] = "true"
os.environ["LANGSMITH_API_KEY"] = getpass.getpass("Enter your LangSmith API key: ")

Installation

LangChain NVIDIA AI Endpoints integration은 langchain-nvidia-ai-endpoints 패키지에 있습니다:
pip install -qU langchain-nvidia-ai-endpoints

Instantiation

이제 NVIDIA API Catalog의 모델에 액세스할 수 있습니다:
## Core LC Chat Interface
from langchain_nvidia_ai_endpoints import ChatNVIDIA

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

Invocation

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

Working with NVIDIA NIMs

배포 준비가 되면 NVIDIA AI Enterprise 소프트웨어 라이선스에 포함된 NVIDIA NIM으로 모델을 자체 호스팅하고 어디서나 실행할 수 있어, 커스터마이징에 대한 소유권과 지적 재산권(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")

Stream, Batch, and Async

이러한 모델들은 기본적으로 streaming을 지원하며, 모든 LangChain LLM과 마찬가지로 동시 요청을 처리하기 위한 batch 메서드와 invoke, stream, batch를 위한 async 메서드를 제공합니다. 아래는 몇 가지 예제입니다.
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="|")

Supported models

available_models를 쿼리하면 API 자격 증명으로 제공되는 다른 모든 모델을 얻을 수 있습니다. playground_ 접두사는 선택 사항입니다.
ChatNVIDIA.get_available_models()
# llm.get_available_models()

Model types

위의 모든 모델이 지원되며 ChatNVIDIA를 통해 액세스할 수 있습니다. 일부 모델 유형은 고유한 prompting 기법과 chat 메시지를 지원합니다. 아래에서 몇 가지 중요한 것들을 살펴보겠습니다. 특정 모델에 대한 자세한 내용은 여기에 링크된 AI Foundation 모델의 API 섹션으로 이동하세요.

General Chat

meta/llama3-8b-instructmistralai/mixtral-8x22b-instruct-v0.1과 같은 모델은 모든 LangChain chat 메시지와 함께 사용할 수 있는 우수한 범용 모델입니다. 아래 예제를 참조하세요.
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="")

Code Generation

이러한 모델은 일반 chat 모델과 동일한 인수 및 입력 구조를 허용하지만 코드 생성 및 구조화된 코드 작업에서 더 나은 성능을 발휘하는 경향이 있습니다. 이에 대한 예는 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="")

Multimodal

NVIDIA는 multimodal 입력도 지원하므로 모델이 추론할 수 있도록 이미지와 텍스트를 모두 제공할 수 있습니다. multimodal 입력을 지원하는 예제 모델은 nvidia/neva-22b입니다. 아래는 사용 예제입니다:
import IPython
import requests

image_url = "https://www.nvidia.com/content/dam/en-zz/Solutions/research/ai-playground/[email protected]"  ## 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")

Passing an image as a URL

from langchain.messages import HumanMessage

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

Passing an image as a base64 encoded string

현재 위와 같은 더 큰 이미지를 지원하기 위해 클라이언트 측에서 일부 추가 처리가 발생합니다. 그러나 더 작은 이미지의 경우(그리고 내부에서 진행되는 프로세스를 더 잘 설명하기 위해) 아래와 같이 이미지를 직접 전달할 수 있습니다:
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.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}"},
                },
            ]
        )
    ]
)

Directly within the 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}" />')

Example usage within a RunnableWithMessageHistory

다른 integration과 마찬가지로 ChatNVIDIA는 ConversationChain 사용과 유사한 RunnableWithMessageHistory와 같은 chat 유틸리티를 지원합니다. 아래에서는 mistralai/mixtral-8x22b-instruct-v0.1 모델에 적용된 LangChain RunnableWithMessageHistory 예제를 보여줍니다.
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="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,
)

Tool calling

v0.2부터 ChatNVIDIAbind_tools를 지원합니다. ChatNVIDIAbuild.nvidia.com의 다양한 모델과 로컬 NIM과의 integration을 제공합니다. 이러한 모든 모델이 tool calling을 위해 훈련된 것은 아닙니다. 실험 및 애플리케이션을 위해 tool calling을 지원하는 모델을 선택해야 합니다. tool calling을 지원하는 것으로 알려진 모델 목록은 다음과 같이 얻을 수 있습니다:
tool_models = [
    model for model in ChatNVIDIA.get_available_models() if model.supports_tools
]
tool_models
tool 지원 모델을 사용하면:
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
추가 예제는 How to use chat models to call tools를 참조하세요.

API reference

모든 ChatNVIDIA 기능과 구성에 대한 자세한 문서는 API reference를 참조하세요: python.langchain.com/api_reference/nvidia_ai_endpoints/chat_models/langchain_nvidia_ai_endpoints.chat_models.ChatNVIDIA.html
Connect these docs programmatically to Claude, VSCode, and more via MCP for real-time answers.
I