IBM watsonx.ai
WatsonxEmbeddings 是 IBM watsonx.ai 基础模型的封装。
此示例演示了如何使用 LangChain
与 watsonx.ai
模型进行通信。
设置
安装包 langchain-ibm
。
!pip install -qU langchain-ibm
此单元定义了与 watsonx Embeddings 一起使用所需的 WML 凭据。
操作: 提供 IBM Cloud 用户 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"
加载模型
您可能需要为不同的模型调整 parameters
。
from ibm_watsonx_ai.metanames import EmbedTextParamsMetaNames
embed_params = {
EmbedTextParamsMetaNames.TRUNCATE_INPUT_TOKENS: 3,
EmbedTextParamsMetaNames.RETURN_OPTIONS: {"input_text": True},
}
使用之前设置的参数初始化 WatsonxEmbeddings
类。
注意:
- 为了提供 API 调用的上下文,您必须添加
project_id
或space_id
。有关更多信息,请参见 documentation。 - 根据您所配置的服务实例的区域,使用 这里 描述的其中一个 URL。
在此示例中,我们将使用 project_id
和达拉斯 URL。
您需要指定将用于推理的 model_id
。
from langchain_ibm import WatsonxEmbeddings
watsonx_embedding = WatsonxEmbeddings(
model_id="ibm/slate-125m-english-rtrvr",
url="https://us-south.ml.cloud.ibm.com",
project_id="PASTE YOUR PROJECT_ID HERE",
params=embed_params,
)
您也可以使用 Cloud Pak for Data 凭据。有关详细信息,请参见 documentation。
watsonx_embedding = WatsonxEmbeddings(
model_id="ibm/slate-125m-english-rtrvr",
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=embed_params,
)
对于某些要求,可以将 IBM 的 APIClient
对象传递到 WatsonxEmbeddings
类中。
from ibm_watsonx_ai import APIClient
api_client = APIClient(...)
watsonx_llm = WatsonxEmbeddings(
model_id="ibm/slate-125m-english-rtrvr",
watsonx_client=api_client,
)
用法
嵌入查询
text = "This is a test document."
query_result = watsonx_embedding.embed_query(text)
query_result[:5]
[0.0094472, -0.024981909, -0.026013248, -0.040483925, -0.057804465]
嵌入文档
texts = ["This is a content of the document", "This is another document"]
doc_result = watsonx_embedding.embed_documents(texts)
doc_result[0][:5]
[0.009447193, -0.024981918, -0.026013244, -0.040483937, -0.057804447]