Google GenAI Chat
Google GenAI API 允许开发者通过 Gemini Developer API 或 Vertex AI 使用 Google 的 Gemini 模型构建生成式 AI 应用程序。Google GenAI API 支持多模态提示作为输入,并输出文本或代码。多模态模型能够处理来自多种模态的信息,包括图像、视频和文本。例如,您可以向模型发送一盘饼干的照片,并要求它提供这些饼干的食谱。
Gemini 是 Google DeepMind 开发的生成式 AI 模型家族,专为多模态用例设计。Gemini API 允许您访问 Gemini 2.0 Flash、Gemini 2.0 Flash-Lite 和 Gemini Pro 模型。
此实现提供了两种身份验证模式
-
Gemini Developer API:使用 API 密钥进行快速原型开发和开发
-
Vertex AI:使用 Google Cloud 凭据进行具有企业功能的生产部署
先决条件
选择以下身份验证方法之一
选项 1:Gemini Developer API(API 密钥)
-
从 Google AI Studio 获取 API 密钥
-
将 API 密钥设置为环境变量或应用程序属性
选项 2:Vertex AI (Google Cloud)
-
安装适用于您的操作系统的 gcloud CLI。
-
通过运行以下命令进行身份验证。将
PROJECT_ID替换为您的 Google Cloud 项目 ID,将ACCOUNT替换为您的 Google Cloud 用户名。
gcloud config set project <PROJECT_ID> &&
gcloud auth application-default login <ACCOUNT>
自动配置
|
Spring AI 自动配置、启动模块的工件名称发生了重大变化。请参阅 升级说明 以获取更多信息。 |
Spring AI 为 Google GenAI Chat 客户端提供 Spring Boot 自动配置。要启用它,请将以下依赖项添加到您项目的 Maven pom.xml 或 Gradle build.gradle 构建文件
-
Maven
-
Gradle
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-google-genai</artifactId>
</dependency>
dependencies {
implementation 'org.springframework.ai:spring-ai-starter-model-google-genai'
}
| 请参阅 依赖项管理 部分,将 Spring AI BOM 添加到您的构建文件中。 |
聊天属性
|
聊天自动配置的启用和禁用现在通过以 要启用,`spring.ai.model.chat=google-genai`(默认启用) 要禁用,`spring.ai.model.chat=none`(或任何与 `google-genai` 不匹配的值) 此更改是为了允许配置多个模型。 |
连接属性
前缀 `spring.ai.google.genai` 用作属性前缀,允许您连接到 Google GenAI。
| 财产 | 描述 | 默认值 |
|---|---|---|
spring.ai.model.chat |
启用聊天模型客户端 |
google-genai |
spring.ai.google.genai.api-key |
Gemini Developer API 的 API 密钥。如果提供,客户端将使用 Gemini Developer API 而不是 Vertex AI。 |
- |
spring.ai.google.genai.project-id |
Google Cloud Platform 项目 ID(Vertex AI 模式必需) |
- |
spring.ai.google.genai.location |
Google Cloud 区域(Vertex AI 模式必需) |
- |
spring.ai.google.genai.credentials-uri |
Google Cloud 凭据的 URI。如果提供,它将用于创建 `GoogleCredentials` 实例进行身份验证。 |
- |
聊天模型属性
前缀 `spring.ai.google.genai.chat` 是属性前缀,允许您配置 Google GenAI Chat 的聊天模型实现。
| 财产 | 描述 | 默认值 |
|---|---|---|
spring.ai.google.genai.chat.options.model |
支持的 Google GenAI 聊天模型包括 `gemini-2.0-flash`、`gemini-2.0-flash-lite`、`gemini-pro` 和 `gemini-1.5-flash`。 |
gemini-2.0-flash |
spring.ai.google.genai.chat.options.response-mime-type |
生成候选文本的输出响应 MIME 类型。 |
`text/plain`:(默认)文本输出或 `application/json`:JSON 响应。 |
spring.ai.google.genai.chat.options.google-search-retrieval |
使用 Google 搜索 Grounding 功能 |
`true` 或 `false`,默认 `false`。 |
spring.ai.google.genai.chat.options.temperature |
控制输出的随机性。值范围为 [0.0,1.0],包括。值越接近 1.0 将产生更多样化的响应,而值越接近 0.0 通常会导致生成器的响应不那么令人惊讶。 |
0.7 |
spring.ai.google.genai.chat.options.top-k |
采样时要考虑的最大令牌数。生成器使用 Top-k 和 nucleus 采样相结合。Top-k 采样考虑 topK 个最可能的令牌集。 |
- |
spring.ai.google.genai.chat.options.top-p |
采样时要考虑的令牌的最大累积概率。生成器使用 Top-k 和 nucleus 采样相结合。nucleus 采样考虑概率和至少为 topP 的最小令牌集。 |
- |
spring.ai.google.genai.chat.options.candidate-count |
要返回的生成响应消息的数量。此值必须在 [1, 8] 之间,包括。默认为 1。 |
1 |
spring.ai.google.genai.chat.options.max-output-tokens |
要生成的最大令牌数。 |
- |
spring.ai.google.genai.chat.options.frequency-penalty |
用于减少重复的频率惩罚。 |
- |
spring.ai.google.genai.chat.options.presence-penalty |
用于减少重复的出现惩罚。 |
- |
spring.ai.google.genai.chat.options.thinking-budget |
思考过程的思考预算。 |
- |
spring.ai.google.genai.chat.options.tool-names |
工具列表,通过其名称标识,用于在单个提示请求中启用函数调用。具有这些名称的工具必须存在于 ToolCallback 注册表中。 |
- |
spring.ai.google.genai.chat.options.tool-callbacks |
要注册到 ChatModel 的工具回调。 |
- |
spring.ai.google.genai.chat.options.internal-tool-execution-enabled |
如果为 true,则应执行工具,否则将模型响应返回给用户。默认为 null,但如果为 null,则将考虑 `ToolCallingChatOptions.DEFAULT_TOOL_EXECUTION_ENABLED`(为 true) |
- |
spring.ai.google.genai.chat.options.safety-settings |
用于控制安全过滤器的安全设置列表,如 Google GenAI 安全设置 所定义。每个安全设置都可以有一个方法、阈值和类别。 |
- |
| 所有以 `spring.ai.google.genai.chat.options` 为前缀的属性都可以在运行时通过向 `Prompt` 调用添加特定请求的 运行时选项 来覆盖。 |
运行时选项
GoogleGenAiChatOptions.java 提供模型配置,例如温度、topK 等。
在启动时,可以使用 `GoogleGenAiChatModel(client, options)` 构造函数或 `spring.ai.google.genai.chat.options.*` 属性配置默认选项。
在运行时,您可以通过向 `Prompt` 调用添加新的特定请求选项来覆盖默认选项。例如,要覆盖特定请求的默认温度
ChatResponse response = chatModel.call(
new Prompt(
"Generate the names of 5 famous pirates.",
GoogleGenAiChatOptions.builder()
.temperature(0.4)
.build()
));
| 除了模型特定的 `GoogleGenAiChatOptions`,您还可以使用可移植的 ChatOptions 实例,使用 ChatOptions#builder() 创建。 |
工具调用
Google GenAI 模型支持工具调用(函数调用)功能,允许模型在对话期间使用工具。以下是定义和使用基于 `@Tool` 的工具的示例
public class WeatherService {
@Tool(description = "Get the weather in location")
public String weatherByLocation(@ToolParam(description= "City or state name") String location) {
...
}
}
String response = ChatClient.create(this.chatModel)
.prompt("What's the weather like in Boston?")
.tools(new WeatherService())
.call()
.content();
您也可以将 java.util.function bean 用作工具
@Bean
@Description("Get the weather in location. Return temperature in 36°F or 36°C format.")
public Function<Request, Response> weatherFunction() {
return new MockWeatherService();
}
String response = ChatClient.create(this.chatModel)
.prompt("What's the weather like in Boston?")
.toolNames("weatherFunction")
.inputType(Request.class)
.call()
.content();
在 工具 文档中查找更多信息。
多模态
多模态是指模型能够同时理解和处理来自各种(输入)源的信息的能力,包括 `text`、`pdf`、`images`、`audio` 和其他数据格式。
图像、音频、视频
Google 的 Gemini AI 模型通过理解和集成文本、代码、音频、图像和视频来支持此功能。有关更多详细信息,请参阅博客文章 Introducing Gemini。
Spring AI 的 Message 接口通过引入媒体类型来支持多模态 AI 模型。此类型包含消息中媒体附件的数据和信息,使用 Spring 的 org.springframework.util.MimeType 和 java.lang.Object 用于原始媒体数据。
下面是摘自 GoogleGenAiChatModelIT.java 的简单代码示例,演示了用户文本与图像的组合。
byte[] data = new ClassPathResource("/vertex-test.png").getContentAsByteArray();
var userMessage = UserMessage.builder()
.text("Explain what do you see o this picture?")
.media(List.of(new Media(MimeTypeUtils.IMAGE_PNG, data)))
.build();
ChatResponse response = chatModel.call(new Prompt(List.of(this.userMessage)));
Google GenAI 支持 PDF 输入类型。使用 `application/pdf` 媒体类型将 PDF 文件附加到消息
var pdfData = new ClassPathResource("/spring-ai-reference-overview.pdf");
var userMessage = UserMessage.builder()
.text("You are a very professional document summarization specialist. Please summarize the given document.")
.media(List.of(new Media(new MimeType("application", "pdf"), pdfData)))
.build();
var response = this.chatModel.call(new Prompt(List.of(userMessage)));
示例控制器
创建一个新的 Spring Boot 项目,并将 `spring-ai-starter-model-google-genai` 添加到您的 pom(或 gradle)依赖项中。
在 `src/main/resources` 目录下添加 `application.properties` 文件,以启用和配置 Google GenAI 聊天模型
使用 Gemini Developer API(API 密钥)
spring.ai.google.genai.api-key=YOUR_API_KEY
spring.ai.google.genai.chat.options.model=gemini-2.0-flash
spring.ai.google.genai.chat.options.temperature=0.5
使用 Vertex AI
spring.ai.google.genai.project-id=PROJECT_ID
spring.ai.google.genai.location=LOCATION
spring.ai.google.genai.chat.options.model=gemini-2.0-flash
spring.ai.google.genai.chat.options.temperature=0.5
| 将 `project-id` 替换为您的 Google Cloud 项目 ID,`location` 是 Google Cloud 区域,如 `us-central1`、`europe-west1` 等…… |
|
每个模型都有自己支持的区域集,您可以在模型页面中找到支持区域列表。 |
这将创建一个 `GoogleGenAiChatModel` 实现,您可以将其注入到您的类中。这是一个简单的 `@Controller` 类示例,它使用聊天模型进行文本生成。
@RestController
public class ChatController {
private final GoogleGenAiChatModel chatModel;
@Autowired
public ChatController(GoogleGenAiChatModel chatModel) {
this.chatModel = chatModel;
}
@GetMapping("/ai/generate")
public Map generate(@RequestParam(value = "message", defaultValue = "Tell me a joke") String message) {
return Map.of("generation", this.chatModel.call(message));
}
@GetMapping("/ai/generateStream")
public Flux<ChatResponse> generateStream(@RequestParam(value = "message", defaultValue = "Tell me a joke") String message) {
Prompt prompt = new Prompt(new UserMessage(message));
return this.chatModel.stream(prompt);
}
}
手动配置
GoogleGenAiChatModel 实现了 `ChatModel`,并使用 `com.google.genai.Client` 连接到 Google GenAI 服务。
将 `spring-ai-google-genai` 依赖项添加到您项目的 Maven `pom.xml` 文件中
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-google-genai</artifactId>
</dependency>
或添加到您的 Gradle build.gradle 构建文件中。
dependencies {
implementation 'org.springframework.ai:spring-ai-google-genai'
}
| 请参阅 依赖项管理 部分,将 Spring AI BOM 添加到您的构建文件中。 |
接下来,创建 `GoogleGenAiChatModel` 并将其用于文本生成
使用 API 密钥
Client genAiClient = Client.builder()
.apiKey(System.getenv("GOOGLE_API_KEY"))
.build();
var chatModel = new GoogleGenAiChatModel(genAiClient,
GoogleGenAiChatOptions.builder()
.model(ChatModel.GEMINI_2_0_FLASH)
.temperature(0.4)
.build());
ChatResponse response = this.chatModel.call(
new Prompt("Generate the names of 5 famous pirates."));
使用 Vertex AI
Client genAiClient = Client.builder()
.project(System.getenv("GOOGLE_CLOUD_PROJECT"))
.location(System.getenv("GOOGLE_CLOUD_LOCATION"))
.vertexAI(true)
.build();
var chatModel = new GoogleGenAiChatModel(genAiClient,
GoogleGenAiChatOptions.builder()
.model(ChatModel.GEMINI_2_0_FLASH)
.temperature(0.4)
.build());
ChatResponse response = this.chatModel.call(
new Prompt("Generate the names of 5 famous pirates."));
`GoogleGenAiChatOptions` 提供聊天请求的配置信息。`GoogleGenAiChatOptions.Builder` 是流畅的选项构建器。
从 Vertex AI Gemini 迁移
如果您目前正在使用 Vertex AI Gemini 实现(`spring-ai-vertex-ai-gemini`),您可以以最小的更改迁移到 Google GenAI