Google GenAI Chat
Google GenAI API 允許開發者透過 Gemini Developer API 或 Vertex AI 使用 Google 的 Gemini 模型構建生成式 AI 應用程式。Google GenAI API 支援多模態提示作為輸入,並輸出文字或程式碼。多模態模型能夠處理來自多種模態的資訊,包括影像、影片和文字。例如,您可以向模型傳送一盤餅乾的照片,並要求它提供這些餅乾的食譜。
Gemini 是 Google DeepMind 開發的生成式 AI 模型家族,專為多模態用例設計。Gemini API 允許您訪問 Gemini 2.0 Flash、Gemini 2.0 Flash-Lite 和 Gemini Pro 模型。
此實現提供了兩種身份驗證模式
-
Gemini Developer API:使用 API 金鑰進行快速原型開發和開發
-
Vertex AI:使用 Google Cloud 憑據進行具有企業功能的生產部署
先決條件
選擇以下身份驗證方法之一
選項 1:Gemini Developer API(API 金鑰)
-
從 Google AI Studio 獲取 API 金鑰
-
將 API 金鑰設定為環境變數或應用程式屬性
選項 2:Vertex AI (Google Cloud)
-
安裝適用於您的作業系統的 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 為 Google GenAI Chat 客戶端提供 Spring Boot 自動配置。要啟用它,請將以下依賴項新增到您專案的 Maven pom.xml 或 Gradle build.gradle 構建檔案
-
Maven
-
Gradle
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-google-genai</artifactId>
</dependency>
dependencies {
implementation 'org.springframework.ai:spring-ai-starter-model-google-genai'
}
| 請參閱 依賴項管理 部分,將 Spring AI BOM 新增到您的構建檔案中。 |
聊天屬性
|
聊天自動配置的啟用和停用現在透過以 要啟用,`spring.ai.model.chat=google-genai`(預設啟用) 要停用,`spring.ai.model.chat=none`(或任何與 `google-genai` 不匹配的值) 此更改是為了允許配置多個模型。 |
連線屬性
字首 `spring.ai.google.genai` 用作屬性字首,允許您連線到 Google GenAI。
| 財產 | 描述 | 預設值 |
|---|---|---|
spring.ai.model.chat |
啟用聊天模型客戶端 |
google-genai |
spring.ai.google.genai.api-key |
Gemini Developer API 的 API 金鑰。如果提供,客戶端將使用 Gemini Developer API 而不是 Vertex AI。 |
- |
spring.ai.google.genai.project-id |
Google Cloud Platform 專案 ID(Vertex AI 模式必需) |
- |
spring.ai.google.genai.location |
Google Cloud 區域(Vertex AI 模式必需) |
- |
spring.ai.google.genai.credentials-uri |
Google Cloud 憑據的 URI。如果提供,它將用於建立 `GoogleCredentials` 例項進行身份驗證。 |
- |
聊天模型屬性
字首 `spring.ai.google.genai.chat` 是屬性字首,允許您配置 Google GenAI Chat 的聊天模型實現。
| 財產 | 描述 | 預設值 |
|---|---|---|
spring.ai.google.genai.chat.options.model |
支援的 Google GenAI 聊天模型包括 `gemini-2.0-flash`、`gemini-2.0-flash-lite`、`gemini-pro` 和 `gemini-1.5-flash`。 |
gemini-2.0-flash |
spring.ai.google.genai.chat.options.response-mime-type |
生成候選文字的輸出響應 MIME 型別。 |
`text/plain`:(預設)文字輸出或 `application/json`:JSON 響應。 |
spring.ai.google.genai.chat.options.google-search-retrieval |
使用 Google 搜尋 Grounding 功能 |
`true` 或 `false`,預設 `false`。 |
spring.ai.google.genai.chat.options.temperature |
控制輸出的隨機性。值範圍為 [0.0,1.0],包括。值越接近 1.0 將產生更多樣化的響應,而值越接近 0.0 通常會導致生成器的響應不那麼令人驚訝。 |
0.7 |
spring.ai.google.genai.chat.options.top-k |
取樣時要考慮的最大令牌數。生成器使用 Top-k 和 nucleus 取樣相結合。Top-k 取樣考慮 topK 個最可能的令牌集。 |
- |
spring.ai.google.genai.chat.options.top-p |
取樣時要考慮的令牌的最大累積機率。生成器使用 Top-k 和 nucleus 取樣相結合。nucleus 取樣考慮機率和至少為 topP 的最小令牌集。 |
- |
spring.ai.google.genai.chat.options.candidate-count |
要返回的生成響應訊息的數量。此值必須在 [1, 8] 之間,包括。預設為 1。 |
1 |
spring.ai.google.genai.chat.options.max-output-tokens |
要生成的最大令牌數。 |
- |
spring.ai.google.genai.chat.options.frequency-penalty |
用於減少重複的頻率懲罰。 |
- |
spring.ai.google.genai.chat.options.presence-penalty |
用於減少重複的出現懲罰。 |
- |
spring.ai.google.genai.chat.options.thinking-budget |
思考過程的思考預算。 |
- |
spring.ai.google.genai.chat.options.tool-names |
工具列表,透過其名稱標識,用於在單個提示請求中啟用函式呼叫。具有這些名稱的工具必須存在於 ToolCallback 登錄檔中。 |
- |
spring.ai.google.genai.chat.options.tool-callbacks |
要註冊到 ChatModel 的工具回撥。 |
- |
spring.ai.google.genai.chat.options.internal-tool-execution-enabled |
如果為 true,則應執行工具,否則將模型響應返回給使用者。預設為 null,但如果為 null,則將考慮 `ToolCallingChatOptions.DEFAULT_TOOL_EXECUTION_ENABLED`(為 true) |
- |
spring.ai.google.genai.chat.options.safety-settings |
用於控制安全過濾器的安全設定列表,如 Google GenAI 安全設定 所定義。每個安全設定都可以有一個方法、閾值和類別。 |
- |
| 所有以 `spring.ai.google.genai.chat.options` 為字首的屬性都可以在執行時透過向 `Prompt` 呼叫新增特定請求的 執行時選項 來覆蓋。 |
執行時選項
GoogleGenAiChatOptions.java 提供模型配置,例如溫度、topK 等。
在啟動時,可以使用 `GoogleGenAiChatModel(client, options)` 建構函式或 `spring.ai.google.genai.chat.options.*` 屬性配置預設選項。
在執行時,您可以透過向 `Prompt` 呼叫新增新的特定請求選項來覆蓋預設選項。例如,要覆蓋特定請求的預設溫度
ChatResponse response = chatModel.call(
new Prompt(
"Generate the names of 5 famous pirates.",
GoogleGenAiChatOptions.builder()
.temperature(0.4)
.build()
));
| 除了模型特定的 `GoogleGenAiChatOptions`,您還可以使用可移植的 ChatOptions 例項,使用 ChatOptions#builder() 建立。 |
工具呼叫
Google GenAI 模型支援工具呼叫(函式呼叫)功能,允許模型在對話期間使用工具。以下是定義和使用基於 `@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();
在 工具 文件中查詢更多資訊。
多模態
多模態是指模型能夠同時理解和處理來自各種(輸入)源的資訊的能力,包括 `text`、`pdf`、`images`、`audio` 和其他資料格式。
影像、音訊、影片
Google 的 Gemini AI 模型透過理解和整合文字、程式碼、音訊、影像和影片來支援此功能。有關更多詳細資訊,請參閱部落格文章 Introducing Gemini。
Spring AI 的 Message 介面透過引入媒體型別來支援多模態 AI 模型。此型別包含訊息中媒體附件的資料和資訊,使用 Spring 的 org.springframework.util.MimeType 和 java.lang.Object 用於原始媒體資料。
下面是摘自 GoogleGenAiChatModelIT.java 的簡單程式碼示例,演示了使用者文字與影像的組合。
byte[] data = new ClassPathResource("/vertex-test.png").getContentAsByteArray();
var userMessage = UserMessage.builder()
.text("Explain what do you see o this picture?")
.media(List.of(new Media(MimeTypeUtils.IMAGE_PNG, data)))
.build();
ChatResponse response = chatModel.call(new Prompt(List.of(this.userMessage)));
Google GenAI 支援 PDF 輸入型別。使用 `application/pdf` 媒體型別將 PDF 檔案附加到訊息
var pdfData = new ClassPathResource("/spring-ai-reference-overview.pdf");
var userMessage = UserMessage.builder()
.text("You are a very professional document summarization specialist. Please summarize the given document.")
.media(List.of(new Media(new MimeType("application", "pdf"), pdfData)))
.build();
var response = this.chatModel.call(new Prompt(List.of(userMessage)));
示例控制器
建立一個新的 Spring Boot 專案,並將 `spring-ai-starter-model-google-genai` 新增到您的 pom(或 gradle)依賴項中。
在 `src/main/resources` 目錄下新增 `application.properties` 檔案,以啟用和配置 Google GenAI 聊天模型
使用 Gemini Developer API(API 金鑰)
spring.ai.google.genai.api-key=YOUR_API_KEY
spring.ai.google.genai.chat.options.model=gemini-2.0-flash
spring.ai.google.genai.chat.options.temperature=0.5
使用 Vertex AI
spring.ai.google.genai.project-id=PROJECT_ID
spring.ai.google.genai.location=LOCATION
spring.ai.google.genai.chat.options.model=gemini-2.0-flash
spring.ai.google.genai.chat.options.temperature=0.5
| 將 `project-id` 替換為您的 Google Cloud 專案 ID,`location` 是 Google Cloud 區域,如 `us-central1`、`europe-west1` 等…… |
|
每個模型都有自己支援的區域集,您可以在模型頁面中找到支援區域列表。 |
這將建立一個 `GoogleGenAiChatModel` 實現,您可以將其注入到您的類中。這是一個簡單的 `@Controller` 類示例,它使用聊天模型進行文字生成。
@RestController
public class ChatController {
private final GoogleGenAiChatModel chatModel;
@Autowired
public ChatController(GoogleGenAiChatModel 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);
}
}
手動配置
GoogleGenAiChatModel 實現了 `ChatModel`,並使用 `com.google.genai.Client` 連線到 Google GenAI 服務。
將 `spring-ai-google-genai` 依賴項新增到您專案的 Maven `pom.xml` 檔案中
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-google-genai</artifactId>
</dependency>
或新增到您的 Gradle build.gradle 構建檔案中。
dependencies {
implementation 'org.springframework.ai:spring-ai-google-genai'
}
| 請參閱 依賴項管理 部分,將 Spring AI BOM 新增到您的構建檔案中。 |
接下來,建立 `GoogleGenAiChatModel` 並將其用於文字生成
使用 API 金鑰
Client genAiClient = Client.builder()
.apiKey(System.getenv("GOOGLE_API_KEY"))
.build();
var chatModel = new GoogleGenAiChatModel(genAiClient,
GoogleGenAiChatOptions.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."));
使用 Vertex AI
Client genAiClient = Client.builder()
.project(System.getenv("GOOGLE_CLOUD_PROJECT"))
.location(System.getenv("GOOGLE_CLOUD_LOCATION"))
.vertexAI(true)
.build();
var chatModel = new GoogleGenAiChatModel(genAiClient,
GoogleGenAiChatOptions.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."));
`GoogleGenAiChatOptions` 提供聊天請求的配置資訊。`GoogleGenAiChatOptions.Builder` 是流暢的選項構建器。
從 Vertex AI Gemini 遷移
如果您目前正在使用 Vertex AI Gemini 實現(`spring-ai-vertex-ai-gemini`),您可以以最小的更改遷移到 Google GenAI