Skip to main content
Open In ColabOpen on GitHub

oci_generative_ai

Oracle Cloud Infrastructure 生成式AI

Oracle Cloud Infrastructure (OCI) 生成式 AI 是一项完全托管的服务,提供了多种高度先进的可自定义的大语言模型(LLMs),这些模型覆盖了广泛的用例,并可通过单一 API 获取。 使用 OCI 生成式 AI 服务,您可以访问预训练的现成模型,或基于您自己的数据在专用 AI 集群上创建和托管自定义微调模型。有关该服务和 API 的详细文档请参阅 这里这里

本笔记本介绍了如何将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)
API 参考:OCIGenAI

链式调用与提示模板

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)
API 参考:提示模板

流式传输

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
)