主题
Google GenAI 聊天
Google GenAI API 让开发者能通过 Gemini Developer API 或 Vertex AI,使用 Google 的 Gemini 模型来构建生成式 AI 应用。 Google GenAI API 支持多模态提示词作为输入,并输出文本或代码。 多模态模型能处理来自多种模态的信息,包括图像、视频和文本。例如,你可以发给模型一张一盘饼干的照片,并让它给你一份那些饼干的食谱。
Gemini 是由 Google DeepMind 开发、为多模态用例设计的一族生成式 AI 模型。Gemini API 让你访问多种模型,如 Gemini Flash-Lite、Gemini Flash 或 Gemini Pro。
此实现提供两种认证模式:
- Gemini Developer API:使用 API 密钥快速做原型与开发
- Vertex AI:使用 Google Cloud 凭据进行带企业特性的生产部署
前置条件
选择以下认证方式之一:
选项一:Gemini Developer API(API 密钥)
- 从 Google AI Studio 获取一个 API 密钥
- 把 API 密钥设为环境变量或写在你的应用属性里
选项二: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>自动配置
NOTE
Spring AI 的自动配置、starter 模块的制品名称发生了重大变更。 更多信息请参阅 升级说明。
Spring AI 为 Google GenAI 聊天客户端提供 Spring Boot 自动配置。 要启用它,请将以下依赖添加到你的项目的 Maven pom.xml 或 Gradle build.gradle 构建文件:
xml
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-google-genai</artifactId>
</dependency>TIP
参见 依赖管理 一节,把 Spring AI BOM 添加到你的构建文件。
聊天属性
NOTE
聊天自动配置的启用与禁用,现通过以 spring.ai.model.chat 为前缀的顶层属性来配置。
要启用,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 聊天配置聊天模型实现的属性前缀。
| 属性 | 描述 | 默认值 |
|---|---|---|
| spring.ai.google.genai.chat.model | 要使用的受支持 Google GenAI 聊天模型,包括 gemini-2.5-flash、gemini-2.5-flash-lite、gemini-2.5-pro、gemini-3.1-pro-preview、gemini-3.1-flash-lite 和 gemini-3.5-flash。 | gemini-2.5-flash |
| spring.ai.google.genai.chat.response-mime-type | 所生成候选文本的输出响应 mimetype。 | text/plain:(默认)文本输出,或 application/json:JSON 响应。 |
| spring.ai.google.genai.chat.google-search-retrieval | 使用 Google 搜索 Grounding 特性 | true 或 false,默认 false。 |
| spring.ai.google.genai.chat.include-server-side-tool-invocations | 为 true 时,API 响应会在响应元数据中包含服务端工具调用与响应(例如 Google 搜索调用),让你得以观察服务端的工具使用。仅在 Gemini Developer API(MLDev)上支持,Vertex AI 不支持。参见 server-side-tool-invocations。 | false |
| spring.ai.google.genai.chat.temperature | 控制输出的随机性。取值范围 [0.0,1.0],含端点。接近 1.0 的值会产生更多样的响应,而接近 0.0 的值通常会带来不太出人意料的生成。 | - |
| spring.ai.google.genai.chat.top-k | 采样时要考虑令牌的最大数。生成器结合使用 Top-k 与核采样。Top-k 采样考虑最可能的 topK 个令牌的集合。 | - |
| spring.ai.google.genai.chat.top-p | 采样时要考虑令牌的累计概率最大值。生成器结合使用 Top-k 与核采样。核采样考虑概率之和至少为 topP 的最小令牌集合。 | - |
| spring.ai.google.genai.chat.candidate-count | 要返回的生成响应消息数。该值必须在 [1, 8] 之间,含端点。默认为 1。 | 1 |
| spring.ai.google.genai.chat.max-output-tokens | 要生成的最大令牌数。 | - |
| spring.ai.google.genai.chat.frequency-penalty | 用于减少重复的频率惩罚。 | - |
| spring.ai.google.genai.chat.presence-penalty | 用于减少重复的存在惩罚。 | - |
| spring.ai.google.genai.chat.thinking-budget | 思考过程的思考预算。参见 thinking-config。 | - |
| spring.ai.google.genai.chat.thinking-level | 模型应生成的思考令牌级别。有效值:LOW、HIGH、THINKING_LEVEL_UNSPECIFIED。参见 thinking-config。 | - |
| spring.ai.google.genai.chat.include-thoughts | 为函数调用启用思考签名。对 Gemini 3 Pro 是必需的,以避免工具调用循环期间的校验错误。参见 thought-signatures。 | false |
| spring.ai.google.genai.chat.tool-callbacks | 注册到 ChatModel 的工具回调。 | - |
| spring.ai.google.genai.chat.safety-settings | 用于控制安全过滤器的安全设置列表,其定义见 Google GenAI 安全设置。每个安全设置可有方法、阈值和类别。 | - |
| spring.ai.google.genai.chat.cached-content-name | 此请求要使用的缓存内容名。与 use-cached-content=true 一并设置时,缓存内容将用作上下文。参见 cached-content。 | - |
| spring.ai.google.genai.chat.use-cached-content | 是否在可用时使用缓存内容。为 true 且设置了 cached-content-name 时,系统会使用缓存内容。 | false |
| spring.ai.google.genai.chat.auto-cache-threshold | 自动缓存超过此令牌阈值的提示词。设置后,大于此值的提示词会被自动缓存以供复用。设为 null 禁用自动缓存。 | - |
| spring.ai.google.genai.chat.auto-cache-ttl | 自动缓存内容的存活时长(Duration),采用 ISO-8601 格式(例如 PT1H 表示 1 小时)。在启用自动缓存时使用。 | PT1H |
| spring.ai.google.genai.chat.enable-cached-content | 启用用于管理缓存内容的 GoogleGenAiCachedContentService bean。 | true |
| spring.ai.google.genai.chat.service-tier | 请求要使用的服务层。有效值:STANDARD、PRIORITY、FLEX。 | - |
| spring.ai.google.genai.chat.tool-choice.mode | 控制提供工具时模型如何选择函数。有效值:AUTO(模型决定)、ANY(总是调用函数)、VALIDATED(函数调用或自然语言)、NONE(不调用函数)。参见 tool-choice。 | - |
| spring.ai.google.genai.chat.tool-choice.allowed-function-names | 以逗号分隔的、模型可调用的函数名列表。仅在 tool-choice.mode 为 ANY 或 VALIDATED 时应用;其他模式忽略。 | - |
TIP
所有以 spring.ai.google.genai.chat 为前缀的属性,都可通过在 Prompt 调用中添加请求专用的 chat-options 在运行时被覆盖。
运行时选项
GoogleGenAiChatOptions.java 提供模型配置,例如温度、topK 等。
在启动时,可通过 GoogleGenAiChatModel(client, options) 构造器或 spring.ai.google.genai.chat.* 属性配置默认选项。
在运行时,你可以通过向 Prompt 调用添加新的、请求特定的选项来覆盖默认选项。 例如,要为某个特定请求覆盖默认温度:
java
ChatResponse response = chatModel.call(
new Prompt(
"Generate the names of 5 famous pirates.",
GoogleGenAiChatOptions.builder()
.temperature(0.4)
.build()
));TIP
除模型特定的 GoogleGenAiChatOptions 外,你还可以使用一个可移植的 ChatOptions 实例,通过 ChatOptions#builder() 创建。
工具调用
GoogleGenAiChatModel 支持工具调用。模型可以请求执行工具,但它自己并不运行工具——由 Spring AI 处理执行。
对于大多数应用,请搭配自动注册的 ToolCallingAdvisor 使用 ChatClient —— 参见工具调用。若需要由你自己驱动该循环的底层控制,参见 ChatModel 工具调用。
关于 Google 的内建工具(Search、Maps、URL Context)以及如何与客户端函数调用结合,见下方的服务端工具调用。
工具选择
GoogleGenAiChatOptions.ToolChoice 配置提供工具时模型如何选择函数。 它映射到 Google GenAI 的 FunctionCallingConfig。
| 模式 | 行为 |
|---|---|
AUTO | 模型自行决定是调用函数还是返回自然语言响应(默认行为)。 |
ANY | 模型总是预测一个函数调用。当设置了 allowedFunctionNames 时,调用被限定于那些函数。 |
VALIDATED | 模型可调用函数或返回自然语言响应。当设置了 allowedFunctionNames 时,调用被限定于那些函数。 |
NONE | 模型不调用任何函数,返回自然语言响应。 |
NOTE
allowedFunctionNames 仅在模式为 ANY 或 VALIDATED 时应用,对 AUTO 和 NONE 会被静默忽略。
编程式配置
java
ChatResponse response = chatModel.call(
new Prompt(
"What is the weather in Paris?",
GoogleGenAiChatOptions.builder()
.toolChoice(new GoogleGenAiChatOptions.ToolChoice(
GoogleGenAiChatOptions.ToolChoice.Mode.ANY,
List.of("get_weather")))
.build()
));要施加某个模式而不限制到特定函数:
java
GoogleGenAiChatOptions.builder()
.toolChoice(new GoogleGenAiChatOptions.ToolChoice(
GoogleGenAiChatOptions.ToolChoice.Mode.NONE, null))
.build();基于属性的配置
application.properties
# Force the model to always call a function
spring.ai.google.genai.chat.tool-choice.mode=ANY
# Optionally restrict to specific functions (only applies when mode is ANY or VALIDATED)
spring.ai.google.genai.chat.tool-choice.allowed-function-names=get_weather,get_forecast或在 YAML 中:
yaml
spring:
ai:
google:
genai:
chat:
tool-choice:
mode: ANY
allowed-function-names:
- get_weather
- get_forecast服务端工具调用
当通过 googleSearchRetrieval(true) 启用 Google 搜索或其他服务端工具时,模型在服务端执行这些工具。默认情况下这些调用对客户端是不可见的——你只能看到最终的文本响应。设置 includeServerSideToolInvocations(true) 会让 API 把服务端的工具调用与响应包含进响应内容,从而让你能观察模型搜了什么、收到了什么结果。
WARNING
此特性仅在 Gemini Developer API(MLDev / API 密钥认证)上支持。它在 Vertex AI 上不受支持。
配置
通过应用属性启用:
application.properties
spring.ai.google.genai.chat.google-search-retrieval=true
spring.ai.google.genai.chat.include-server-side-tool-invocations=true或在运行时以编程方式:
java
ChatResponse response = chatModel.call(
new Prompt(
"What are the latest developments in quantum computing?",
GoogleGenAiChatOptions.builder()
.model("gemini-2.0-flash")
.googleSearchRetrieval(true)
.includeServerSideToolInvocations(true)
.build()
));访问服务端工具调用元数据
启用后,服务端工具调用可在响应消息元数据的 serverSideToolInvocations 键下获得:
java
ChatResponse response = chatModel.call(prompt);
Map<String, Object> metadata = response.getResult().getOutput().getMetadata();
@SuppressWarnings("unchecked")
List<Map<String, Object>> invocations =
(List<Map<String, Object>>) metadata.get("serverSideToolInvocations");
if (invocations != null) {
for (Map<String, Object> invocation : invocations) {
String type = (String) invocation.get("type"); // "toolCall" or "toolResponse"
String id = (String) invocation.get("id"); // Unique invocation ID
String toolType = (String) invocation.get("toolType"); // e.g., "GOOGLE_SEARCH_WEB"
if ("toolCall".equals(type)) {
Map<String, Object> args = (Map<String, Object>) invocation.get("args");
// Inspect what the model searched for
} else if ("toolResponse".equals(type)) {
Map<String, Object> responseData = (Map<String, Object>) invocation.get("response");
// Inspect what search results the model received
}
}
}列表中的每一项包含:
| 字段 | 描述 |
|---|---|
type | 为 "toolCall"(模型的调用请求)或 "toolResponse"(服务端的结果)之一 |
id | 把一个 toolCall 与其对应 toolResponse 关联起来的唯一标识符 |
toolType | 服务端工具的类型(例如 GOOGLE_SEARCH_WEB、GOOGLE_SEARCH_IMAGE、URL_CONTEXT、GOOGLE_MAPS) |
args | (仅 toolCall)传给工具的参数 |
response | (仅 toolResponse)工具返回的结果 |
与客户端工具调用结合
服务端工具调用与客户端工具调用协同工作。你可以在同一请求中同时启用 Google 搜索(服务端)与自定义工具(客户端):
java
ChatResponse response = chatModel.call(
new Prompt(
"What's the weather in San Francisco? Also search for the latest news about the city.",
GoogleGenAiChatOptions.builder()
.model("gemini-2.0-flash")
.googleSearchRetrieval(true)
.includeServerSideToolInvocations(true)
.toolCallbacks(List.of(
FunctionToolCallback.builder("get_current_weather", new WeatherService())
.description("Get the current weather in a given location")
.inputType(WeatherRequest.class)
.build()))
.build()
));
// The response contains:
// - Weather data from the client-side function call (executed locally)
// - Google Search invocations visible in metadata (executed server-side)NOTE
服务端工具调用仅作观察用——客户端不执行它们。它们在元数据中独立于客户端函数调用被呈现,以免干扰工具执行循环。
思考配置
Gemini 模型支持一种“思考”能力,让模型能在生成响应前做更深入的推理。它通过 ThinkingConfig 控制,其中包含三个相关选项:thinkingBudget、thinkingLevel 和 includeThoughts。
思考级别
thinkingLevel 选项控制模型生成的推理令牌深度。这对支持思考的模型可用(例如 Gemini 3 Pro Preview)。
| 值 | 描述 |
|---|---|
THINKING_LEVEL_UNSPECIFIED | 模型使用其默认行为。 |
MINIMAL | 对多数查询匹配“无思考”设置。把延迟降到最低。 |
LOW | 低思考。最少的推理令牌。 |
MEDIUM | 对多数任务平衡的思考。 |
HIGH | 广泛思考。用于需要深入分析和分步推理的复杂问题。 |
通过属性配置
application.properties
spring.ai.google.genai.chat.model=gemini-3.1-pro-preview
spring.ai.google.genai.chat.thinking-level=HIGH编程式配置
java
import org.springframework.ai.google.genai.common.GoogleGenAiThinkingLevel;
ChatResponse response = chatModel.call(
new Prompt(
"Explain the theory of relativity in simple terms.",
GoogleGenAiChatOptions.builder()
.model("gemini-3.1-pro-preview")
.thinkingLevel(GoogleGenAiThinkingLevel.HIGH)
.build()
));思考预算
thinkingBudget 选项为思考过程设置一个令牌预算:
- 正值:思考的最大令牌数(例如
8192) - 零(
0):完全禁用思考 - 未设置:模型依据查询复杂度自动决定
java
ChatResponse response = chatModel.call(
new Prompt(
"Solve this complex math problem step by step.",
GoogleGenAiChatOptions.builder()
.model("gemini-2.5-pro")
.thinkingBudget(8192)
.build()
));选项兼容性
WARNING
thinkingLevel 与 thinkingBudget 互斥。 你不能在同一请求中同时使用两者——那样会导致 API 错误。
- 对 Gemini 3.x 模型使用
thinkingLevel。Gemini 3 Pro 只支持LOW和HIGH;Gemini 3 Flash 模型支持所有级别(MINIMAL、LOW、MEDIUM、HIGH)。 - 对 Gemini 2.5 系列模型使用
thinkingBudget(令牌数)。
你可以把 includeThoughts 与 thinkingLevel 或 thinkingBudget 之一(而非两者)相结合:
java
// For Gemini 3.x (e.g. Pro): use thinkingLevel + includeThoughts
ChatResponse response = chatModel.call(
new Prompt(
"Analyze this complex scenario.",
GoogleGenAiChatOptions.builder()
.model("gemini-3.1-pro-preview")
.thinkingLevel(GoogleGenAiThinkingLevel.HIGH)
.includeThoughts(true)
.build()
));
// For Gemini 2.5: use thinkingBudget + includeThoughts
ChatResponse response = chatModel.call(
new Prompt(
"Analyze this complex scenario.",
GoogleGenAiChatOptions.builder()
.model("gemini-2.5-pro")
.thinkingBudget(8192)
.includeThoughts(true)
.build()
));模型支持
思考配置选项是模型特定的:
| 模型 | 模型 ID | thinkingLevel | thinkingBudget | 备注 |
|---|---|---|---|---|
| Gemini 3 Pro Preview | gemini-3.1-pro-preview | ✅ 仅 LOW 和 HIGH | ⚠️ 仅向后兼容 | 使用 thinkingLevel。无法禁用思考。需要全球端点。 |
| Gemini 3.5 Flash | gemini-3.5-flash | ✅ 所有级别 | ❌ 不支持 | 使用 thinkingLevel,可含 MINIMAL 和 MEDIUM 的任意级别。 |
| Gemini 3.1 Flash-Lite | gemini-3.1-flash-lite | ✅ 所有级别 | ❌ 不支持 | 使用 thinkingLevel,可含 MINIMAL 和 MEDIUM 的任意级别。 |
| Gemini 2.5 Pro | gemini-2.5-pro | ❌ 不支持 | ✅ 支持 | 使用 thinkingBudget。设为 0 禁用,-1 动态。 |
| Gemini 2.5 Flash | gemini-2.5-flash | ❌ 不支持 | ✅ 支持 | 使用 thinkingBudget。设为 0 禁用,-1 动态。 |
| Gemini 2.5 Flash-Lite | gemini-2.5-flash-lite | ❌ 不支持 | ✅ 支持 | 思考默认禁用。设置 thinkingBudget 以启用。 |
| Gemini 2.0 Flash | gemini-2.0-flash-001 | ❌ 不支持 | ❌ 不支持 | 思考不可用。 |
WARNING
- 对不支持的模型使用
thinkingLevel(例如 Gemini 2.5 或更早)会导致 API 错误。 - 对 Gemini 3 Pro 模型使用
MINIMAL或MEDIUM会导致IllegalArgumentException。 - Gemini 3 Pro Preview 只在全球端点可用。设置
spring.ai.google.genai.location=global或GOOGLE_CLOUD_LOCATION=global。 - 关于最新的模型能力,查阅 Google GenAI 思考文档。
NOTE
启用思考特性会增加令牌用量和 API 成本。请依据查询的复杂度恰当使用。
思考签名
Gemini 3 Pro 引入了思考签名,它是不透明的字节数组,在函数调用期间保留模型的推理上下文。当启用 includeThoughts 时,模型返回的思考签名必须在工具调用循环期间、于同一回合内被回传。
思考签名何时重要
重要:思考签名校验只适用于当前回合——具体是模型进行函数调用(并行与顺序皆有)时的工具调用循环。API 不会校验对话历史中先前回合的思考签名。
按 Google 的文档:
- 校验只对当前回合内的函数调用强制
- 先前回合的签名无需保留
- 当前回合函数调用中缺失签名,对 Gemini 3 Pro 会导致 HTTP 400 错误
- 对并行函数调用,只有第一个
functionCall部分携带签名
对 Gemini 2.5 Pro 及更早模型,思考签名是可选的,API 较为宽松。
配置
使用配置属性启用思考签名:
application.properties
spring.ai.google.genai.chat.model=gemini-3.1-pro-preview
spring.ai.google.genai.chat.include-thoughts=true或在运行时以编程方式:
java
ChatResponse response = chatModel.call(
new Prompt(
"Your question here",
GoogleGenAiChatOptions.builder()
.model("gemini-3.1-pro-preview")
.includeThoughts(true)
.toolCallbacks(callbacks)
.build()
));经由 ChatClient 自动处理(推荐)
当使用带 ToolCallingAdvisor 的 ChatClient(推荐方式)时,Spring AI 会自动处理思考签名:
- 从模型响应中提取思考签名
- 在回传函数响应时把它们附加到正确的
functionCall部分 - 在单回合内的函数调用期间正确地传播它们(并行与顺序皆然)
java
@Bean
ToolCallback weatherFunction() {
return FunctionToolCallback.builder("weatherFunction", new WeatherService())
.description("Get the weather in a location")
.inputType(WeatherRequest.class)
.build();
}
// Enable includeThoughts for Gemini 3 Pro with function calling
String response = ChatClient.create(this.chatModel)
.prompt("What's the weather like in Boston?")
.options(GoogleGenAiChatOptions.builder()
.model("gemini-3.1-pro-preview")
.includeThoughts(true)
.build())
.tools(weatherFunction)
.call()
.content();带思考签名的用户控制工具执行
当使用手动工具执行循环时,你必须通过在对话历史中保留原始 AssistantMessage(连同其元数据)来保存思考签名。Spring AI 在转换消息时会自动把签名附加到正确的 functionCall 部分。
带思考签名的手动工具执行的要求:
- 从响应元数据中提取思考签名:
java
AssistantMessage assistantMessage = response.getResult().getOutput();
Map<String, Object> metadata = assistantMessage.getMetadata();
List<byte[]> thoughtSignatures = (List<byte[]>) metadata.get("thoughtSignatures");在回传函数响应时,把原始的
AssistantMessage(元数据完好)包含进你的消息历史。Spring AI 会自动把思考签名附加到正确的functionCall部分。对 Gemini 3 Pro,在当前回合未能保留思考签名会导致来自 API 的 HTTP 400 错误。
WARNING
只有当前回合的函数调用需要思考签名。当开始一个新的对话回合(完成一轮函数调用之后)时,你无需保留先前回合的签名。
NOTE
启用 includeThoughts 会增加令牌用量,因为思考过程被包含进响应。这影响 API 成本,但提供更好的推理透明度。
多模态
多模态指的是模型同时理解和处理来自各种(输入)来源信息的能力,包括 text、pdf、images、audio 及其他数据格式。
图像、音频、视频
Google 的 Gemini AI 模型通过理解和整合文本、代码、音频、图像与视频来支持这一能力。 更多细节参阅博客文章 Introducing Gemini。
Spring AI 的 Message 接口通过引入 Media 类型支持多模态 AI 模型。 该类型包含消息中媒体附件的数据与信息,使用 Spring 的 org.springframework.util.MimeType 和一个 java.lang.Object 表示原始媒体数据。
下面是一个简单代码示例,摘自 GoogleGenAiChatModelIT.java,演示把用户文本与一张图像结合。
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 文件附加到消息:
java
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)));缓存内容
Google GenAI 的上下文缓存 让你能缓存大量内容(如长文档、代码仓库或媒体)并在多个请求间复用它。这能显著降低 API 成本,并改善对相同内容重复查询的响应延迟。
好处
- 成本降低:被缓存的令牌计费远低于常规输入令牌(通常便宜 75-90%)
- 性能提升:复用缓存内容减少了大上下文的处理时间
- 一致性:相同的缓存上下文确保多个请求间响应一致
缓存要求
- 最小缓存大小:32,768 令牌(约 25,000 词)
- 最大缓存时长:默认 1 小时(可通过 TTL 配置)
- 缓存内容必须包含系统指令或对话历史之一
使用缓存内容服务
Spring AI 提供 GoogleGenAiCachedContentService 用于以编程方式管理缓存。使用 Spring Boot 自动配置时该服务会被自动配置。
创建缓存内容
java
@Autowired
private GoogleGenAiCachedContentService cachedContentService;
// Create cached content with a large document
String largeDocument = "... your large context here (>32k tokens) ...";
CachedContentRequest request = CachedContentRequest.builder()
.model("gemini-2.5-flash")
.contents(List.of(
Content.builder()
.role("user")
.parts(List.of(Part.fromText(largeDocument)))
.build()
))
.displayName("My Large Document Cache")
.ttl(Duration.ofHours(1))
.build();
GoogleGenAiCachedContent cachedContent = cachedContentService.create(request);
String cacheName = cachedContent.getName(); // Save this for reuse在聊天请求中使用缓存内容
一旦你创建了缓存内容,就在聊天请求中引用它:
java
ChatResponse response = chatModel.call(
new Prompt(
"Summarize the key points from the document",
GoogleGenAiChatOptions.builder()
.useCachedContent(true)
.cachedContentName(cacheName) // Use the cached content name
.build()
));或通过配置属性:
application.properties
spring.ai.google.genai.chat.use-cached-content=true
spring.ai.google.genai.chat.cached-content-name=cachedContent/your-cache-name管理缓存内容
GoogleGenAiCachedContentService 提供全面的缓存管理:
java
// Retrieve cached content
GoogleGenAiCachedContent content = cachedContentService.get(cacheName);
// Update cache TTL
CachedContentUpdateRequest updateRequest = CachedContentUpdateRequest.builder()
.ttl(Duration.ofHours(2))
.build();
GoogleGenAiCachedContent updated = cachedContentService.update(cacheName, updateRequest);
// List all cached content
List<GoogleGenAiCachedContent> allCaches = cachedContentService.listAll();
// Delete cached content
boolean deleted = cachedContentService.delete(cacheName);
// Extend cache TTL
GoogleGenAiCachedContent extended = cachedContentService.extendTtl(cacheName, Duration.ofMinutes(30));
// Cleanup expired caches
int removedCount = cachedContentService.cleanupExpired();异步操作
所有操作都有异步变体:
java
CompletableFuture<GoogleGenAiCachedContent> futureCache =
cachedContentService.createAsync(request);
CompletableFuture<GoogleGenAiCachedContent> futureGet =
cachedContentService.getAsync(cacheName);
CompletableFuture<Boolean> futureDelete =
cachedContentService.deleteAsync(cacheName);自动缓存
当大型提示词超过指定的令牌阈值时,Spring AI 能自动缓存它们:
application.properties
# Automatically cache prompts larger than 100,000 tokens
spring.ai.google.genai.chat.auto-cache-threshold=100000
# Set auto-cache TTL to 1 hour
spring.ai.google.genai.chat.auto-cache-ttl=PT1H或以编程方式:
java
ChatResponse response = chatModel.call(
new Prompt(
largePrompt,
GoogleGenAiChatOptions.builder()
.autoCacheThreshold(100000)
.autoCacheTtl(Duration.ofHours(1))
.build()
));NOTE
自动缓存对一次性的大型上下文很有用。对于同一上下文的重复使用,手动创建并引用缓存内容更高效。
监控缓存用量
缓存内容包含可通过该服务访问的用量元数据:
java
GoogleGenAiCachedContent content = cachedContentService.get(cacheName);
// Check if cache is expired
boolean expired = content.isExpired();
// Get remaining TTL
Duration remaining = content.getRemainingTtl();
// Get usage metadata
CachedContentUsageMetadata metadata = content.getUsageMetadata();
if (metadata != null) {
System.out.println("Total tokens: " + metadata.totalTokenCount().orElse(0));
}最佳实践
- 缓存寿命:依据你的用例设置合适的 TTL。频繁变化的内容用较短 TTL,静态内容用较长 TTL。
- 缓存命名:使用描述性的显示名以便轻松识别缓存内容。
- 清理:定期清理过期缓存以保持条理。
- 令牌阈值:只缓存超过最小阈值(32,768 令牌)的内容。
- 成本优化:在多个请求间复用缓存内容以最大化省钱。
配置示例
完整配置示例:
application.properties
# Enable cached content service (enabled by default)
spring.ai.google.genai.chat.enable-cached-content=true
# Use a specific cached content
spring.ai.google.genai.chat.use-cached-content=true
spring.ai.google.genai.chat.cached-content-name=cachedContent/my-cache-123
# Auto-caching configuration
spring.ai.google.genai.chat.auto-cache-threshold=50000
spring.ai.google.genai.chat.auto-cache-ttl=PT30M示例控制器
创建 一个新的 Spring Boot 项目,并把 spring-ai-starter-model-google-genai 添加到你的 pom(或 gradle)依赖。
在 src/main/resources 目录下添加一个 application.properties 文件,以启用并配置 Google GenAI 聊天模型:
使用 Gemini Developer API(API 密钥)
application.properties
spring.ai.google.genai.api-key=YOUR_API_KEY
spring.ai.google.genai.chat.model=gemini-2.5-flash
spring.ai.google.genai.chat.temperature=0.5使用 Vertex AI
application.properties
spring.ai.google.genai.project-id=PROJECT_ID
spring.ai.google.genai.location=LOCATION
spring.ai.google.genai.chat.model=gemini-2.5-flash
spring.ai.google.genai.chat.temperature=0.5TIP
用你的 Google Cloud 项目 ID 替换 project-id,location 是 Google Cloud 区域
如 us-central1、europe-west1 等……
NOTE
每个模型都有各自支持的区域集合,你可以在模型页找到受支持区域的列表。
这会创建一个可注入到你类中的 GoogleGenAiChatModel 实现。 下面是一个简单 @Controller 类的示例,它使用聊天模型进行文本生成。
java
@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 文件:
xml
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-google-genai</artifactId>
</dependency>或添加到你的 Gradle build.gradle 构建文件。
groovy
dependencies {
implementation 'org.springframework.ai:spring-ai-google-genai'
}TIP
参见 依赖管理 一节,把 Spring AI BOM 添加到你的构建文件。
接下来,创建一个 GoogleGenAiChatModel 并将其用于文本生成:
使用 API 密钥
java
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
java
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:
主要差异:
- SDK:Google GenAI 使用新的
com.google.genai.Client而非com.google.cloud.vertexai.VertexAI - 认证:同时支持 API 密钥和 Google Cloud 凭据(Vertex AI 模式)
- 包名:类位于
org.springframework.ai.google.genai而非org.springframework.ai.vertexai.gemini - 属性前缀:使用
spring.ai.google.genai而非spring.ai.vertex.ai.gemini
Google GenAI 既支持用 API 密钥快速做原型,也支持通过 Google Cloud 凭据使用 Vertex AI 进行生产部署。
底层 Java 客户端
Google GenAI 实现构建在新的 Google GenAI Java SDK 之上,它提供一个现代的、精简的 API 来访问 Gemini 模型。