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.response-schema

字串,包含 OpenAPI 格式的輸出響應模式,如 ai.google.dev/gemini-api/docs/structured-output#json-schemas 中所述。

-

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 登錄檔中。

-

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

要註冊到 ChatModel 的工具回撥。

-

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.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 例項,透過 ChatOptions#builder() 建立。

工具呼叫

Vertex AI Gemini 模型支援工具呼叫(在 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();

您也可以將 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?")
        .toolNames("weatherFunction")
        .inputType(Request.class)
        .call()
        .content();

工具 文件中查詢更多資訊。

多模態

多模態是指模型能夠同時理解和處理來自各種(輸入)源的資訊,包括 文字pdf影像音訊 和其他資料格式。

影像、音訊、影片

Google 的 Gemini AI 模型透過理解和整合文字、程式碼、音訊、影像和影片來支援此功能。有關更多詳細資訊,請參閱部落格文章 Introducing Gemini

Spring AI 的 Message 介面透過引入媒體型別來支援多模態 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 專案,並將 spring-ai-starter-model-vertex-ai-gemini 新增到您的 pom (或 gradle) 依賴項中。

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 等...

每個模型都有自己支援的區域集,您可以在模型頁面中找到支援區域的列表。

例如,模型 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 服務。

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 是一個流式選項構建器。

低階 Java 客戶端

下圖說明了 Vertex AI Gemini 原生 Java API

vertex ai gemini native api
© . This site is unofficial and not affiliated with VMware.