Skip to main content
Oracle Cloud Infrastructure(OCI)生成式 AI 是一项完全托管的服务,通过单一 API 提供一系列先进的可定制大型语言模型(LLM),覆盖广泛的使用场景。 使用 OCI 生成式 AI 服务,您可以访问现成可用的预训练模型,或在专用 AI 集群上基于自有数据创建并托管微调的自定义模型。详细的服务和 API 文档请参阅此处此处 本 notebook 说明如何使用 OCI 生成式 AI 补全模型与 LangChain 配合使用。

设置

确保已安装 oci sdk 和 langchain-community 包。
!pip install -U oci langchain-community

使用方法

from langchain_community.llms.oci_generative_ai import OCIGenAI

llm = OCIGenAI(
    model_id="cohere.command",
    service_endpoint="https://inference.generativeai.us-chicago-1.oci.oraclecloud.com",
    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="https://inference.generativeai.us-chicago-1.oci.oraclecloud.com",
    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="https://inference.generativeai.us-chicago-1.oci.oraclecloud.com",
    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)

认证

LlamaIndex 支持的认证方式与其他 OCI 服务相同,遵循标准 SDK 认证方法,具体包括 API 密钥、会话令牌、实例主体和资源主体。 以上示例中默认使用 API 密钥认证。以下示例演示如何使用其他认证方式(会话令牌):
llm = OCIGenAI(
    model_id="cohere.command",
    service_endpoint="https://inference.generativeai.us-chicago-1.oci.oraclecloud.com",
    compartment_id="MY_OCID",
    auth_type="SECURITY_TOKEN",
    auth_profile="MY_PROFILE",  # replace with your profile name
    auth_file_location="MY_CONFIG_FILE_LOCATION",  # replace with file location where profile name configs present
)

专用 AI 集群

要访问托管在专用 AI 集群中的模型,请创建一个端点,其分配的 OCID(当前以 ‘ocid1.generativeaiendpoint.oc1.us-chicago-1’ 为前缀)将用作您的模型 ID。 访问托管在专用 AI 集群中的模型时,需要使用两个额外的必填参数(“provider” 和 “context_size”)初始化 OCIGenAI 接口。
llm = OCIGenAI(
    model_id="ocid1.generativeaiendpoint.oc1.us-chicago-1....",
    service_endpoint="https://inference.generativeai.us-chicago-1.oci.oraclecloud.com",
    compartment_id="DEDICATED_COMPARTMENT_OCID",
    auth_profile="MY_PROFILE",  # replace with your profile name,
    auth_file_location="MY_CONFIG_FILE_LOCATION",  # replace with file location where profile name configs present
    provider="MODEL_PROVIDER",  # e.g., "cohere" or "meta"
    context_size="MODEL_CONTEXT_SIZE",  # e.g., 128000
)