IBM watsonx.ai
IBM watsonx.ai
WatsonxLLM은 IBM watsonx.ai 파운데이션 모델을 위한 래퍼예요. 이 예제들은 LlamaIndex의 LLMs API로 watsonx.ai 모델과 통신하는 방법을 보여 줍니다.
출처: 문서
본문
설정 (Setting up)
llama-index-llms-ibm 패키지를 설치해요.
!pip install -qU llama-index-llms-ibm
아래 셀은 watsonx Foundation Model 추론에 필요한 자격 증명을 정의해요.
액션: IBM Cloud 사용자 API 키를 제공하세요. 자세한 내용은 Managing user API keys를 참고하세요.
import os
from getpass import getpass
watsonx_api_key = getpass()
os.environ["WATSONX_APIKEY"] = watsonx_api_key
추가 비밀값을 환경 변수로 전달할 수도 있어요.
import os
os.environ["WATSONX_URL"] = "your service instance url"
os.environ["WATSONX_TOKEN"] = "your token for accessing the 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"
모델 로드 (Load the model)
모델이나 태스크에 따라 모델 parameters를 조정해야 할 수 있어요. 자세한 내용은 Available MetaNames를 참고하세요.
temperature = 0.5
max_new_tokens = 50
additional_params = {
"decoding_method": "sample",
"min_new_tokens": 1,
"top_k": 50,
"top_p": 1,
}
앞서 설정한 파라미터로 WatsonxLLM 클래스를 초기화해요.
참고:
- API 호출에 컨텍스트를 제공하려면
project_id또는space_id를 전달해야 해요. 프로젝트나 스페이스 ID를 얻으려면 프로젝트(스페이스)를 열고 Manage 탭으로 가서 General을 클릭하세요. 자세한 내용은 Project 문서 또는 Deployment space 문서를 참고하세요. - 프로비저닝된 서비스 인스턴스의 리전에 따라 watsonx.ai API Authentication에 나열된 URL 중 하나를 사용하세요.
이 예제에서는 project_id와 Dallas URL을 사용할게요.
추론에 사용할 model_id를 지정해야 해요. 사용 가능한 전체 모델 목록은 Supported foundation models에서 확인할 수 있어요.
from llama_index.llms.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",
temperature=temperature,
max_new_tokens=max_new_tokens,
additional_params=additional_params,
)
대신 Cloud Pak for Data 자격 증명을 사용할 수도 있어요. 자세한 내용은 watsonx.ai software setup를 참고하세요.
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",
temperature=temperature,
max_new_tokens=max_new_tokens,
additional_params=additional_params,
)
model_id 대신 이전에 튜닝한 모델의 deployment_id를 전달할 수도 있어요. 전체 모델 튜닝 워크플로는 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",
temperature=temperature,
max_new_tokens=max_new_tokens,
additional_params=additional_params,
)
완성 만들기 (Create a Completion)
문자열 타입 프롬프트로 모델을 직접 호출해요.
response = watsonx_llm.complete("What is a Generative AI?")
print(response)
A generative AI is a computer program that can create new text, images, or other types of content. These programs are trained on large datasets of existing content, and they use that data to generate new content that is similar to the training data.
CompletionResponse에서 서비스가 반환한 원시 응답도 가져올 수 있어요.
print(response.raw)
{'model_id': 'ibm/granite-13b-instruct-v2', 'created_at': '2024-05-20T07:11:57.984Z', 'results': [{'generated_text': 'A generative AI is a computer program that can create new text, images, or other types of content. These programs are trained on large datasets of existing content, and they use that data to generate new content that is similar to the training data.', 'generated_token_count': 50, 'input_token_count': 7, 'stop_reason': 'max_tokens', 'seed': 494448017}]}
프롬프트 템플릿을 제공하는 모델도 호출할 수 있어요.
from llama_index.core import PromptTemplate
template = "What is {object} and how does it work?"
prompt_template = PromptTemplate(template=template)
prompt = prompt_template.format(object="a loan")
response = watsonx_llm.complete(prompt)
print(response)
A loan is a sum of money that is borrowed to buy something, such as a house or a car. The borrower must repay the loan plus interest. The interest is a fee charged for using the money. The interest rate is the amount of
메시지 목록으로 chat 호출
메시지 목록을 제공해 chat 완성을 만들어요.
from llama_index.core.llms import ChatMessage
messages = [
ChatMessage(role="system", content="You are an AI assistant"),
ChatMessage(role="user", content="Who are you?"),
]
response = watsonx_llm.chat(
messages, max_new_tokens=20, decoding_method="greedy"
)
print(response)
assistant: I am an AI assistant.
여기서는 max_new_tokens 파라미터를 20으로, decoding_method를 greedy로 바꿨다는 점에 유의하세요.
모델 출력 스트리밍 (Streaming the model output)
모델 응답을 스트리밍해요.
for chunk in watsonx_llm.stream_complete(
"Describe your favorite city and why it is your favorite."
):
print(chunk.delta, end="")
I like New York because it is the city of dreams. You can achieve anything you want here.
마찬가지로 chat 완성을 스트리밍하려면 다음 코드를 사용해요.
messages = [
ChatMessage(role="system", content="You are an AI assistant"),
ChatMessage(role="user", content="Who are you?"),
]
for chunk in watsonx_llm.stream_chat(messages):
print(chunk.delta, end="")
I am an AI assistant.