VertexAI Gemini 聊天

Vertex AI Gemini API 允許開發者使用 Gemini 模型構建生成式 AI 應用。 Vertex AI Gemini API 支援將多模態提示作為輸入,並輸出文字或程式碼。多模態模型是一種能夠處理來自多種模態資訊(包括影像、影片和文字)的模型。例如,您可以向模型傳送一張餅乾的照片,並要求它提供這些餅乾的配方。

Gemini 是 Google DeepMind 開發的一系列生成式 AI 模型,專為多模態用例設計。Gemini API 讓您可以使用 Gemini 1.0 Pro Vision 和 Gemini 1.0 Pro 模型。有關 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 自動配置、starter 模組的 artifact 名稱發生了重大變化。請參閱 升級注意事項 瞭解更多資訊。

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

Google Cloud Platform 專案 ID

-

spring.ai.vertex.ai.gemini.location

區域

-

spring.ai.vertex.ai.gemini.credentialsUri

Vertex AI Gemini 憑據的 URI。提供後,將用於建立 GoogleCredentials 例項以對 VertexAI 進行身份驗證。

-

spring.ai.vertex.ai.gemini.apiEndpoint

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 聊天模型 包括 (1.0) gemini-progemini-pro-vision(已棄用)以及新的 gemini-1.5-pro-001gemini-1.5-flash-001 模型。

gemini-1.5-pro-001

spring.ai.vertex.ai.gemini.chat.options.responseMimeType

生成的候選文字的輸出響應 mimetype。

text/plain:(預設)文字輸出,或 application/json:JSON 響應。

spring.ai.vertex.ai.gemini.chat.options.googleSearchRetrieval

使用 Google 搜尋 Grounding 功能

truefalse,預設 false

spring.ai.vertex.ai.gemini.chat.options.temperature

控制輸出的隨機性。取值範圍為 [0.0, 1.0],包含邊界。值越接近 1.0,生成的響應越多樣化;值越接近 0.0,生成模型的響應通常越不令人驚訝。此值指定了後端在呼叫生成模型時使用的預設值。

0.8

spring.ai.vertex.ai.gemini.chat.options.topK

取樣時要考慮的最大 token 數。生成模型使用 Top-k 和 nucleus 取樣相結合的方式。Top-k 取樣考慮 topK 個最可能的 token 集合。

-

spring.ai.vertex.ai.gemini.chat.options.topP

取樣時要考慮的 token 的最大累積機率。生成模型使用 Top-k 和 nucleus 取樣相結合的方式。Nucleus 取樣考慮機率和至少為 topP 的最小 token 集合。

-

spring.ai.vertex.ai.gemini.chat.options.candidateCount

要返回的生成響應訊息的數量。此值必須介於 [1, 8] 之間,包含邊界。預設值為 1。

-

spring.ai.vertex.ai.gemini.chat.options.candidateCount

要返回的生成響應訊息的數量。此值必須介於 [1, 8] 之間,包含邊界。預設值為 1。

-

spring.ai.vertex.ai.gemini.chat.options.maxOutputTokens

要生成的最大 token 數。

-

spring.ai.vertex.ai.gemini.chat.options.frequencyPenalty

-

spring.ai.vertex.ai.gemini.chat.options.presencePenalty

-

spring.ai.vertex.ai.gemini.chat.options.toolNames

工具列表,按名稱標識,用於在單個提示請求中啟用函式呼叫。具有這些名稱的工具必須存在於 ToolCallback 登錄檔中。

-

(已被 toolNames 棄用)spring.ai.vertex.ai.gemini.chat.options.functions

函式列表,按名稱標識,用於在單個提示請求中啟用函式呼叫。具有這些名稱的函式必須存在於 functionCallbacks 登錄檔中。

-

spring.ai.vertex.ai.gemini.chat.options.proxy-tool-calls

如果為 true,Spring AI 將不會在內部處理函式呼叫,而是將其代理到客戶端。然後由客戶端負責處理函式呼叫,將其分派到適當的函式,並返回結果。如果為 false(預設值),Spring AI 將在內部處理函式呼叫。僅適用於支援函式呼叫的聊天模型

false

spring.ai.vertex.ai.gemini.chat.options.safetySettings

用於控制安全過濾器的安全設定列表,定義見 Vertex AI 安全過濾器。每個安全設定可以包含方法、閾值和類別。

-

所有帶有 spring.ai.vertex.ai.gemini.chat.options 字首的屬性都可以在執行時透過向 Prompt 呼叫新增請求特定的 執行時選項 來覆蓋。

執行時選項

VertexAiGeminiChatOptions.java 提供了模型配置,例如 temperature、topK 等。

啟動時,可以透過 VertexAiGeminiChatModel(api, options) 建構函式或 spring.ai.vertex.ai.chat.options.* 屬性來配置預設選項。

在執行時,您可以透過向 Prompt 呼叫新增新的、針對請求的選項來覆蓋預設選項。例如,要為特定請求覆蓋預設的 temperature

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 模型支援工具呼叫功能,允許模型在對話中使用工具。以下是定義和使用基於 @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 beans 作為工具

@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();

更多資訊請參閱 工具 文件。

多模態

多模態是指模型同時理解和處理來自各種來源的資訊的能力,包括 textpdfimagesaudio 和其他資料格式。

影像、音訊、影片

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

Spring AI 的 Message 介面透過引入 Media 型別來支援多模態 AI 模型。此型別包含訊息中媒體附件的資料和資訊,使用 Spring 的 org.springframework.util.MimeTypejava.lang.Object 來表示原始媒體資料。

下面是一個從 VertexAiGeminiChatModelIT.java 中提取的簡單程式碼示例,演示了使用者文字與影像的組合。

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=vertex-pro-vision
spring.ai.vertex.ai.gemini.chat.options.temperature=0.5
project-id 替換為您的 Google Cloud 專案 ID,將 location 替換為 Gemini 區域

這將建立一個 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_PRO_1_5_PRO)
        .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