ChatWatsonx
ChatWatsonx 是 IBM watsonx.ai 基礎模型的封裝器。
這些範例旨在展示如何使用 LangChain
LLMs API 與 watsonx.ai
模型進行通訊。
概觀
整合詳細資訊
類別 | 套件 | 本地 | 可序列化 | JS 支援 | 套件下載 | 套件最新版本 |
---|---|---|---|---|---|---|
ChatWatsonx | langchain-ibm | ❌ | ❌ | ✅ |
模型功能
工具呼叫 | 結構化輸出 | JSON 模式 | 圖像輸入 | 音訊輸入 | 視訊輸入 | Token 層級串流 | 原生非同步 | Token 使用量 | Logprobs |
---|---|---|---|---|---|---|---|---|---|
✅ | ✅ | ✅ | ✅ | ❌ | ❌ | ✅ | ❌ | ✅ | ✅ |
設定
若要存取 IBM watsonx.ai 模型,您需要建立 IBM watsonx.ai 帳戶、取得 API 金鑰,並安裝 langchain-ibm
整合套件。
憑證
以下儲存格定義了使用 watsonx Foundation Model 推論所需的憑證。
動作: 提供 IBM Cloud 使用者 API 金鑰。如需詳細資訊,請參閱管理使用者 API 金鑰。
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"
安裝
LangChain IBM 整合位於 langchain-ibm
套件中
!pip install -qU langchain-ibm
例項化
您可能需要針對不同的模型或任務調整模型 parameters
。如需詳細資訊,請參閱可用的 TextChatParameters。
parameters = {
"temperature": 0.9,
"max_tokens": 200,
}
使用先前設定的參數初始化 WatsonxLLM
類別。
注意:
- 若要為 API 呼叫提供背景資訊,您必須傳遞
project_id
或space_id
。若要取得您的專案或空間 ID,請開啟您的專案或空間,前往管理標籤,然後按一下一般。如需更多資訊,請參閱:專案文件或部署空間文件。 - 根據您佈建的服務實例的區域,使用watsonx.ai API 驗證中列出的 URL 之一。
在此範例中,我們將使用 project_id
和 Dallas URL。
您需要指定將用於推論的 model_id
。您可以在支援的聊天模型中找到所有可用模型的清單。
from langchain_ibm import ChatWatsonx
chat = ChatWatsonx(
model_id="ibm/granite-34b-code-instruct",
url="https://us-south.ml.cloud.ibm.com",
project_id="PASTE YOUR PROJECT_ID HERE",
params=parameters,
)
或者,您可以使用 Cloud Pak for Data 憑證。如需詳細資訊,請參閱watsonx.ai 軟體設定。
chat = ChatWatsonx(
model_id="ibm/granite-34b-code-instruct",
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
之外,您也可以傳遞先前調整模型的 deployment_id
。整個模型調整工作流程在使用 TuneExperiment 和 PromptTuner中說明。
chat = ChatWatsonx(
deployment_id="PASTE YOUR DEPLOYMENT_ID HERE",
url="https://us-south.ml.cloud.ibm.com",
project_id="PASTE YOUR PROJECT_ID HERE",
params=parameters,
)
調用
若要取得完成結果,您可以直接使用字串提示呼叫模型。
# Invocation
messages = [
("system", "You are a helpful assistant that translates English to French."),
(
"human",
"I love you for listening to Rock.",
),
]
chat.invoke(messages)
AIMessage(content="J'adore que tu escois de écouter de la rock ! ", additional_kwargs={}, response_metadata={'token_usage': {'completion_tokens': 19, 'prompt_tokens': 34, 'total_tokens': 53}, 'model_name': 'ibm/granite-34b-code-instruct', 'system_fingerprint': '', 'finish_reason': 'stop'}, id='chat-ef888fc41f0d4b37903b622250ff7528', usage_metadata={'input_tokens': 34, 'output_tokens': 19, 'total_tokens': 53})
# Invocation multiple chat
from langchain_core.messages import (
HumanMessage,
SystemMessage,
)
system_message = SystemMessage(
content="You are a helpful assistant which telling short-info about provided topic."
)
human_message = HumanMessage(content="horse")
chat.invoke([system_message, human_message])
AIMessage(content='horses are quadrupedal mammals that are members of the family Equidae. They are typically farm animals, competing in horse racing and other forms of equine competition. With over 200 breeds, horses are diverse in their physical appearance and behavior. They are intelligent, social animals that are often used for transportation, food, and entertainment.', additional_kwargs={}, response_metadata={'token_usage': {'completion_tokens': 89, 'prompt_tokens': 29, 'total_tokens': 118}, 'model_name': 'ibm/granite-34b-code-instruct', 'system_fingerprint': '', 'finish_reason': 'stop'}, id='chat-9a6e28abb3d448aaa4f83b677a9fd653', usage_metadata={'input_tokens': 29, 'output_tokens': 89, 'total_tokens': 118})
串鏈
建立 ChatPromptTemplate
物件,它將負責建立隨機問題。
from langchain_core.prompts import ChatPromptTemplate
system = (
"You are a helpful assistant that translates {input_language} to {output_language}."
)
human = "{input}"
prompt = ChatPromptTemplate.from_messages([("system", system), ("human", human)])
提供輸入並執行鏈。
chain = prompt | chat
chain.invoke(
{
"input_language": "English",
"output_language": "German",
"input": "I love Python",
}
)
AIMessage(content='Ich liebe Python.', additional_kwargs={}, response_metadata={'token_usage': {'completion_tokens': 7, 'prompt_tokens': 28, 'total_tokens': 35}, 'model_name': 'ibm/granite-34b-code-instruct', 'system_fingerprint': '', 'finish_reason': 'stop'}, id='chat-fef871190b6047a7a3e68c58b3810c33', usage_metadata={'input_tokens': 28, 'output_tokens': 7, 'total_tokens': 35})
串流模型輸出
您可以串流模型輸出。
system_message = SystemMessage(
content="You are a helpful assistant which telling short-info about provided topic."
)
human_message = HumanMessage(content="moon")
for chunk in chat.stream([system_message, human_message]):
print(chunk.content, end="")
The Moon is the fifth largest moon in the solar system and the largest relative to its host planet. It is the fifth brightest object in Earth's night sky after the Sun, the stars, the Milky Way, and the Moon itself. It orbits around the Earth at an average distance of 238,855 miles (384,400 kilometers). The Moon's gravity is about one-sixthth of Earth's and thus allows for the formation of tides on Earth. The Moon is thought to have formed around 4.5 billion years ago from debris from a collision between Earth and a Mars-sized body named Theia. The Moon is effectively immutable, with its current characteristics remaining from formation. Aside from Earth, the Moon is the only other natural satellite of Earth. The most widely accepted theory is that it formed from the debris of a collision
批次處理模型輸出
您可以批次處理模型輸出。
message_1 = [
SystemMessage(
content="You are a helpful assistant which telling short-info about provided topic."
),
HumanMessage(content="cat"),
]
message_2 = [
SystemMessage(
content="You are a helpful assistant which telling short-info about provided topic."
),
HumanMessage(content="dog"),
]
chat.batch([message_1, message_2])
[AIMessage(content='The cat is a popular domesticated carnivorous mammal that belongs to the family Felidae. Cats arefriendly, intelligent, and independent animals that are well-known for their playful behavior, agility, and ability to hunt prey. cats come in a wide range of breeds, each with their own unique physical and behavioral characteristics. They are kept as pets worldwide due to their affectionate nature and companionship. Cats are important members of the household and are often involved in everything from childcare to entertainment.', additional_kwargs={}, response_metadata={'token_usage': {'completion_tokens': 127, 'prompt_tokens': 28, 'total_tokens': 155}, 'model_name': 'ibm/granite-34b-code-instruct', 'system_fingerprint': '', 'finish_reason': 'stop'}, id='chat-fa452af0a0fa4a668b6a704aecd7d718', usage_metadata={'input_tokens': 28, 'output_tokens': 127, 'total_tokens': 155}),
AIMessage(content='Dogs are domesticated animals that belong to the Canidae family, also known as wolves. They are one of the most popular pets worldwide, known for their loyalty and affection towards their owners. Dogs come in various breeds, each with unique characteristics, and are trained for different purposes such as hunting, herding, or guarding. They require a lot of exercise and mental stimulation to stay healthy and happy, and they need proper training and socialization to be well-behaved. Dogs are also known for their playful and energetic nature, making them great companions for people of all ages.', additional_kwargs={}, response_metadata={'token_usage': {'completion_tokens': 144, 'prompt_tokens': 28, 'total_tokens': 172}, 'model_name': 'ibm/granite-34b-code-instruct', 'system_fingerprint': '', 'finish_reason': 'stop'}, id='chat-cae7663c50cf4f3499726821cc2f0ec7', usage_metadata={'input_tokens': 28, 'output_tokens': 144, 'total_tokens': 172})]
工具呼叫
ChatWatsonx.bind_tools()
請注意,ChatWatsonx.bind_tools
處於 Beta 狀態,因此我們建議使用 mistralai/mistral-large
模型。
from langchain_ibm import ChatWatsonx
chat = ChatWatsonx(
model_id="mistralai/mistral-large",
url="https://us-south.ml.cloud.ibm.com",
project_id="PASTE YOUR PROJECT_ID HERE",
params=parameters,
)
from pydantic import BaseModel, Field
class GetWeather(BaseModel):
"""Get the current weather in a given location"""
location: str = Field(..., description="The city and state, e.g. San Francisco, CA")
llm_with_tools = chat.bind_tools([GetWeather])
ai_msg = llm_with_tools.invoke(
"Which city is hotter today: LA or NY?",
)
ai_msg
AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'chatcmpl-tool-6c06a19bbe824d78a322eb193dbde12d', 'type': 'function', 'function': {'name': 'GetWeather', 'arguments': '{"location": "Los Angeles, CA"}'}}, {'id': 'chatcmpl-tool-493542e46f1141bfbfeb5deae6c9e086', 'type': 'function', 'function': {'name': 'GetWeather', 'arguments': '{"location": "New York, NY"}'}}]}, response_metadata={'token_usage': {'completion_tokens': 46, 'prompt_tokens': 95, 'total_tokens': 141}, 'model_name': 'mistralai/mistral-large', 'system_fingerprint': '', 'finish_reason': 'tool_calls'}, id='chat-027f2bdb217e4238909cb26d3e8a8fbf', tool_calls=[{'name': 'GetWeather', 'args': {'location': 'Los Angeles, CA'}, 'id': 'chatcmpl-tool-6c06a19bbe824d78a322eb193dbde12d', 'type': 'tool_call'}, {'name': 'GetWeather', 'args': {'location': 'New York, NY'}, 'id': 'chatcmpl-tool-493542e46f1141bfbfeb5deae6c9e086', 'type': 'tool_call'}], usage_metadata={'input_tokens': 95, 'output_tokens': 46, 'total_tokens': 141})
AIMessage.tool_calls
請注意,AIMessage 具有 tool_calls
屬性。這包含模型供應商不可知的標準化 ToolCall 格式。
ai_msg.tool_calls
[{'name': 'GetWeather',
'args': {'location': 'Los Angeles, CA'},
'id': 'chatcmpl-tool-6c06a19bbe824d78a322eb193dbde12d',
'type': 'tool_call'},
{'name': 'GetWeather',
'args': {'location': 'New York, NY'},
'id': 'chatcmpl-tool-493542e46f1141bfbfeb5deae6c9e086',
'type': 'tool_call'}]
API 參考
如需所有 ChatWatsonx
功能和組態的詳細文件,請前往API 參考。