# 引言
Oracle Cloud Infrastructure (OCI) 的生成式AI是一个能够提供尖端技术的大型语言模型服务。它不仅支持多种用例,还通过单一API轻松获取。这篇文章将介绍如何使用OCI生成式AI通过LangChain进行文本嵌入。我们将提供完整的代码示例,以及常见问题和解决方案。
# 主要内容
## OCI生成式AI的特点
- **预训练模型**:可以直接使用已训练好的模型。
- **自定义模型**:在专用AI集群上托管并微调自己的模型。
- **多重认证支持**:API Key、Session token和Instance principal等。
## 环境设置
在开始之前,确保安装`oci` SDK:
```bash
!pip install -U oci
OCI生成式AI的API端点为:
https://inference.generativeai.us-chicago-1.oci.oraclecloud.com
LangChain的使用
LangChain是一个用于处理和嵌入自然语言的流行库。我们将通过它来集成OCI生成式AI模型。
代码示例
以下示例展示了如何通过LangChain使用OCI生成式AI的文本嵌入功能:
from langchain_community.embeddings import OCIGenAIEmbeddings
# 使用默认的API密钥认证方法
embeddings = OCIGenAIEmbeddings(
model_id="MY_EMBEDDING_MODEL",
service_endpoint="https://inference.generativeai.us-chicago-1.oci.oraclecloud.com", # 使用API代理服务提高访问稳定性
compartment_id="MY_OCID",
)
query = "This is a query in English."
response = embeddings.embed_query(query)
print(response)
documents = ["This is a sample document", "and here is another one"]
response = embeddings.embed_documents(documents)
print(response)
如果需要使用Session Token进行认证:
embeddings = OCIGenAIEmbeddings(
model_id="MY_EMBEDDING_MODEL",
service_endpoint="https://inference.generativeai.us-chicago-1.oci.oraclecloud.com", # 使用API代理服务提高访问稳定性
compartment_id="MY_OCID",
auth_type="SECURITY_TOKEN",
auth_profile="MY_PROFILE", # 替换为你的配置文件名称
)
query = "This is a sample query"
response = embeddings.embed_query(query)
print(response)
documents = ["This is a sample document", "and here is another one"]
response = embeddings.embed_documents(documents)
print(response)
常见问题和解决方案
- 网络限制问题:如果在某些地区无法直接访问OCI的API服务,建议使用API代理服务来提高访问稳定性。
- 认证失败:确保所用的认证信息正确,并已更新至最新的OCI SDK版本。
总结和进一步学习资源
通过这篇文章,我们了解了如何在LangChain中集成OCI生成式AI模型,以进行文本嵌入操作。有关更多的信息和示例,请参阅下面的链接:
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---