VertexAI Gemini 聊天

Vertex AI Gemini API 允许开发者使用 Gemini 模型构建生成式 AI 应用程序。 Vertex AI Gemini 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 自动配置和启动器模块的构件名称发生了重大变化。 请参阅 升级说明 了解更多信息。

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 项目 ID

-

spring.ai.vertex.ai.gemini.location

区域

-

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

Vertex AI Gemini 凭据的 URI。提供时,它用于创建 GoogleCredentials 实例以对 VertexAI 进行身份验证。

-

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

Vertex AI Gemini API 端点。

-

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:(默认)文本输出或 application/json:JSON 响应。

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

采样时考虑的最大标记数。生成器使用组合的 Top-k 和核采样。Top-k 采样考虑 topK 个最可能的标记集。

-

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

采样时考虑的最大累积标记概率。生成器使用组合的 Top-k 和核采样。核采样考虑概率总和至少为 topP 的最小标记集。

-

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

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

1

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

要生成的最大标记数。

-

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,但如果为 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 提供模型配置,如温度、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 外,您还可以使用可移植的 ChatOptions 实例,使用 ChatOptionsBuilder#builder() 创建。

工具调用

Vertex AI Gemini 模型支持工具调用(在 Google Gemini 上下文中,称为 function calling)功能,允许模型在对话过程中使用工具。 以下是定义和使用基于 @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?")
        .tools("weatherFunction")
        .inputType(Request.class)
        .call()
        .content();

更多信息请参阅 工具 文档。

多模态

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

图像、音频、视频

Google 的 Gemini AI 模型通过理解和集成文本、代码、音频、图像和视频来支持这种能力。 有关更多详细信息,请参阅博客文章 Introducing 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)));

示例控制器

创建 一个新的 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 项目 ID,location 是 Google Cloud 区域 如 us-central1europe-west1 等…​

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

例如,model=gemini-2.5-flash 目前仅在 us-central1 区域可用,您必须设置 location=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 服务。

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

<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 是流畅的选项构建器。

低级 Java 客户端

以下类图说明了 Vertex AI Gemini 原生 Java API:

vertex ai gemini native api