跳至主要内容

ChatGoogleGenerativeAI

Google AI 提供了许多不同的聊天模型,包括强大的 Gemini 系列。有关最新模型、功能、上下文窗口等的信息,请前往 Google AI 文档.

这将帮助您开始使用 ChatGoogleGenerativeAI 聊天模型。有关所有 ChatGoogleGenerativeAI 功能和配置的详细文档,请前往 API 参考.

概述

集成详细信息

本地可序列化PY 支持包下载包最新
ChatGoogleGenerativeAI@langchain/google-genaiNPM - DownloadsNPM - Version

模型功能

请参阅下方表头中的链接,了解如何使用特定功能的指南。

工具调用结构化输出JSON 模式图像输入音频输入视频输入令牌级流式传输令牌使用Logprobs

设置

您可以通过 @langchain/google-genai 集成包中的 ChatGoogleGenerativeAI 类访问 Google 的 geminigemini-vision 模型,以及 LangChain 中的其他生成模型。

提示

您也可以通过 LangChain VertexAI 和 VertexAI-web 集成访问 Google 的 gemini 模型系列。

点击这里阅读文档。

凭据

在这里获取 API 密钥:https://ai.google.dev/tutorials/setup

然后设置 GOOGLE_API_KEY 环境变量

export GOOGLE_API_KEY="your-api-key"

如果您想自动跟踪模型调用,您还可以通过取消注释以下内容来设置您的LangSmith API 密钥

# export LANGCHAIN_TRACING_V2="true"
# export LANGCHAIN_API_KEY="your-api-key"

安装

LangChain ChatGoogleGenerativeAI 集成位于 @langchain/google-genai 包中

yarn add @langchain/google-genai

实例化

现在我们可以实例化我们的模型对象并生成聊天完成

import { ChatGoogleGenerativeAI } from "@langchain/google-genai";

const llm = new ChatGoogleGenerativeAI({
model: "gemini-1.5-pro",
temperature: 0,
maxRetries: 2,
// other params...
});

调用

const aiMsg = await llm.invoke([
[
"system",
"You are a helpful assistant that translates English to French. Translate the user sentence.",
],
["human", "I love programming."],
]);
aiMsg;
AIMessage {
"content": "J'adore programmer. \n",
"additional_kwargs": {
"finishReason": "STOP",
"index": 0,
"safetyRatings": [
{
"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
"probability": "NEGLIGIBLE"
},
{
"category": "HARM_CATEGORY_HATE_SPEECH",
"probability": "NEGLIGIBLE"
},
{
"category": "HARM_CATEGORY_HARASSMENT",
"probability": "NEGLIGIBLE"
},
{
"category": "HARM_CATEGORY_DANGEROUS_CONTENT",
"probability": "NEGLIGIBLE"
}
]
},
"response_metadata": {
"finishReason": "STOP",
"index": 0,
"safetyRatings": [
{
"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
"probability": "NEGLIGIBLE"
},
{
"category": "HARM_CATEGORY_HATE_SPEECH",
"probability": "NEGLIGIBLE"
},
{
"category": "HARM_CATEGORY_HARASSMENT",
"probability": "NEGLIGIBLE"
},
{
"category": "HARM_CATEGORY_DANGEROUS_CONTENT",
"probability": "NEGLIGIBLE"
}
]
},
"tool_calls": [],
"invalid_tool_calls": [],
"usage_metadata": {
"input_tokens": 21,
"output_tokens": 5,
"total_tokens": 26
}
}
console.log(aiMsg.content);
J'adore programmer.

链接

我们可以链接我们的模型与提示模板,如下所示

import { ChatPromptTemplate } from "@langchain/core/prompts";

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

const chain = prompt.pipe(llm);
await chain.invoke({
input_language: "English",
output_language: "German",
input: "I love programming.",
});
AIMessage {
"content": "Ich liebe das Programmieren. \n",
"additional_kwargs": {
"finishReason": "STOP",
"index": 0,
"safetyRatings": [
{
"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
"probability": "NEGLIGIBLE"
},
{
"category": "HARM_CATEGORY_HATE_SPEECH",
"probability": "NEGLIGIBLE"
},
{
"category": "HARM_CATEGORY_HARASSMENT",
"probability": "NEGLIGIBLE"
},
{
"category": "HARM_CATEGORY_DANGEROUS_CONTENT",
"probability": "NEGLIGIBLE"
}
]
},
"response_metadata": {
"finishReason": "STOP",
"index": 0,
"safetyRatings": [
{
"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
"probability": "NEGLIGIBLE"
},
{
"category": "HARM_CATEGORY_HATE_SPEECH",
"probability": "NEGLIGIBLE"
},
{
"category": "HARM_CATEGORY_HARASSMENT",
"probability": "NEGLIGIBLE"
},
{
"category": "HARM_CATEGORY_DANGEROUS_CONTENT",
"probability": "NEGLIGIBLE"
}
]
},
"tool_calls": [],
"invalid_tool_calls": [],
"usage_metadata": {
"input_tokens": 16,
"output_tokens": 7,
"total_tokens": 23
}
}

安全设置

Gemini 模型具有可以覆盖的默认安全设置。如果您从模型中收到大量“安全警告”,您可以尝试调整模型的安全设置属性。例如,要关闭对危险内容的安全阻止,您可以从 @google/generative-ai 包中导入枚举,然后按如下所示构建您的 LLM

import { ChatGoogleGenerativeAI } from "@langchain/google-genai";
import { HarmBlockThreshold, HarmCategory } from "@google/generative-ai";

const llmWithSafetySettings = new ChatGoogleGenerativeAI({
model: "gemini-1.5-pro",
temperature: 0,
safetySettings: [
{
category: HarmCategory.HARM_CATEGORY_HARASSMENT,
threshold: HarmBlockThreshold.BLOCK_LOW_AND_ABOVE,
},
],
// other params...
});

工具调用

使用 Google AI 进行工具调用与使用其他模型进行工具调用基本相同,但对模式有一些限制。

Google AI API 不允许工具模式包含具有未知属性的对象。例如,以下 Zod 模式将引发错误

const invalidSchema = z.object({ properties: z.record(z.unknown()) });

const invalidSchema2 = z.record(z.unknown());

相反,您应该显式定义对象字段的属性。以下是一个示例

import { tool } from "@langchain/core/tools";
import { ChatGoogleGenerativeAI } from "@langchain/google-genai";
import { z } from "zod";

// Define your tool
const fakeBrowserTool = tool(
(_) => {
return "The search result is xyz...";
},
{
name: "browser_tool",
description:
"Useful for when you need to find something on the web or summarize a webpage.",
schema: z.object({
url: z.string().describe("The URL of the webpage to search."),
query: z.string().optional().describe("An optional search query to use."),
}),
}
);

const llmWithTool = new ChatGoogleGenerativeAI({
model: "gemini-pro",
}).bindTools([fakeBrowserTool]); // Bind your tools to the model

const toolRes = await llmWithTool.invoke([
[
"human",
"Search the web and tell me what the weather will be like tonight in new york. use a popular weather website",
],
]);

console.log(toolRes.tool_calls);
[
{
name: 'browser_tool',
args: {
url: 'https://www.weather.com',
query: 'weather tonight in new york'
},
type: 'tool_call'
}
]

Gemini 提示常见问题解答

截至撰写本文档时(2023/12/12),Gemini 对其接受的提示的类型和结构有一些限制。具体来说

  1. 当提供多模态(图像)输入时,您最多只能使用 1 条“人类”(用户)类型的消息。您不能传递多条消息(尽管单条人类消息可能包含多个内容条目)
  2. 系统消息不受原生支持,如果存在,将与第一条人类消息合并。
  3. 对于常规的聊天对话,消息必须遵循人类/人工智能/人类/人工智能交替模式。您不能连续提供 2 条人工智能或人类消息。
  4. 如果消息违反了 LLM 的安全检查,可能会被阻止。在这种情况下,模型将返回空响应。

API 参考

有关所有 ChatGoogleGenerativeAI 功能和配置的详细文档,请前往 API 参考:https://api.js.langchain.com/classes/langchain_google_genai.ChatGoogleGenerativeAI.html


此页面对您有帮助吗?


您也可以在 GitHub 上留下详细的反馈 on GitHub.