如需最新的快照版本,请使用 Spring AI 1.1.3spring-doc.cadn.net.cn

VertexAI Gemini Chat

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

Gemini 是由 Google DeepMind 开发的一套生成式 AI 模型,专为多模态用例设计。Gemini API 让您可以访问 Gemini 2.0 FlashGemini 2.0 Flash-Lite。 有关 Vertex AI Gemini API 模型的规格,请参阅 模型信息spring-doc.cadn.net.cn

前置条件

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

<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-doc.cadn.net.cn

要启用,spring.ai.model.chat=vertexai(默认已启用)spring-doc.cadn.net.cn

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

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

前缀 spring.ai.vertex.ai.gemini 用作属性前缀,使您能够连接到 VertexAI。spring-doc.cadn.net.cn

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

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

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

VertexAIspring-doc.cadn.net.cn

spring.ai.vertex.ai.gemini.project-idspring-doc.cadn.net.cn

Google Cloud Platform 项目 IDspring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.vertex.ai.gemini.locationspring-doc.cadn.net.cn

区域spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.vertex.ai.gemini.credentials-urispring-doc.cadn.net.cn

用于 Vertex AI Gemini 凭证的 URI。如果提供,它将用于创建一个 GoogleCredentials 实例以对 VertexAI 进行身份验证。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.vertex.ai.gemini.api-endpointspring-doc.cadn.net.cn

Vertex AI Gemini API 端点。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.vertex.ai.gemini.scopesspring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.vertex.ai.gemini.transportspring-doc.cadn.net.cn

API 传输方式。GRPC 或 REST。spring-doc.cadn.net.cn

gRPCspring-doc.cadn.net.cn

前缀 spring.ai.vertex.ai.gemini.chat 是属性前缀,允许您为 VertexAI Gemini Chat 配置聊天模型的实现。spring-doc.cadn.net.cn

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

spring.ai.vertex.ai.gemini.chat.options.modelspring-doc.cadn.net.cn

支持的 Vertex AI Gemini 聊天模型 包括 gemini-2.0-flashgemini-2.0-flash-lite 以及新的 gemini-2.5-pro-preview-03-25gemini-2.5-flash-preview-04-17 模型。spring-doc.cadn.net.cn

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

spring.ai.vertex.ai.gemini.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.vertex.ai.gemini.chat.options.google-search-retrievalspring-doc.cadn.net.cn

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

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

spring.ai.vertex.ai.gemini.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.vertex.ai.gemini.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.vertex.ai.gemini.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.vertex.ai.gemini.chat.options.candidate-countspring-doc.cadn.net.cn

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

1spring-doc.cadn.net.cn

spring.ai.vertex.ai.gemini.chat.options.max-output-tokensspring-doc.cadn.net.cn

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

-spring-doc.cadn.net.cn

spring.ai.vertex.ai.gemini.chat.options.tool-namesspring-doc.cadn.net.cn

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

-spring-doc.cadn.net.cn

(已弃用 by tool-names) spring.ai.vertex.ai.gemini.chat.options.functionsspring-doc.cadn.net.cn

在单个提示请求中,通过函数名称标识以启用函数调用的函数列表。这些名称对应的函数必须存在于 functionCallbacks 注册表中。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.vertex.ai.gemini.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

(已弃用 by internal-tool-execution-enabled) spring.ai.vertex.ai.gemini.chat.options.proxy-tool-callsspring-doc.cadn.net.cn

如果为 true,Spring AI 将不会在内部处理函数调用,而是将其代理给客户端。然后由客户端负责处理函数调用,将其分派到相应的函数,并返回结果。如果为 false(默认值),Spring AI 将在内部处理函数调用。仅适用于支持函数调用的聊天模型spring-doc.cadn.net.cn

falsespring-doc.cadn.net.cn

spring.ai.vertex.ai.gemini.chat.options.safety-settingsspring-doc.cadn.net.cn

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

-spring-doc.cadn.net.cn

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

运行时选项

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

启动时,可以使用VertexAiGeminiChatModel(api, options)构造函数或spring.ai.vertex.ai.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.",
        VertexAiGeminiChatOptions.builder()
            .temperature(0.4)
        .build()
    ));
除此之外,除了特定模型的VertexAiGeminiChatOptions之外,您还可以使用一个通用的ChatOptions实例,该实例是通过调用ChatOptions#builder()创建的。

工具调用

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

多模态

多模态指的是模型同时理解并处理来自各种(输入)来源的信息的能力,包括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

以下是从 VertexAiGeminiChatModelIT#multiModalityTest() 中提取的一个简单代码示例,演示了如何将用户文本与图像结合使用。spring-doc.cadn.net.cn

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 文件附加到消息中:spring-doc.cadn.net.cn

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-geminispring-doc.cadn.net.cn

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

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

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

例如,model=gemini-2.5-flash 目前仅在 us-central1 区域可用,您必须设置 location=us-central1, 参考模型页面 Gemini 2.5 Flash - 支持的区域spring-doc.cadn.net.cn

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

@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-doc.cadn.net.cn

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

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

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

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

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

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

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

低级Java客户端

以下类图展示了 Vertex AI Gemini 原生 Java API:spring-doc.cadn.net.cn

vertex ai gemini native api