收藏本站,收获最前沿的人工智能与编程资讯!!

Spring AI 使用 Google GenAI 对话模型

技术文档 17℃ 0

Google GenAI API 允许开发者通过 Gemini 开发者 API 或 Vertex AI,使用谷歌的 Gemini 模型构建生成式人工智能应用。Google GenAI API 支持多模态提示词作为输入,并输出文本或代码。多模态模型能够处理来自多种模态的信息,包括图像、视频和文本。例如,你可以向模型发送一盘饼干的照片,并让它为你提供这些饼干的配方。

Gemini 是由谷歌 DeepMind 开发的生成式人工智能模型系列,专为多模态场景设计。通过 Gemini API,你可以使用 Gemini 2.0 Flash、Gemini 2.0 Flash-Lite、所有 Gemini Pro 模型,以及最新的 Gemini 3 Pro 模型。

该实现提供两种认证模式:

  • Gemini 开发者 API:使用 API 密钥进行快速原型设计和开发

  • Vertex AI:使用谷歌云凭证,适用于具备企业级功能的生产部署

Gemini API 参考文档

前提条件

选择以下认证方式之一:

方式一:Gemini 开发者 API(API 密钥)

  • 从 Google AI Studio 获取 API 密钥

  • 将 API 密钥设置为环境变量或配置到应用属性文件中

方式二:Vertex AI(谷歌云)

  • 安装适用于你操作系统的 gcloud 命令行工具

  • 运行以下命令进行认证,将 PROJECT_ID 替换为你的谷歌云项目 ID,ACCOUNT 替换为你的谷歌云账号

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

自动配置

Spring AI 自动配置、启动器模块的构件名称发生了重大变更。更多信息请参考升级说明。

Spring AI 为 Google GenAI 对话客户端提供 Spring Boot 自动配置。要启用该功能,请在项目的 Maven 或 Gradle 构建文件中添加以下依赖:

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

参考依赖管理章节,将 Spring AI 物料清单(BOM)添加到你的构建文件中。

对话属性配置

现在通过顶级属性 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-keyGemini 开发者 API 密钥,配置后客户端将使用该方式而非 Vertex AI-
spring.ai.google.genai.project-id谷歌云平台项目 ID(Vertex AI 模式必填)-
spring.ai.google.genai.location谷歌云区域(Vertex AI 模式必填)-
spring.ai.google.genai.credentials-uri谷歌云凭证 URI,配置后用于创建认证用的 GoogleCredentials 实例-

模型配置属性

spring.ai.google.genai.chat 前缀用于配置 Google GenAI 对话模型实现。

属性描述默认值
spring.ai.google.genai.chat.options.model支持的模型:gemini-2.0-flash、gemini-2.0-flash-lite、gemini-pro、gemini-1.5-flashgemini-2.0-flash
spring.ai.google.genai.chat.options.response-mime-type输出响应类型:text/plain(默认)或 application/jsontext/plain
spring.ai.google.genai.chat.options.google-search-retrieval启用谷歌搜索基础功能false
spring.ai.google.genai.chat.options.temperature输出随机性,0.0~1.0,值越高越随机0.7
spring.ai.google.genai.chat.options.top-k采样时考虑的最大令牌数-
spring.ai.google.genai.chat.options.top-p采样时考虑的最大累积概率-
spring.ai.google.genai.chat.options.candidate-count返回的生成结果数量,1~81
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.thinking-level模型思考令牌级别:LOW、HIGH、THINKING_LEVEL_UNSPECIFIED-
spring.ai.google.genai.chat.options.include-thoughts为函数调用启用思考签名false
spring.ai.google.genai.chat.options.tool-names单次提示请求启用的工具名称列表-
spring.ai.google.genai.chat.options.tool-callbacks向对话模型注册的工具回调-
spring.ai.google.genai.chat.options.internal-tool-execution-enabled是否内部执行工具调用-
spring.ai.google.genai.chat.options.safety-settings安全设置列表-
spring.ai.google.genai.chat.options.cached-content-name缓存内容名称-
spring.ai.google.genai.chat.options.use-cached-content是否使用缓存内容false
spring.ai.google.genai.chat.options.auto-cache-threshold自动缓存提示词的令牌阈值-
spring.ai.google.genai.chat.options.auto-cache-ttl自动缓存内容有效期PT1H
spring.ai.google.genai.chat.enable-cached-content启用缓存内容管理 Beantrue

所有 spring.ai.google.genai.chat.options 前缀的属性,均可在运行时通过为 Prompt 添加请求级运行时选项覆盖。

运行时选项

GoogleGenAiChatOptions.java 提供模型、温度、topK 等配置。

启动时可通过构造方法或配置文件设置默认选项。

运行时可覆盖默认配置,示例:

ChatResponse response = chatModel.call(
    new Prompt(
        "生成5位著名海盗的名字。",
        GoogleGenAiChatOptions.builder()
            .temperature(0.4)
        .build()
    ));

除了模型专用的 GoogleGenAiChatOptions,也可使用通用 ChatOptions。

工具调用

Google GenAI 模型支持工具调用(函数调用)功能,允许模型在对话中使用工具。以下是 @Tool 定义和使用工具的示例:

public class WeatherService {

    @Tool(description = "获取指定地点的天气")
    public String weatherByLocation(@ToolParam(description= "城市或州名称") String location) {
        ...
    }
}

String response = ChatClient.create(this.chatModel)
        .prompt("波士顿的天气如何?")
        .tools(new WeatherService())
        .call()
        .content();

也可使用 java.util.function Bean 作为工具:

@Bean
@Description("获取指定地点的天气,返回温度格式为36°F或36°C")
public Function<Request, Response> weatherFunction() {
    return new MockWeatherService();
}

String response = ChatClient.create(this.chatModel)
        .prompt("波士顿的天气如何?")
        .toolNames("weatherFunction")
        .inputType(Request.class)
        .call()
        .content();

更多内容查看工具文档。

思考配置

Gemini 模型支持思考能力,允许模型在生成响应前进行深度推理。通过 ThinkingConfig 控制,包含 thinkingBudget、thinkingLevel、includeThoughts 三个选项。

思考级别

描述
LOW最小思考,适用于简单查询
HIGH深度思考,适用于复杂问题
THINKING_LEVEL_UNSPECIFIED模型默认行为

配置方式

属性配置:

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

编程配置:

ChatResponse response = chatModel.call(
    new Prompt(
        "用简单语言解释相对论。",
        GoogleGenAiChatOptions.builder()
            .model("gemini-3-pro-preview")
            .thinkingLevel(GoogleGenAiThinkingLevel.HIGH)
            .build()
    ));

思考预算

ChatResponse response = chatModel.call(
    new Prompt(
        "分步解决这个复杂数学题。",
        GoogleGenAiChatOptions.builder()
            .model("gemini-2.5-pro")
            .thinkingBudget(8192)
            .build()
    ));

选项兼容性

  • thinkingLevel 和 thinkingBudget 互斥,不可同时使用

  • Gemini 3 Pro 使用 thinkingLevel

  • Gemini 2.5 系列使用 thinkingBudget

  • includeThoughts 可与其中一个组合使用

模型支持

模型thinkingLevelthinkingBudget
Gemini 3 Pro支持兼容
Gemini 2.5 Pro不支持支持
Gemini 2.5 Flash不支持支持
Gemini 2.0 Flash不支持不支持

思考签名

Gemini 3 Pro 引入思考签名,在函数调用中保留推理上下文。启用 includeThoughts 后,模型会返回签名,必须在工具执行循环中传递。

Spring AI 会自动处理思考签名,无需手动管理。手动执行模式下需自行提取并传递签名。

// 启用思考签名
String response = ChatClient.create(this.chatModel)
        .prompt("波士顿的天气如何?")
        .options(GoogleGenAiChatOptions.builder()
            .model("gemini-3-pro-preview")
            .includeThoughts(true)
            .build())
        .toolNames("weatherFunction")
        .call()
        .content();

多模态

多模态指模型同时理解和处理文本、图片、音频、视频、PDF 等多种输入信息的能力。

图片/音频/视频

byte[] data = new ClassPathResource("/vertex-test.png").getContentAsByteArray();

var userMessage = UserMessage.builder()
			.text("描述图片内容")
			.media(List.of(new Media(MimeTypeUtils.IMAGE_PNG, data)))
			.build();

ChatResponse response = chatModel.call(new Prompt(List.of(userMessage)));

PDF

var pdfData = new ClassPathResource("/spring-ai-reference-overview.pdf");

var userMessage = UserMessage.builder()
			.text("总结这份文档")
			.media(List.of(new Media(new MimeType("application", "pdf"), pdfData)))
			.build();

var response = this.chatModel.call(new Prompt(List.of(userMessage)));

缓存内容

Google GenAI 上下文缓存可缓存大量内容,降低成本、提升响应速度。最小缓存大小 32768 令牌。

创建缓存

@Autowired
private GoogleGenAiCachedContentService cachedContentService;

CachedContentRequest request = CachedContentRequest.builder()
    .model("gemini-2.0-flash")
    .contents(List.of(Content.builder().role("user").parts(List.of(Part.fromText(largeDocument))).build()))
    .displayName("大容量文档缓存")
    .ttl(Duration.ofHours(1))
    .build();

GoogleGenAiCachedContent cachedContent = cachedContentService.create(request);

使用缓存

ChatResponse response = chatModel.call(
    new Prompt(
        "总结文档要点",
        GoogleGenAiChatOptions.builder()
            .useCachedContent(true)
            .cachedContentName(cacheName)
        .build()
    ));

自动缓存

spring.ai.google.genai.chat.options.auto-cache-threshold=100000
spring.ai.google.genai.chat.options.auto-cache-ttl=PT1H

示例控制器

创建 Spring Boot 项目,添加 spring-ai-starter-model-google-genai 依赖。

配置文件:

# API 密钥方式
spring.ai.google.genai.api-key=YOUR_API_KEY
spring.ai.google.genai.chat.options.model=gemini-2.0-flash

# Vertex AI 方式
spring.ai.google.genai.project-id=PROJECT_ID
spring.ai.google.genai.location=us-central1

控制器代码:

@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 = "讲个笑话") String message) {
        return Map.of("generation", chatModel.call(message));
    }

    @GetMapping("/ai/generateStream")
	public Flux<ChatResponse> generateStream(@RequestParam(value = "message", defaultValue = "讲个笑话") String message) {
        Prompt prompt = new Prompt(new UserMessage(message));
        return chatModel.stream(prompt);
    }
}

手动配置

添加依赖:

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

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

Vertex AI 方式创建模型:

Client genAiClient = Client.builder()
    .project(System.getenv("GOOGLE_CLOUD_PROJECT"))
    .location(System.getenv("GOOGLE_CLOUD_LOCATION"))
    .vertexAI(true)
    .build();

从 Vertex AI Gemini 迁移

Google GenAI 使用新 SDK,支持 API 密钥和谷歌云认证,包名和属性前缀已变更。

底层 Java 客户端

Google GenAI 基于全新的谷歌 GenAI Java SDK 构建,提供现代化的简化 API。

相关推荐