Google GenAI Chat

The Google GenAI API 允许开发者使用 Google 的 Gemini 模型通过 Gemini 开发者 API 或 Vertex AI 构建生成式人工智能应用。 Google GenAI API 支持多模态提示作为输入,并输出文本或代码。 一个多模态模型能够处理来自多种模态的信息,包括图像、视频和文本。例如,您可以向模型发送一张饼干盘的照片,并请它给出这些饼干的Recipes。spring-doc.cadn.net.cn

Gemini 是由 Google DeepMind 开发的一系列生成式 AI 模型,旨在用于多模态应用场景。Gemini API 给您访问 Gemini 2.0 FlashGemini 2.0 Flash-Lite、所有 Gemini Pro 模型,直至最新的 Gemini 3 Prospring-doc.cadn.net.cn

此实现提供了两种认证模式:spring-doc.cadn.net.cn

前置条件

请选择以下之一的身份验证方法:spring-doc.cadn.net.cn

选项 1: 吉明尼开发人员 API(API 密钥)

选项 2: Vertex AI(Google Cloud)

gcloud config set project <PROJECT_ID> &&
gcloud auth application-default login <ACCOUNT>

Auto-configuration

Spring AI自动配置和starter模块的artifact名称有了重大变化。 请参阅升级说明获取更多信息。spring-doc.cadn.net.cn

Spring AI 为 Google GenAI 聊天客户端提供了 Spring Boot 自动配置。 要启用它,请将以下依赖项添加到您的项目 Maven pom.xml 或 Gradle build.gradle 构建文件中:spring-doc.cadn.net.cn

<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的顶级属性来配置聊天自动配置的启用和禁用。spring-doc.cadn.net.cn

要启用,请设置:spring.ai.model.chat=google-genai(默认已启用)spring-doc.cadn.net.cn

要禁用,请设置spring.ai.model.chat=none(或任何不匹配google-genai的值)spring-doc.cadn.net.cn

此更改是为了允许配置多个模型。spring-doc.cadn.net.cn

连接属性

spring-doc.cadn.net.cn

前缀spring.ai.google.genai用作属性前缀,让您能够连接到Google GenAI。spring-doc.cadn.net.cn

spring-doc.cadn.net.cn

<property> </property> <description> </description> 默认

spring.ai.model.chatspring-doc.cadn.net.cn

启用聊天模型客户端spring-doc.cadn.net.cn

google-genaispring-doc.cadn.net.cn

spring.ai.google.genai.api-keyspring-doc.cadn.net.cn

Gemini开发者API的API密钥。当提供时,客户端将使用Gemini开发者API而不是Vertex AI。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.google.genai.project-idspring-doc.cadn.net.cn

Google Cloud Platform 项目ID(在 Vertex AI 模式下必填)spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.google.genai.locationspring-doc.cadn.net.cn

Google Cloud 区域(对于 Vertex AI 模式是必需的)spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.google.genai.credentials-urispring-doc.cadn.net.cn

使用指向Google Cloud凭证的URI。当提供时,将用于创建一个GoogleCredentials实例进行身份验证。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

聊天模型属性

spring.ai.google.genai.chat 前缀是属性前缀,用于配置与 Google GenAI Chat 的聊天模型实现相关的设置。spring-doc.cadn.net.cn

<property> </property> <description> </description> 默认

spring.ai.google.genai.chat.options.modelspring-doc.cadn.net.cn

支持使用的Google GenAI Chat 模型包括gemini-2.0-flashgemini-2.0-flash-litegemini-progemini-1.5-flashspring-doc.cadn.net.cn

gemini-2.0-flashspring-doc.cadn.net.cn

spring.ai.google.genai.chat.options.response-mime-typespring-doc.cadn.net.cn

输出生成的候选文本的响应MIME类型。spring-doc.cadn.net.cn

text/plain: (默认) 文本输出或 application/json: JSON 响应。spring-doc.cadn.net.cn

spring.ai.google.genai.chat.options.google-search-retrievalspring-doc.cadn.net.cn

使用Google搜索功能spring-doc.cadn.net.cn

truefalse,默认为 falsespring-doc.cadn.net.cn

spring.ai.google.genai.chat.options.temperaturespring-doc.cadn.net.cn

控制输出的随机性。值可以在 [0.0,1.0] 的范围内,包括边界值。接近 1.0 的值将产生更加多变的回答,而接近 0.0 的值通常会导致生成的回答不那么令人惊讶。spring-doc.cadn.net.cn

0.7spring-doc.cadn.net.cn

spring.ai.google.genai.chat.options.top-kspring-doc.cadn.net.cn

考虑在采样时使用的最大token数量。生成模型使用结合了Top-k和核截断(nucleus)的采样方法。Top-k采样会考虑最有可能的前K个token集合。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.google.genai.chat.options.top-pspring-doc.cadn.net.cn

考虑采样时要考虑的Tokens的最大累积概率。生成模型使用结合了Top-k和核取样方法。核取样会考虑那些概率总和至少为topP的最小Tokens集合。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.google.genai.chat.options.candidate-countspring-doc.cadn.net.cn

返回的生成响应消息的数量。此值必须在 [1, 8] 范围内,包括边界值。默认值为 1。spring-doc.cadn.net.cn

1spring-doc.cadn.net.cn

spring.ai.google.genai.chat.options.max-output-tokensspring-doc.cadn.net.cn

生成的最大token数。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.google.genai.chat.options.frequency-penaltyspring-doc.cadn.net.cn

减少重复性的频率惩罚。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.google.genai.chat.options.presence-penaltyspring-doc.cadn.net.cn

减少重复的存现罚金。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.google.genai.chat.options.thinking-budgetspring-doc.cadn.net.cn

思考预算用于思考过程。请参见思考配置spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.google.genai.chat.options.thinking-levelspring-doc.cadn.net.cn

应由模型生成的思考Tokens水平。有效值:LOWHIGHTHINKING_LEVEL_UNSPECIFIED。参见 思考配置spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.google.genai.chat.options.include-thoughtsspring-doc.cadn.net.cn

启用函数调用的思想签名。在使用Gemini 3 Pro时必需,以避免内部工具执行循环中的验证错误。详见思想签名spring-doc.cadn.net.cn

falsespring-doc.cadn.net.cn

spring.ai.google.genai.chat.options.tool-namesspring-doc.cadn.net.cn

使用名称标识的工具列表,以在单个提示请求中启用功能调用。具有这些名称的工具必须存在于ToolCallback注册表中。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.google.genai.chat.options.tool-callbacksspring-doc.cadn.net.cn

使用回调注册与ChatModel相关的工具。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.google.genai.chat.options.internal-tool-execution-enabledspring-doc.cadn.net.cn

如果为true,则应执行工具执行,否则将模型的响应返回给用户。默认值为null,但如果为null,则会考虑ToolCallingChatOptions.DEFAULT_TOOL_EXECUTION_ENABLED(即true)。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.google.genai.chat.options.safety-settingsspring-doc.cadn.net.cn

spring-doc.cadn.net.cn

列表用于控制安全过滤器的安全设置,由Google GenAI 安全设置定义。每个安全设置可以包含方法、阈值和类别。spring-doc.cadn.net.cn

spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.google.genai.chat.options.cached-content-namespring-doc.cadn.net.cn

此请求使用的缓存内容名称。当与use-cached-content=true一起设置时,将使用缓存内容作为上下文。参见缓存内容spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.google.genai.chat.options.use-cached-contentspring-doc.cadn.net.cn

是否使用可用的缓存内容。当设置为true且cached-content-name时,系统将使用缓存内容。spring-doc.cadn.net.cn

falsespring-doc.cadn.net.cn

spring.ai.google.genai.chat.options.auto-cache-thresholdspring-doc.cadn.net.cn

超过此token阈值的提示将自动缓存。启用时,超出该值的提示将被自动缓存以供重用。设置为null以禁用自动缓存。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.google.genai.chat.options.auto-cache-ttlspring-doc.cadn.net.cn

时间存活期(持续时间),以ISO-8601格式表示(例如,PT1H 表示1小时)。在启用自动缓存时使用。spring-doc.cadn.net.cn

PT1Hspring-doc.cadn.net.cn

spring.ai.google.genai.chat.enable-cached-contentspring-doc.cadn.net.cn

启用GoogleGenAiCachedContentService豆以管理缓存内容。spring-doc.cadn.net.cn

truespring-doc.cadn.net.cn

所有以spring.ai.google.genai.chat.options开头的属性可以在运行时通过向Prompt调用添加请求特定的运行时选项来覆盖。

运行时选项

The GoogleGenAiChatOptions.java 提供了模型配置,例如温度、topK等。spring-doc.cadn.net.cn

启动时,可以使用GoogleGenAiChatModel(client, options)构造函数或spring.ai.google.genai.chat.options.*属性来配置默认选项。spring-doc.cadn.net.cn

在运行时,您可以覆盖默认选项并通过向Prompt调用添加新的、请求特定的选项来实现。例如,要为特定请求覆盖默认温度设置:spring-doc.cadn.net.cn

ChatResponse response = chatModel.call(
    new Prompt(
        "Generate the names of 5 famous pirates.",
        GoogleGenAiChatOptions.builder()
            .temperature(0.4)
        .build()
    ));
除此之外,除了特定模型的GoogleGenAiChatOptions之外,您还可以使用一个通用的ChatOptions实例,该实例是通过调用ChatOptions#builder()创建的。

工具调用

The Google GenAI 模型支持工具调用(函数调用)能力,允许模型在对话中使用工具。 以下是定义和使用基于@Tool-索引的工具的一个示例:spring-doc.cadn.net.cn

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 工具作为 Beans 使用:spring-doc.cadn.net.cn

@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();

工具文档中查找更多内容。spring-doc.cadn.net.cn

思考配置

Gemini模型支持一种"思考"能力,允许模型在生成响应之前进行更深入的推理。这通过ThinkingConfig控制,包括三个相关选项:thinkingBudgetthinkingLevelincludeThoughtsspring-doc.cadn.net.cn

思考层级

thinkingLevel选项控制模型生成的推理Tokens深度。此功能适用于支持思考(例如,Gemini 3 Pro Preview)的模型。spring-doc.cadn.net.cn

<description> </description>

LOWspring-doc.cadn.net.cn

简单的思考方式。适用于简单查询,在速度优先于深入分析的情况下使用。spring-doc.cadn.net.cn

HIGHspring-doc.cadn.net.cn

广泛思考。适用于需要深入分析和逐步推理的复杂问题。spring-doc.cadn.net.cn

THINKING_LEVEL_UNSPECIFIEDspring-doc.cadn.net.cn

该模型使用其默认行为。spring-doc.cadn.net.cn

配置通过属性

spring.ai.google.genai.chat.options.model=gemini-3-pro-preview
spring.ai.google.genai.chat.options.thinking-level=HIGH

程序化配置

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-pro-preview")
            .thinkingLevel(GoogleGenAiThinkingLevel.HIGH)
            .build()
    ));

思考预算

The thinkingBudget 选项为思考过程设置一个Tokens预算:spring-doc.cadn.net.cn

ChatResponse response = chatModel.call(
    new Prompt(
        "Solve this complex math problem step by step.",
        GoogleGenAiChatOptions.builder()
            .model("gemini-2.5-pro")
            .thinkingBudget(8192)
            .build()
    ));

选项兼容性

thinkingLevelthinkingBudget 是互斥的。 您在同一请求中不能同时使用两者 - 如此操作将会导致 API 错误。spring-doc.cadn.net.cn

您可以将includeThoughtsthinkingLevelthinkingBudget结合使用(但不能同时使用两者):spring-doc.cadn.net.cn

// For Gemini 3 Pro: use thinkingLevel + includeThoughts
ChatResponse response = chatModel.call(
    new Prompt(
        "Analyze this complex scenario.",
        GoogleGenAiChatOptions.builder()
            .model("gemini-3-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()
    ));

模型支持

thinking 配置选项是模型特定的:spring-doc.cadn.net.cn

模型 思考层级 思考预算 注释

Gemini 3 Pro (预览版)spring-doc.cadn.net.cn

✅ 支持spring-doc.cadn.net.cn

⚠️ 只向后兼容spring-doc.cadn.net.cn

使用thinkingLevel。无法禁用思考。需要全局端点。spring-doc.cadn.net.cn

Gemini 2.5 Prospring-doc.cadn.net.cn

❌ 不支持spring-doc.cadn.net.cn

✅ 支持spring-doc.cadn.net.cn

使用thinkingBudget。设置为0以禁用,设置为-1以启用动态模式。spring-doc.cadn.net.cn

Gemini 2.5 Flashspring-doc.cadn.net.cn

❌ 不支持spring-doc.cadn.net.cn

✅ 支持spring-doc.cadn.net.cn

使用thinkingBudget。设置为0以禁用,设置为-1以启用动态模式。spring-doc.cadn.net.cn

Gemini 2.5 Flash-Litespring-doc.cadn.net.cn

❌ 不支持spring-doc.cadn.net.cn

✅ 支持spring-doc.cadn.net.cn

默认禁用思考。设为thinkingBudget启用。spring-doc.cadn.net.cn

Gemini 2.0 Flashspring-doc.cadn.net.cn

❌ 不支持spring-doc.cadn.net.cn

❌ 不支持spring-doc.cadn.net.cn

thinking 不可用。spring-doc.cadn.net.cn

启用思考功能会增加Tokens使用量和API成本。请根据您的查询复杂性适当使用。

思想特征

Gemini 3 Pro 引入了思维签名,这是一种不透明的字节数组,在函数调用过程中保留模型的推理上下文。当 includeThoughts 启用时,在内部工具执行循环中,模型返回的思维签名必须在同一次回合内传递回去。spring-doc.cadn.net.cn

当思维签名至关重要

重要:思维签名验证仅适用于当前回合-具体而言是在模型在内部工具执行循环中进行函数调用(包括并行和顺序)时。API 不会验证对话历史中的前几回合的思维签名。spring-doc.cadn.net.cn

对于Gemini 2.5 Pro及更早版本的模型,思维签名是可选的,并且API较为宽容。spring-doc.cadn.net.cn

配置

使用配置属性启用思维签名:spring-doc.cadn.net.cn

spring.ai.google.genai.chat.options.model=gemini-3-pro-preview
spring.ai.google.genai.chat.options.include-thoughts=true

在运行时编程设置:spring-doc.cadn.net.cn

ChatResponse response = chatModel.call(
    new Prompt(
        "Your question here",
        GoogleGenAiChatOptions.builder()
            .model("gemini-3-pro-preview")
            .includeThoughts(true)
            .toolCallbacks(callbacks)
            .build()
    ));

自动处理

Spring AI 在内部工具执行循环中自动处理思维签名。当internalToolExecutionEnabled为真(默认值)时,Spring AI:spring-doc.cadn.net.cn

  1. 从模型响应中提取思想特征spring-doc.cadn.net.cn

  2. 将其附到发送回函数响应的正确functionCall部分spring-doc.cadn.net.cn

  3. 在单个回合内的函数调用中,正确地传播它们(无论是并行还是顺序)spring-doc.cadn.net.cn

无需手动管理思维签名 - Spring AI 确保它们按照API规范正确地附加到functionCall部分。spring-doc.cadn.net.cn

示例与函数调用

@Bean
@Description("Get the weather in a location")
public Function<WeatherRequest, WeatherResponse> weatherFunction() {
    return new WeatherService();
}

// 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-pro-preview")
            .includeThoughts(true)
            .build())
        .toolNames("weatherFunction")
        .call()
        .content();

手动工具执行模式

如果将internalToolExecutionEnabled=false设置为手动控制工具执行循环,在使用Gemini 3 Pro与includeThoughts=true时,您必须自己处理思维签名。spring-doc.cadn.net.cn

使用思维签名手动工具执行的要求:spring-doc.cadn.net.cn

  1. 从响应元数据中提取思想签名:spring-doc.cadn.net.cn

    AssistantMessage assistantMessage = response.getResult().getOutput();
    Map<String, Object> metadata = assistantMessage.getMetadata();
    List<byte[]> thoughtSignatures = (List<byte[]>) metadata.get("thoughtSignatures");
  2. 在发送回函数响应时,请确保在消息历史中包含原始AssistantMessage及其元数据。Spring AI 将会自动将思维签名附加到正确的functionCall部分。spring-doc.cadn.net.cn

  3. Gemini 3 Pro 在当前回合未能保存思维签名将导致 API 返回 HTTP 400 错误。spring-doc.cadn.net.cn

仅当前轮次的函数调用需要思考签名。在完成一个函数调用回合后开始新的对话轮次时,不需要保留之前的轮次的签名。
启用includeThoughts会增加token使用量,因为响应中包含了思考过程。这会影响API成本,但能提供更好的推理透明度。

多模态

多模态指的是模型同时理解并处理来自各种(输入)来源的信息的能力,包括textpdfimagesaudio以及其他数据格式。spring-doc.cadn.net.cn

图像, 音频, 视频

Google的Gemini AI模型支持此功能,能够理解和整合文本、代码、音频、图像和视频。 如需了解详细信息,请参阅博客文章:介绍Geminispring-doc.cadn.net.cn

Spring AI的Message接口通过引入Media类型支持多模态AI模型。 这种类型包含消息中媒体附件的数据和信息,使用Spring的org.springframework.util.MimeType和一个java.lang.Object来承载原始媒体数据。spring-doc.cadn.net.cn

以下是一个从GoogleGenAiChatModelIT.java提取的简单代码示例,演示了用户文本与图片的结合。spring-doc.cadn.net.cn

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)));

PDF

Google GenAI 提供了对 PDF 输入类型的支持。 使用 application/pdf 媒体类型将 PDF 文件附加到消息中:spring-doc.cadn.net.cn

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成本,并提高了在相同内容上重复查询时的响应延迟。spring-doc.cadn.net.cn

好处

缓存要求

使用缓存内容服务

Spring AI 提供 GoogleGenAiCachedContentService 用于程序化缓存管理。当使用 Spring Boot 自动配置时,该服务会自动配置。spring-doc.cadn.net.cn

创建缓存内容

@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.0-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

使用缓存内容进行聊天请求

创建完缓存内容后,在您的聊天请求中引用它:spring-doc.cadn.net.cn

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()
    ));

通过配置属性:spring-doc.cadn.net.cn

spring.ai.google.genai.chat.options.use-cached-content=true
spring.ai.google.genai.chat.options.cached-content-name=cachedContent/your-cache-name

管理缓存内容

The GoogleGenAiCachedContentService 提供了全面的缓存管理:spring-doc.cadn.net.cn

// 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();

异步操作

所有操作都有异步版本:spring-doc.cadn.net.cn

CompletableFuture<GoogleGenAiCachedContent> futureCache =
    cachedContentService.createAsync(request);

CompletableFuture<GoogleGenAiCachedContent> futureGet =
    cachedContentService.getAsync(cacheName);

CompletableFuture<Boolean> futureDelete =
    cachedContentService.deleteAsync(cacheName);

Auto-Caching

Spring AI 可以自动缓存大型提示词,当它们超过指定的标记阈值时:spring-doc.cadn.net.cn

# Automatically cache prompts larger than 100,000 tokens
spring.ai.google.genai.chat.options.auto-cache-threshold=100000
# Set auto-cache TTL to 1 hour
spring.ai.google.genai.chat.options.auto-cache-ttl=PT1H

或编程方式:spring-doc.cadn.net.cn

ChatResponse response = chatModel.call(
    new Prompt(
        largePrompt,
        GoogleGenAiChatOptions.builder()
            .autoCacheThreshold(100000)
            .autoCacheTtl(Duration.ofHours(1))
            .build()
    ));
自动缓存适用于一次性处理大型上下文。对于相同上下文的重复使用,手动创建和引用缓存内容更高效。

监控缓存使用情况

缓存的内容包括可通过服务访问的使用元数据:spring-doc.cadn.net.cn

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));
}

最佳实践

  1. 缓存有效期: 根据您的使用场景设置适当的TTL。频繁变化的内容应设置较短的TTL,静态内容则可以设置较长的TTL。spring-doc.cadn.net.cn

  2. 强缓存命名:使用描述性的显示名称来轻松识别缓存的内容。spring-doc.cadn.net.cn

  3. 清理: 定期清除过期的缓存以保持组织有序。spring-doc.cadn.net.cn

  4. Token阈值: 只缓存超过最小阈值(32,768个标记)的内容。spring-doc.cadn.net.cn

  5. 成本优化: 在多个请求中重用缓存的内容以最大限度地节省成本。spring-doc.cadn.net.cn

配置示例

完整配置示例:spring-doc.cadn.net.cn

# 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.options.use-cached-content=true
spring.ai.google.genai.chat.options.cached-content-name=cachedContent/my-cache-123

# Auto-caching configuration
spring.ai.google.genai.chat.options.auto-cache-threshold=50000
spring.ai.google.genai.chat.options.auto-cache-ttl=PT30M

样本控制器

创建一个新的Spring Boot项目,并在pom(或gradle)依赖中添加spring-ai-starter-model-google-genaispring-doc.cadn.net.cn

src/main/resources目录下添加一个application.properties文件,以启用并配置Google GenAI聊天模型:spring-doc.cadn.net.cn

使用Gemini开发者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云项目ID,location是Google云区域,例如us-central1europe-west1等。

每个模型都有其支持的区域集合,在模型页面中可以找到支持的区域列表。spring-doc.cadn.net.cn

这将创建一个GoogleGenAiChatModel实现,你可以在你的类中注入。 以下是一个使用聊天模型进行文本生成的简单@Controller类示例。spring-doc.cadn.net.cn

@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);
    }
}

手动配置

The GoogleGenAiChatModel 实现了 ChatModel 并使用 com.google.genai.Client 连接到 Google GenAI 服务。spring-doc.cadn.net.cn

将如下的spring-ai-google-genai依赖添加到项目中Maven的pom.xml文件中:spring-doc.cadn.net.cn

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-google-genai</artifactId>
</dependency>

请将以下内容添加到您的Gradle build.gradle 构建文件中。spring-doc.cadn.net.cn

dependencies {
    implementation 'org.springframework.ai:spring-ai-google-genai'
}
请参阅依赖管理部分,将Spring AI BOM添加到您的构建文件中。

接下来,创建一个GoogleGenAiChatModel 并用于文本生成:spring-doc.cadn.net.cn

使用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."));

The GoogleGenAiChatOptions 提供了聊天请求的配置信息。 The GoogleGenAiChatOptions.Builder 是流畅选项构建器。spring-doc.cadn.net.cn

迁移至Vertex AI Gemini

如果当前您正在使用Vertex AI Gemini实现(spring-ai-vertex-ai-gemini),您可以使用最少的更改迁移到Google GenAI:spring-doc.cadn.net.cn

关键差异

  1. SDK: Google GenAI 使用新的 com.google.genai.Client 而不是 com.google.cloud.vertexai.VertexAIspring-doc.cadn.net.cn

  2. 认证: 支持API密钥和Google Cloud凭据spring-doc.cadn.net.cn

  3. 包名:类在org.springframework.ai.google.genai中而不是在org.springframework.ai.vertexai.geminispring-doc.cadn.net.cn

  4. 属性前缀: 使用spring.ai.google.genai而不是spring.ai.vertex.ai.geminispring-doc.cadn.net.cn

何时使用Google GenAI还是Vertex AI Gemini

在以下情况下使用 Google GenAI: - 您希望使用 API 密钥进行快速原型设计 - 您需要从 Developer API 获取最新的 Gemini 功能 - 您希望灵活地在 API 密钥模式和 Vertex AI 模式之间切换spring-doc.cadn.net.cn

使用 Vertex AI Gemini 时: spring-doc.cadn.net.cn

  • 您已有现有的 Vertex AI 基础设施
  • 需要特定的 Vertex AI 企业功能
  • 您的组织要求仅在 Google Cloud 上部署

spring-doc.cadn.net.cn

低级Java客户端

Google GenAI 实现基于新的 Google GenAI Java SDK,它提供了访问 Gemini 模型的现代、简洁的 API。spring-doc.cadn.net.cn