在本文中,我们将介绍如何使用Amazon Bedrock在文本嵌入任务中。Amazon Bedrock是一款强大的工具,能够帮助我们将文本转换为高维向量,这在NLP任务中非常有用。例如,我们可以将文本嵌入用在文本相似度计算、信息检索和分类等任务中。
安装LlamaIndex模块
在开始之前,我们需要安装LlamaIndex模块,这个模块提供了对Bedrock嵌入的支持。
%pip install llama-index-embeddings-bedrock
使用Bedrock进行文本嵌入
接下来,我们将展示如何使用BedrockEmbedding类进行文本嵌入。我们需要提供AWS的访问密钥和会话令牌等信息。
import os
from llama_index.embeddings.bedrock import BedrockEmbedding
embed_model = BedrockEmbedding(
aws_access_key_id=os.getenv("AWS_ACCESS_KEY_ID"),
aws_secret_access_key=os.getenv("AWS_SECRET_ACCESS_KEY"),
aws_session_token=os.getenv("AWS_SESSION_TOKEN"),
region_name="<aws-region>",
profile_name="<aws-profile>",
)
embedding = embed_model.get_text_embedding("hello world")
print(embedding)
列出支持的模型
我们可以调用 list_supported_models() 方法来查看Amazon Bedrock在LlamaIndex中支持的所有模型。
from llama_index.embeddings.bedrock import BedrockEmbedding
import json
supported_models = BedrockEmbedding.list_supported_models()
print(json.dumps(supported_models, indent=2))
使用Amazon Titan模型进行文本嵌入
我们可以选择使用Amazon Titan嵌入模型进行文本嵌入。
from llama_index.embeddings.bedrock import BedrockEmbedding
model = BedrockEmbedding(model="amazon.titan-embed-g1-text-02")
embeddings = model.get_text_embedding("hello world")
print(embeddings)
使用Cohere英语模型进行文本嵌入
我们还可以选择使用Cohere的英语嵌入模型。
model = BedrockEmbedding(model="cohere.embed-english-v3")
coherePayload = ["This is a test document", "This is another test document"]
embed1 = model.get_text_embedding("This is a test document")
print(embed1)
embeddings = model.get_text_embedding_batch(coherePayload)
print(embeddings)
使用Cohere多语言模型进行文本嵌入
对于多语言文本,我们可以使用Cohere的多语言嵌入模型。
model = BedrockEmbedding(model="cohere.embed-multilingual-v3")
coherePayload = [
"This is a test document",
"తెలుగు అనేది ద్రావిడ భాషల కుటుంబానికి చెందిన భాష.",
"Esto es una prueba de documento multilingüe.",
"攻殻機動隊",
"Combien de temps ça va prendre ?",
"Документ проверен",
]
embeddings = model.get_text_embedding_batch(coherePayload)
print(embeddings)
常见错误与解决方法
-
认证错误
- 确保AWS访问密钥和会话令牌正确配置。
- 错误信息示例:
Invalid AWS credentials. - 解决方案: 检查并重新配置环境变量或AWS配置文件。
-
模型不支持
- 确保选择的模型在当前区域和API版本中受支持。
- 错误信息示例:
Model not supported. - 解决方案: 通过
list_supported_models()检查支持的模型,选择合适的模型。
-
网络问题
- 确保网络连接正常,能够访问AWS服务。
- 错误信息示例:
Network connection error. - 解决方案: 检查网络连接,或选择稳定的网络环境。
如果你觉得这篇文章对你有帮助,请点赞,关注我的博客,谢谢!
参考资料:

627

被折叠的 条评论
为什么被折叠?



