WatsonxLLM은 IBM watsonx.ai foundation model을 위한 wrapper입니다.
이 예제는 LangChain을 사용하여 watsonx.ai model과 통신하는 방법을 보여줍니다.

개요

Integration 세부 정보

ClassPackageLocalSerializableJS supportDownloadsVersion
WatsonxLLMlangchain-ibmPyPI - DownloadsPyPI - Version

설정

IBM watsonx.ai model에 액세스하려면 IBM watsonx.ai 계정을 생성하고, API key를 받고, langchain-ibm integration package를 설치해야 합니다.

자격 증명

아래 셀은 watsonx Foundation Model inferencing 작업에 필요한 자격 증명을 정의합니다. 작업: IBM Cloud 사용자 API key를 제공하세요. 자세한 내용은 Managing user API keys를 참조하세요.
import os
from getpass import getpass

watsonx_api_key = getpass()
os.environ["WATSONX_APIKEY"] = watsonx_api_key
추가로 환경 변수로 추가 secret을 전달할 수 있습니다.
import os

os.environ["WATSONX_URL"] = "your service instance url"
os.environ["WATSONX_TOKEN"] = "your token for accessing the CLOUD or CPD cluster"
os.environ["WATSONX_PASSWORD"] = "your password for accessing the CPD cluster"
os.environ["WATSONX_USERNAME"] = "your username for accessing the CPD cluster"
os.environ["WATSONX_INSTANCE_ID"] = "your instance_id for accessing the CPD cluster"

설치

LangChain IBM integration은 langchain-ibm package에 있습니다:
!pip install -qU langchain-ibm

인스턴스화

다양한 model이나 작업에 대해 model parameters를 조정해야 할 수 있습니다. 자세한 내용은 documentation을 참조하세요.
parameters = {
    "decoding_method": "sample",
    "max_new_tokens": 100,
    "min_new_tokens": 1,
    "temperature": 0.5,
    "top_k": 50,
    "top_p": 1,
}
이전에 설정한 parameter로 WatsonxLLM class를 초기화합니다. 참고:
  • API 호출에 대한 context를 제공하려면 project_id 또는 space_id를 추가해야 합니다. 자세한 내용은 documentation을 참조하세요.
  • 프로비저닝된 서비스 인스턴스의 지역에 따라 여기에 설명된 url 중 하나를 사용하세요.
이 예제에서는 project_id와 Dallas url을 사용합니다. inferencing에 사용할 model_id를 지정해야 합니다. 사용 가능한 모든 model은 documentation에서 찾을 수 있습니다.
from langchain_ibm import WatsonxLLM

watsonx_llm = WatsonxLLM(
    model_id="ibm/granite-13b-instruct-v2",
    url="https://us-south.ml.cloud.ibm.com",
    project_id="PASTE YOUR PROJECT_ID HERE",
    params=parameters,
)
또는 Cloud Pak for Data 자격 증명을 사용할 수 있습니다. 자세한 내용은 documentation을 참조하세요.
watsonx_llm = WatsonxLLM(
    model_id="ibm/granite-13b-instruct-v2",
    url="PASTE YOUR URL HERE",
    username="PASTE YOUR USERNAME HERE",
    password="PASTE YOUR PASSWORD HERE",
    instance_id="openshift",
    version="4.8",
    project_id="PASTE YOUR PROJECT_ID HERE",
    params=parameters,
)
model_id 대신 이전에 튜닝된 model의 deployment_id를 전달할 수도 있습니다. 전체 model tuning workflow는 Working with TuneExperiment and PromptTuner에 설명되어 있습니다.
watsonx_llm = WatsonxLLM(
    deployment_id="PASTE YOUR DEPLOYMENT_ID HERE",
    url="https://us-south.ml.cloud.ibm.com",
    project_id="PASTE YOUR PROJECT_ID HERE",
    params=parameters,
)
특정 요구 사항의 경우, IBM의 APIClient 객체를 WatsonxLLM class에 전달하는 옵션이 있습니다.
from ibm_watsonx_ai import APIClient

api_client = APIClient(...)

watsonx_llm = WatsonxLLM(
    model_id="ibm/granite-13b-instruct-v2",
    watsonx_client=api_client,
)
IBM의 ModelInference 객체를 WatsonxLLM class에 전달할 수도 있습니다.
from ibm_watsonx_ai.foundation_models import ModelInference

model = ModelInference(...)

watsonx_llm = WatsonxLLM(watsonx_model=model)

호출

completion을 얻으려면 문자열 prompt를 사용하여 model을 직접 호출할 수 있습니다.
# Calling a single prompt

watsonx_llm.invoke("Who is man's best friend?")
"Man's best friend is his dog. Dogs are man's best friend because they are always there for you, they never judge you, and they love you unconditionally. Dogs are also great companions and can help reduce stress levels. "
# Calling multiple prompts

watsonx_llm.generate(
    [
        "The fastest dog in the world?",
        "Describe your chosen dog breed",
    ]
)
LLMResult(generations=[[Generation(text='The fastest dog in the world is the greyhound. Greyhounds can run up to 45 mph, which is about the same speed as a Usain Bolt.', generation_info={'finish_reason': 'eos_token'})], [Generation(text='The Labrador Retriever is a breed of retriever that was bred for hunting. They are a very smart breed and are very easy to train. They are also very loyal and will make great companions. ', generation_info={'finish_reason': 'eos_token'})]], llm_output={'token_usage': {'generated_token_count': 82, 'input_token_count': 13}, 'model_id': 'ibm/granite-13b-instruct-v2', 'deployment_id': None}, run=[RunInfo(run_id=UUID('750b8a0f-8846-456d-93d0-e039e95b1276')), RunInfo(run_id=UUID('aa4c2a1c-5b08-4fcf-87aa-50228de46db5'))], type='LLMResult')

Model output Streaming

model output을 streaming할 수 있습니다.
for chunk in watsonx_llm.stream(
    "Describe your favorite breed of dog and why it is your favorite."
):
    print(chunk, end="")
My favorite breed of dog is a Labrador Retriever. They are my favorite breed because they are my favorite color, yellow. They are also very smart and easy to train.

Chaining

무작위 질문을 생성하는 PromptTemplate 객체를 생성합니다.
from langchain_core.prompts import PromptTemplate

template = "Generate a random question about {topic}: Question: "

prompt = PromptTemplate.from_template(template)
주제를 제공하고 chain을 실행합니다.
llm_chain = prompt | watsonx_llm

topic = "dog"

llm_chain.invoke(topic)
'What is the origin of the name "Pomeranian"?'

API reference

모든 WatsonxLLM 기능 및 구성에 대한 자세한 문서는 API reference를 참조하세요.
Connect these docs programmatically to Claude, VSCode, and more via MCP for real-time answers.
I