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

VertexAI 双子座聊天

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>

自动配置

There has been a significant change in the Spring AI auto-configuration, starter modules' artifact names. Please refer to the 升级说明以获取更多信息。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

属性 描述 默认

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

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

顶点AIspring-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

属性 描述 默认

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

支持使用的 Vertex AI Gemini Chat 模型 包括 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,默认为 false.spring-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

在采样时要考虑的最大Tokens数量。生成器使用了结合了Top-k和 nucleus的采样方法。Top-k采样考虑了概率最高的topK个Tokens集合。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和核(nucleus)采样。核采样会考虑概率总和至少为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

生成的最大Tokens数量。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

(已弃用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

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

-spring-doc.cadn.net.cn

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

如果为真,Spring AI 将不会在内部处理函数调用,而是将其代理给客户端。此时,由客户端负责处理函数调用、将其分发到相应的函数并返回结果。如果为假(默认值),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

On start-up, the default options can be configured with the VertexAiGeminiChatModel(api, options) constructor or the spring.ai.vertex.ai.chat.options.* properties.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人工智能模型通过理解并整合文本、代码、音频、图像和视频支持此功能。 了解更多详情,请参阅博客文章Gemini介绍spring-doc.cadn.net.cn

Spring AI的Message接口通过引入媒体类型来支持多模态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项目,并将spring-boot-starter-web添加到您的pom(或gradle)依赖中。spring-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 Cloud项目ID,而 location 代表Google Cloud区域 如 us-central1, europe-west1, 等……

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

例如,模型=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 构建脚本文件中。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."));

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

Java底层客户端

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

vertex ai gemini native api