VertexAI Gemini

本站(springdoc.cn)中的内容来源于 spring.io ,原始版权归属于 spring.io。由 springdoc.cn 进行翻译,整理。可供个人学习、研究,未经许可,不得进行任何转载、商用或与之相关的行为。 商标声明:Spring 是 Pivotal Software, Inc. 在美国以及其他国家的商标。

Vertex AI Gemini API 支持开发者使用 Gemini 模型构建生成式 AI 应用。该 API 支持多模态提示作为输入,并输出文本或代码。多模态模型能够处理来自多种模态的信息,包括图像、视频和文本。例如,你可以向模型发送一盘饼干的照片,并要求其提供该饼干的制作配方。

Gemini 是由 Google DeepMind 开发的生成式 AI 模型系列,专为多模态用例设计。Gemini API 提供 Gemini 2.0 FlashGemini 2.0 Flash-Lite 模型的访问权限。有关 Vertex AI Gemini API 模型的规格,请参阅 模型信息

先决条件

  • 安装适用于你操作系统的 gcloud CLI。

  • 运行以下命令进行身份验证。将 PROJECT_ID 替换为你的 Google Cloud 项目 ID,并将 ACCOUNT 替换为你的 Google Cloud 用户名。

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

自动配置

Spring AI 自动配置及 Starter 模块的 Artifact 命名已发生重大变更。具体升级说明请参阅 更新文档

Spring AI 为 VertexAI Gemini 聊天客户端提供 Spring Boot 自动配置。要启用该功能,请将以下依赖项添加到项目的 Maven pom.xml 或 Gradle build.gradle 构建文件中:

  • Maven

  • Gradle

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-starter-model-vertex-ai-gemini</artifactId>
</dependency>
dependencies {
    implementation 'org.springframework.ai:spring-ai-starter-model-vertex-ai-gemini'
}
请参考 依赖管理 章节,将 Spring AI BOM 添加到构建文件中。

聊天配置

聊天自动配置的启用/禁用现在通过顶级属性配置,前缀为 spring.ai.model.chat

  • 启用:spring.ai.model.chat=vertexai(默认已启用)

  • 禁用:spring.ai.model.chat=none(或任何非 vertexai 的值)

此项变更是为了支持多模型配置。

前缀 spring.ai.vertex.ai.gemini 用作连接 VertexAI 的属性前缀。

属性 说明 默认值

spring.ai.model.chat

启用聊天模型客户端

vertexai

spring.ai.vertex.ai.gemini.project-id

Google Cloud Platform project ID

-

spring.ai.vertex.ai.gemini.location

Region

-

spring.ai.vertex.ai.gemini.credentials-uri

Vertex AI Gemini 凭证的 URI。设置后,将用于创建 GoogleCredentials 实例以验证 VertexAI

-

spring.ai.vertex.ai.gemini.api-endpoint

Vertex AI Gemini API endpoint.

-

spring.ai.vertex.ai.gemini.scopes

-

spring.ai.vertex.ai.gemini.transport

API 传输协议。GRPC 或 REST。

GRPC

前缀 spring.ai.vertex.ai.gemini.chat 用于配置 VertexAI Gemini 聊天模型的实现。

属性 说明 默认值

spring.ai.vertex.ai.gemini.chat.options.model

支持的 Vertex AI Gemini 聊天模型 包括:gemini-2.0-flashgemini-2.0-flash-lite 以及新版 gemini-2.5-pro-preview-03-25gemini-2.5-flash-preview-04-17 模型。

gemini-2.0-flash

spring.ai.vertex.ai.gemini.chat.options.response-mime-type

生成候选文本的输出响应 MIME 类型。

text/plain: (default) Text output or application/json: JSON response.

spring.ai.vertex.ai.gemini.chat.options.google-search-retrieval

启用 Google 搜索基础功能。

truefalse,默认 false

spring.ai.vertex.ai.gemini.chat.options.temperature

控制输出随机性。取值范围为 [0.0, 1.0](包含边界值)。接近1.0的值会产生更多样化的响应,而接近 0.0 的值通常会使生成结果更稳定可预测。此参数指定后端调用生成模型时使用的默认值。

0.7

spring.ai.vertex.ai.gemini.chat.options.top-k

采样时考虑的最大 Token 数量。生成模型采用 Top-k 与核采样结合的方式:Top-k 采样仅考虑概率最高的前 K 个 Token。

-

spring.ai.vertex.ai.gemini.chat.options.top-p

采样时考虑 Token 的累计概率上限。生成模型采用 Top-k 与核采样结合的方式:核采样选取概率总和至少达到 topP 的最小 Token 集合。

-

spring.ai.vertex.ai.gemini.chat.options.candidate-count

生成的响应消息返回数量。该值必须在 [1, 8] 范围内(含边界值),默认为1。

1

spring.ai.vertex.ai.gemini.chat.options.max-output-tokens

生成的最大 Token 数量。

-

spring.ai.vertex.ai.gemini.chat.options.tool-names

工具名称列表,用于在单次提示请求中启用函数调用功能。这些名称对应的工具必须已在 ToolCallback 注册表中存在。

-

(废弃,由 tool-names 代替) spring.ai.vertex.ai.gemini.chat.options.functions

函数名称列表,用于在单次提示请求中启用函数调用功能。这些名称对应的函数必须已在 functionCallbacks 注册表中存在。

-

spring.ai.vertex.ai.gemini.chat.options.internal-tool-execution-enabled

若为 true 则执行工具调用,否则将模型响应直接返回用户。默认值为null(实际会采用 ToolCallingChatOptions.DEFAULT_TOOL_EXECUTION_ENABLED 的设置值 true)。

-

(废弃internal-tool-execution-enabled 代替) spring.ai.vertex.ai.gemini.chat.options.proxy-tool-calls

若为 true,Spring AI 不会内部处理函数调用,而是将其代理给客户端处理。此时客户端需负责处理函数调用、分派至对应函数并返回结果。若为 false(默认值),Spring AI 将在内部处理函数调用。仅适用于支持函数调用的聊天模型。

false

spring.ai.vertex.ai.gemini.chat.options.safety-settings

安全设置列表(遵循 Vertex AI 安全过滤器 定义),用于控制安全过滤器。每个安全设置可包含方法、阈值和类别参数。

-

所有以 spring.ai.vertex.ai.gemini.chat.options 为前缀的属性,均可通过在 Prompt 调用中添加请求特定的 运行时属性 进行运行时覆盖。

运行时属性

VertexAiGeminiChatOptions.java 提供模型配置参数,包括温度值(temperature)、topK 等。

启动时,默认选项可通过 VertexAiGeminiChatModel(api, options) 构造函数或 spring.ai.vertex.ai.chat.options.* 属性进行配置。

运行时,你可以通过向 Prompt 调用添加新的请求特定选项来覆盖默认配置。例如,针对特定请求覆盖默认温度值:

ChatResponse response = chatModel.call(
    new Prompt(
        "Generate the names of 5 famous pirates.",
        VertexAiGeminiChatOptions.builder()
            .temperature(0.4)
        .build()
    ));
除了特定于模型的 VertexAiGeminiChatOptions 之外,你还可以使用通过 ChatOptionsBuilder#builder() 创建的可移植 ChatOptions 实例。

工具调用

Vertex AI Gemini 模型支持 function calling(在 Google Gemini 上下文中称为函数调用)功能,允许模型在对话期间使用工具。以下是如何定义和使用基于 @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();

You can use the java.util.function beans as tools as well:

@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?")
        .tools("weatherFunction")
        .inputType(Request.class)
        .call()
        .content();

更多内容请参见 工具 文档。

多模态

多模态(Multimodality)是指模型同时理解和处理来自多种(输入)来源的信息的能力,包括文本、PDF、图像、音频和其他数据格式。

图像、音频和视频

谷歌的 Gemini AI 模型支持理解并整合文本、代码、音频、图像和视频的多模态能力。详情参阅博客文章 “ Gemini发布介绍 ”。

Spring AI 的 Message 接口通过引入 Media 类型支持多模态 AI 模型。该类型包含消息中媒体附件的数据和信息,使用 Spring 的 org.springframework.util.MimeTypejava.lang.Object 存储原始媒体数据。

以下是 VertexAiGeminiChatModelIT#multiModalityTest() 中的简单代码示例,展示用户文本与图像的组合处理:

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

var userMessage = new UserMessage("Explain what do you see on this picture?",
        List.of(new Media(MimeTypeUtils.IMAGE_PNG, this.data)));

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

PDF

最新的 Vertex Gemini 支持 PDF 输入类型。使用 application/pdf 媒体类型将 PDF 文件附加到消息中:

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

var userMessage = new UserMessage(
        "You are a very professional document summarization specialist. Please summarize the given document.",
        List.of(new Media(new MimeType("application", "pdf"), pdfData)));

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

示例 Controller

新建 Spring Boot 项目并在 pom(或 gradle)依赖中添加 spring-ai-starter-model-vertex-ai-gemini

src/main/resources 目录下添加 application.properties 文件以启用并配置 VertexAi 聊天模型:

spring.ai.vertex.ai.gemini.project-id=PROJECT_ID
spring.ai.vertex.ai.gemini.location=LOCATION
spring.ai.vertex.ai.gemini.chat.options.model=gemini-2.0-flash
spring.ai.vertex.ai.gemini.chat.options.temperature=0.5
project-id 替换为你的 Google Cloud Project ID,location 替换为 Google Cloud Region(如 us-central1、e`urope-west1` 等)。

每个模型都有其支持的区域列表,你可以在模型页面中找到支持的区域列表。

例如,模型 gemini-2.5-flash 当前仅在 us-central1 区域可用,你必须将位置设置为 us-central1,具体请参考模型页面 Gemini 2.5 Flash - 支持的区域

这将创建一个 VertexAiGeminiChatModel 实现,你可以将其注入到你的类中。以下是一个简单的 @Controller 类示例,该类使用聊天模型进行文本生成。

@RestController
public class ChatController {

    private final VertexAiGeminiChatModel chatModel;

    @Autowired
    public ChatController(VertexAiGeminiChatModel 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);
    }
}

手动配置

VertexAiGeminiChatModel 实现了 ChatModel,并使用 VertexAI 连接到 Vertex AI Gemini 服务。

spring-ai-vertex-ai-gemini 依赖项添加到你项目的 Maven pom.xml 文件中:

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-vertex-ai-gemini</artifactId>
</dependency>

或添加到你的 Gradle build.gradle 构建文件中:

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

接下来,创建一个 VertexAiGeminiChatModel 用于文本生成:

VertexAI vertexApi =  new VertexAI(projectId, location);

var chatModel = new VertexAiGeminiChatModel(this.vertexApi,
    VertexAiGeminiChatOptions.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."));

VertexAiGeminiChatOptions 为聊天请求提供配置信息。VertexAiGeminiChatOptions.Builder 是一个 Fluent 式选项构建器。

低级 Java 客户端

以下类图展示了 Vertex AI Gemini 原生 Java API:

vertex ai gemini native api