Google Vertex AI
Google Vertex 是一项服务,提供了
Google Cloud 中可用的所有基础模型,例如
gemini-1.5-pro、gemini-1.5-flash 等。
这将帮助您通过 LangChain 开始使用 VertexAI 补全模型(LLMs)。有关
VertexAI 功能和配置选项的详细文档,请参阅API
参考文档。
概述
集成详情
| 类别 | 包 | 本地支持 | 可序列化 | PY 支持 | 包下载量 | 最新版本 |
|---|---|---|---|---|---|---|
| VertexAI | @langchain/google-vertexai | ❌ | ✅ | ✅ | ![]() | ![]() |
准备工作
LangChain.js 支持两种不同的认证方式,具体取决于您是在 Node.js 环境还是 Web 环境中运行。
要访问 VertexAI 模型,您需要创建一个 Google Cloud Platform (GCP)
账号,获取 API 密钥,并安装 @langchain/google-vertexai 集成包。
凭证
Node.js
您应确保 Vertex AI API 对相关项目是启用状态,并且已通过以下任一方式对 Google Cloud 进行了身份验证:
- 您已登录一个允许访问该项目的账户(使用
gcloud auth application-default login)。 - 您正在一台使用允许访问该项目的服务账户的机器上运行。
- 您已下载允许访问该项目的服务账户凭证,并将
GOOGLE_APPLICATION_CREDENTIALS环境变量设置为该文件的路径。 或 - 您将
GOOGLE_API_KEY环境变量设置为该项目的 API 密钥。
Web
在 Web 环境中(例如 Edge 函数)调用 Vertex AI 模型时,您需要安装
@langchain/google-vertexai-web 包。
然后,您需要将您的服务账户凭据直接作为
GOOGLE_VERTEX_AI_WEB_CREDENTIALS 环境变量添加:
GOOGLE_VERTEX_AI_WEB_CREDENTIALS={"type":"service_account","project_id":"YOUR_PROJECT-12345",...}
您也可以像这样在代码中直接传入您的凭据:
import { VertexAI } from "@langchain/google-vertexai";
// 如果您使用的是 Web 版本,请取消下一行的注释:
// import { VertexAI } from "@langchain/google-vertexai-web";
const model = new VertexAI({
authOptions: {
credentials: {"type":"service_account","project_id":"YOUR_PROJECT-12345",...},
},
});
如果您希望对模型调用进行自动追踪,也可以通过取消以下注释来设置您的 LangSmith API 密钥:
# export LANGSMITH_TRACING="true"
# export LANGSMITH_API_KEY="your-api-key"
安装
LangChain VertexAI 集成位于 @langchain/google-vertexai 包中:
:::提示 请参阅安装集成包的一般说明部分。 :::
- npm
- yarn
- pnpm
npm i @langchain/google-vertexai @langchain/core
yarn add @langchain/google-vertexai @langchain/core
pnpm add @langchain/google-vertexai @langchain/core
或针对 Web 环境:
- npm
- yarn
- pnpm
npm i @langchain/google-vertexai-web @langchain/core
yarn add @langchain/google-vertexai-web @langchain/core
pnpm add @langchain/google-vertexai-web @langchain/core
实例化
现在我们可以实例化我们的模型对象并生成聊天补全:
import { VertexAI } from "@langchain/google-vertexai-web";
const llm = new VertexAI({
model: "gemini-pro",
temperature: 0,
maxRetries: 2,
// other params...
});
调用
const inputText = "VertexAI is an AI company that ";
const completion = await llm.invoke(inputText);
completion;
为企业和开发者提供广泛的云计算服务和人工智能解决方案。
链式调用
我们可以将补全模型与提示模板以如下方式进行链式调用:
import { PromptTemplate } from "@langchain/core/prompts";
const prompt = PromptTemplate.fromTemplate(
"How to say {input} in {output_language}:\n"
);
const chain = prompt.pipe(llm);
await chain.invoke({
output_language: "German",
input: "I love programming.",
});
"我爱编程。"
发音指南:
Ich: [ɪç](类似于 "ikh",带有轻柔的 "ch" 音)
liebe: [ˈliːbə](LEE-buh)
Programmieren: [pʁoɡʁaˈmiːʁən](pro-gra-MEE-ren)
你也可以这样说:
"Ich liebe es zu programmieren."
更直译的意思是 "我喜欢编程。" 这个版本稍微正式或准确一些。
发音:
es: [ɛs](像字母 "S" 的发音)
zu: [tsuː](tsoo)
两个版本都是正确的,而且都很常用。
API 参考文档
如需了解所有 VertexAI 功能和配置的详细文档,请访问 API 参考页面: https://api.js.langchain.com/classes/langchain_google_vertexai.VertexAI.html
Related
- LLM conceptual guide
- LLM how-to guides

