> ## Documentation Index
> Fetch the complete documentation index at: https://javaai.pig4cloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# VertexAI Gemini 聊天

[Vertex AI Gemini API](https://cloud.google.com/vertex-ai/docs/generative-ai/multimodal/overview) 允许开发人员使用 Gemini 模型构建生成式 AI 应用程序。
Vertex AI Gemini API 支持多模态提示作为输入和输出文本或代码。
多模态模型是一种能够处理来自多种模态（包括图像、视频和文本）信息的模型。例如，你可以向模型发送一张饼干盘子的照片，并要求它提供这些饼干的食谱。

<Frame caption="Spring AI VertexAI Gemini 集成">
  <img src="https://mintlify.s3.us-west-1.amazonaws.com/pig/images/spring-ai-vertexai-gemini-integration.jpg" width="800" />
</Frame>

Gemini 是由 Google DeepMind 开发的一系列生成式 AI 模型，专为多模态用例而设计。Gemini API 允许你访问 [Gemini 2.0 Flash](https://cloud.google.com/vertex-ai/generative-ai/docs/models/gemini/2-0-flash) 和 [Gemini 2.0 Flash-Lite](https://cloud.google.com/vertex-ai/generative-ai/docs/models/gemini/2-0-flash-lite)。
有关 Vertex AI Gemini API 模型的规范，请参阅[模型信息](https://cloud.google.com/vertex-ai/generative-ai/docs/models#gemini-models)。

<Note>
  有关详细的 API 参考，请参阅 [Gemini API 参考](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference)。
</Note>

## 前提条件

* 根据你的操作系统安装 [gcloud](https://cloud.google.com/sdk/docs/install) CLI。
* 通过运行以下命令进行身份验证。
  将 `PROJECT_ID` 替换为你的 Google Cloud 项目 ID，将 `ACCOUNT` 替换为你的 Google Cloud 用户名。

```bash theme={"system"}
gcloud config set project <PROJECT_ID> &&\
gcloud auth application-default login <ACCOUNT>
```

## 自动配置

<Note>
  Spring AI 自动配置、启动器模块的构件名称发生了重大变化。
  有关更多信息，请参阅[升级说明](https://docs.spring.io/spring-ai/reference/upgrade-notes.html)。
</Note>

Spring AI 为 VertexAI Gemini 聊天客户端提供 Spring Boot 自动配置。
要启用它，请将以下依赖项添加到项目的构建文件中：

<Tabs>
  <Tab title="Maven">
    ```xml theme={"system"}
    <dependency>
        <groupId>org.springframework.ai</groupId>
        <artifactId>spring-ai-starter-model-vertex-ai-gemini</artifactId>
    </dependency>
    ```
  </Tab>

  <Tab title="Gradle">
    ```gradle theme={"system"}
    dependencies {
        implementation 'org.springframework.ai:spring-ai-starter-model-vertex-ai-gemini'
    }
    ```
  </Tab>
</Tabs>

<Tip>
  请参阅[依赖管理](/spring4ai/getting-started#dependency-management)部分，将 Spring AI BOM 添加到你的构建文件中。
</Tip>

### 聊天属性

<Note>
  聊天自动配置的启用和禁用现在通过前缀为 `spring.ai.model.chat` 的顶级属性进行配置。

  要启用，`spring.ai.model.chat=vertexai` (默认启用)

  要禁用，`spring.ai.model.chat=none` (或任何与 vertexai 不匹配的值)

  此更改是为了允许配置多个模型。
</Note>

前缀 `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 Chat 的聊天模型实现。

| 属性                                                                      | 描述                                                                                                                                                                                                                             | 默认值                                                |
| :---------------------------------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------- |
| spring.ai.vertex.ai.gemini.chat.options.model                           | 支持的 [Vertex AI Gemini 聊天模型](https://cloud.google.com/vertex-ai/generative-ai/docs/models#gemini-models) 包括 `gemini-2.0-flash`、`gemini-2.0-flash-lite` 以及新的 `gemini-2.5-pro-preview-03-25`、`gemini-2.5-flash-preview-04-17` 模型。 | gemini-2.0-flash                                   |
| spring.ai.vertex.ai.gemini.chat.options.response-mime-type              | 生成的候选文本的输出响应 mimetype。                                                                                                                                                                                                         | `text/plain`：（默认）文本输出或 `application/json`：JSON 响应。 |
| spring.ai.vertex.ai.gemini.chat.options.google-search-retrieval         | 使用 Google 搜索 Grounding 功能                                                                                                                                                                                                      | `true` 或 `false`，默认为 `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 注册表中。                                                                                                                                                                  | -                                                  |
| spring.ai.vertex.ai.gemini.chat.options.functions                       | （已由 `tool-names` 弃用）在单个提示请求中启用函数调用的函数列表（按其名称标识）。具有这些名称的函数必须存在于 functionCallbacks 注册表中。                                                                                                                                         | -                                                  |
| spring.ai.vertex.ai.gemini.chat.options.internal-tool-execution-enabled | 如果为 true，则应执行工具，否则模型中的响应将返回给用户。默认为 null，但如果为 null，则会考虑 `ToolCallingChatOptions.DEFAULT_TOOL_EXECUTION_ENABLED`（即 true）                                                                                                         | -                                                  |
| spring.ai.vertex.ai.gemini.chat.options.proxy-tool-calls                | （已由 `internal-tool-execution-enabled` 弃用）如果为 true，Spring AI 将不会在内部处理函数调用，而是将它们代理到客户端。然后由客户端负责处理函数调用，将它们分派到适当的函数，并返回结果。如果为 false（默认值），Spring AI 将在内部处理函数调用。                                                                     | false                                              |
| spring.ai.vertex.ai.gemini.chat.options.safety-settings                 | 用于控制安全过滤器的安全设置列表，由 [Vertex AI 安全过滤器](https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/configure-safety-filters)定义。每个安全设置都可以有一个方法、阈值和类别。                                                                        | -                                                  |

<Tip>
  所有以 `spring.ai.vertex.ai.gemini.chat.options` 为前缀的属性都可以在运行时通过向 `Prompt` 调用添加特定于请求的运行时选项来覆盖。
</Tip>

## 运行时选项

[VertexAiGeminiChatOptions.java](https://github.com/spring-projects/spring-ai/blob/main/models/spring-ai-vertex-ai-gemini/src/main/java/org/springframework/ai/vertexai/gemini/VertexAiGeminiChatOptions.java) 提供模型配置，例如温度、topK 等。

在启动时，可以使用 `VertexAiGeminiChatModel(api, options)` 构造函数或 `spring.ai.vertex.ai.chat.options.*` 属性配置默认选项。

在运行时，你可以通过向 `Prompt` 调用添加新的、特定于请求的选项来覆盖默认选项。
例如，要为特定请求覆盖默认温度：

```java theme={"system"}
ChatResponse response = chatModel.call(
    new Prompt(
        "生成 5 个著名海盗的名字。",
        VertexAiGeminiChatOptions.builder()
            .temperature(0.4)
        .build()
    ));
```

<Tip>
  除了特定于模型的 `VertexAiGeminiChatOptions`之外，你还可以使用通过 [ChatOptionsBuilder#builder()](https://github.com/spring-projects/spring-ai/blob/main/spring-ai-model/src/main/java/org/springframework/ai/chat/prompt/DefaultChatOptionsBuilder.java) 创建的可移植 [ChatOptions](https://github.com/spring-projects/spring-ai/blob/main/spring-ai-model/src/main/java/org/springframework/ai/chat/prompt/ChatOptions.java) 实例。
</Tip>

## 工具调用

Vertex AI Gemini 模型支持工具调用（在 Google Gemini 上下文中，称为 `function calling`）功能，允许模型在对话期间使用工具。
以下是如何定义和使用基于 `@Tool` 的工具的示例：

```java theme={"system"}
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 作为工具：

```java theme={"system"}
@Bean
@Description("获取某个位置的天气。以 36°F 或 36°C 格式返回温度。")
public Function<Request, Response> weatherFunction() {
    return new MockWeatherService();
}

String response = ChatClient.create(this.chatModel)
        .prompt("波士顿的天气怎么样？")
        .tools("weatherFunction")
        .inputType(Request.class)
        .call()
        .content();
```

<Tip>
  在[工具](/spring4ai/api/tools)文档中查找更多信息。
</Tip>

## 多模态

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

### 图像、音频、视频

Google 的 Gemini AI 模型通过理解和集成文本、代码、音频、图像和视频来支持此功能。
有关更多详细信息，请参阅博文 [Introducing Gemini](https://blog.google/technology/ai/google-gemini-ai/#introducing-gemini)。

Spring AI 的 `Message` 接口通过引入 Media 类型来支持多模态 AI 模型。
此类型包含有关消息中媒体附件的数据和信息，使用 Spring 的 `org.springframework.util.MimeType` 和 `java.lang.Object` 来获取原始媒体数据。

以下是从 [VertexAiGeminiChatModelIT#multiModalityTest()](https://github.com/spring-projects/spring-ai/blob/main/models/spring-ai-vertex-ai-gemini/src/test/java/org/springframework/ai/vertexai/gemini/VertexAiGeminiChatModelIT.java) 中提取的简单代码示例，演示了用户文本与图像的组合：

```java theme={"system"}
byte[] data = new ClassPathResource("/vertex-test.png").getContentAsByteArray();

var userMessage = new UserMessage("解释一下你在这张图片上看到了什么？",
        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 文件附加到消息：

```java theme={"system"}
var pdfData = new ClassPathResource("/spring-ai-reference-overview.pdf");

var userMessage = new UserMessage(
        "你是一位非常专业的文档摘要专家。请总结给定的文档。",
        List.of(new Media(new MimeType("application", "pdf"), pdfData)));

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

## 示例控制器

[创建](https://start.spring.io/)一个新的 Spring Boot 项目，并将 `spring-ai-starter-model-vertex-ai-gemini` 添加到你的 pom (或 gradle) 依赖项中。

在 `src/main/resources` 目录下添加一个 `application.properties` 文件，以启用和配置 VertexAi 聊天模型：

```properties theme={"system"}
spring.ai.vertex.ai.gemini.project-id=项目ID
spring.ai.vertex.ai.gemini.location=位置
spring.ai.vertex.ai.gemini.chat.options.model=gemini-2.0-flash
spring.ai.vertex.ai.gemini.chat.options.temperature=0.5
```

<Tip>
  将 `project-id` 替换为你的 Google Cloud 项目 ID，并将 `location` 替换为 Google Cloud 区域，
  例如 `us-central1`、`europe-west1` 等...
</Tip>

<Note>
  每个模型都有其自己的一组支持区域，你可以在模型页面中找到支持区域的列表。

  例如，模型=`gemini-2.5-flash` 目前仅在 `us-central1` 区域可用，你必须将 location 设置为 `us-central1`，
  遵循模型页面 [Gemini 2.5 Flash - 支持的区域](https://cloud.google.com/vertex-ai/generative-ai/docs/models/gemini/2-5-flash)。
</Note>

<Card title="文档有误？请协助编辑" icon="pencil" href="https://github.com/javaai-pig4cloud-com/javaai-docs/edit/main/spring-ai/api/chat/vertexai-gemini-chat.mdx">
  发现文档问题？点击此处直接在 GitHub 上编辑并提交 PR，帮助我们改进文档！
</Card>
