VertexAI Gemini チャット
Vertex AI Gemini API を使用すると、開発者は Gemini モデルを使用して生成 AI アプリケーションを構築できます。Vertex AI Gemini API は、入力および出力のテキストまたはコードとしてマルチモーダルプロンプトをサポートします。マルチモーダルモデルは、イメージ、ビデオ、テキストなどの複数のモダリティからの情報を処理できるモデルです。例: モデルにクッキーの皿の写真を送り、そのクッキーのレシピを教えてもらうことができます。
Gemini は、Google、DeepMind によって開発された、マルチモーダルユースケース向けに設計された生成 AI モデルファミリーです。Gemini API を使用すると、Gemini 2.0 フラッシュ および Gemini 2.0 フラッシュライト にアクセスできます。Vertex AI、Gemini API モデルの仕様については、モデル情報 を参照してください。
前提条件
OS に適した 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=vertexai (デフォルトで有効になっています) 無効にするには、spring.ai.model.chat=none (または頂点と一致しない値) この変更は、複数のモデルの構成を可能にするために行われます。 |
接頭辞 spring.ai.vertex.ai.gemini は、VertexAI への接続を可能にするプロパティ接頭辞として使用されます。
| プロパティ | 説明 | デフォルト |
|---|---|---|
spring.ai.model.chat | チャットモデルクライアントを有効にする | 頂点 |
spring.ai.vertex.ai.gemini.project-id | Google クラウドプラットフォームプロジェクト ID | - |
spring.ai.vertex.ai.gemini.location | 領域 | - |
spring.ai.vertex.ai.gemini.credentials-uri | Vertex AI Gemini 資格情報への URI。指定すると、 | - |
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 チャットモデル には、 | ジェミニ 2.0 フラッシュ |
spring.ai.vertex.ai.gemini.chat.options.response-mime-type | 生成された候補テキストのレスポンス MIME 型を出力します。 |
|
spring.ai.vertex.ai.gemini.chat.options.response-schema | ai.google.dev/gemini-api/docs/ 構造化出力 #json-schemas (英語) に従って、OpenAPI 形式の出力レスポンススキーマを含む文字列。 | - |
spring.ai.vertex.ai.gemini.chat.options.google-search-retrieval | Google 検索接地機能を使用する |
|
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 サンプリングでは、最も可能性の高い上位 K 個のトークンのセットが考慮されます。 | - |
spring.ai.vertex.ai.gemini.chat.options.top-p | サンプリング時に考慮するトークンの最大累積確率。生成では、Top-k サンプリングと核サンプリングを組み合わせて使用します。nucleus サンプリングでは、確率の合計が少なくとも 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 の場合、true の | - |
spring.ai.vertex.ai.gemini.chat.options.safety-settings | Vertex AI 安全フィルター で定義されている、安全フィルターを制御するための安全設定のリスト。各安全設定には、方法、しきい値、カテゴリを設定できます。 | - |
spring.ai.vertex.ai.gemini.chat.options というプレフィックスが付いたすべてのプロパティは、リクエスト固有のランタイムオプションを Prompt 呼び出しに追加することで実行時にオーバーライドできます。 |
ランタイムオプション
VertexAiGeminiChatOptions.java [GitHub] (英語) は、温度、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#builder() [GitHub] (英語) で作成されたポータブル ChatOptions [GitHub] (英語) インスタンスを使用できます。 |
ツール呼び出し
Vertex AI Gemini モデルはツール呼び出し(Google Gemini のコンテキストでは function calling と呼ばれます)機能をサポートしており、モデルは会話中にツールを使用できます。以下は、@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 モデルは、テキスト、コード、オーディオ、イメージ、ビデオを理解して統合することにより、この機能をサポートします。詳細については、ブログ投稿 Gemini の導入 (英語) を参照してください。
Spring AI の Message インターフェースは、メディア型を導入することでマルチモーダル AI モデルをサポートします。この型には、生のメディアデータに Spring の org.springframework.util.MimeType および java.lang.Object を使用して、メッセージ内のメディア添付ファイルに関するデータと情報が含まれます。
以下は、VertexAiGeminiChatModelIT#multiModalityTest() [GitHub] (英語) から抽出された簡単なコード例で、ユーザーテキストとイメージの組み合わせを示しています。
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))); 最新の Vertex Gemini は PDF 入力型をサポートしています。メッセージに PDF ファイルを添付するには、application/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)));安全設定と安全評価
Vertex AI Gemini API は、プロンプトとレスポンスの両方における有害コンテンツを制御するための安全フィルタリング機能を提供します。詳細については、Vertex AI Safety Filters documentation を参照してください。
安全設定の構成
安全性設定を構成することで、さまざまな危害カテゴリに応じてコンテンツをブロックするしきい値を制御できます。利用可能な危害カテゴリは次のとおりです。
HARM_CATEGORY_HATE_SPEECH- ヘイトスピーチコンテンツHARM_CATEGORY_DANGEROUS_CONTENT- 危険なコンテンツHARM_CATEGORY_HARASSMENT- 嫌がらせコンテンツHARM_CATEGORY_SEXUALLY_EXPLICIT- 性的に露骨な内容HARM_CATEGORY_CIVIC_INTEGRITY- 公民権に関するコンテンツ
The available threshold levels are:
BLOCK_LOW_AND_ABOVE- Block when low, medium, or high probability of unsafe contentBLOCK_MEDIUM_AND_ABOVE- Block when medium or high probability of unsafe contentBLOCK_ONLY_HIGH- Block only when high probability of unsafe contentBLOCK_NONE- Never block (use with caution)
List<VertexAiGeminiSafetySetting> safetySettings = List.of(
VertexAiGeminiSafetySetting.builder()
.withCategory(VertexAiGeminiSafetySetting.HarmCategory.HARM_CATEGORY_HARASSMENT)
.withThreshold(VertexAiGeminiSafetySetting.HarmBlockThreshold.BLOCK_LOW_AND_ABOVE)
.build(),
VertexAiGeminiSafetySetting.builder()
.withCategory(VertexAiGeminiSafetySetting.HarmCategory.HARM_CATEGORY_HATE_SPEECH)
.withThreshold(VertexAiGeminiSafetySetting.HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE)
.build());
ChatResponse response = chatModel.call(new Prompt("Your prompt here",
VertexAiGeminiChatOptions.builder()
.safetySettings(safetySettings)
.build()));Accessing Safety Ratings in Responses
When safety settings are configured, the Gemini API returns safety ratings for each response candidate. These ratings indicate the probability and severity of harmful content in each category.
Safety ratings are available in the AssistantMessage metadata under the key "safetyRatings":
ChatResponse response = chatModel.call(new Prompt(prompt,
VertexAiGeminiChatOptions.builder()
.safetySettings(safetySettings)
.build()));
// Access safety ratings from the response
List<VertexAiGeminiSafetyRating> safetyRatings =
(List<VertexAiGeminiSafetyRating>) response.getResult()
.getOutput()
.getMetadata()
.get("safetyRatings");
for (VertexAiGeminiSafetyRating rating : safetyRatings) {
System.out.println("Category: " + rating.category());
System.out.println("Probability: " + rating.probability());
System.out.println("Severity: " + rating.severity());
System.out.println("Blocked: " + rating.blocked());
}The VertexAiGeminiSafetyRating record contains:
category- The harm category (例:HARM_CATEGORY_HARASSMENT)probability- The probability level (NEGLIGIBLE、LOW、MEDIUM、HIGH)blocked- Whether the content was blocked due to this ratingprobabilityScore- The raw probability score (0.0 1.0 へ)severity- The severity level (HARM_SEVERITY_NEGLIGIBLE、HARM_SEVERITY_LOW、HARM_SEVERITY_MEDIUM、HARM_SEVERITY_HIGH)severityScore- The raw severity score (0.0 1.0 へ)
サンプルコントローラー
新しい 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.5project-id を Google クラウドプロジェクト ID に置き換え、location は us-central1、europe-west1 などの Google クラウドリージョンに置き換えます。 |
各モデルには独自のサポート対象リージョンのセットがあり、サポート対象リージョンのリストはモデルページで確認できます。 例: model= |
これにより、クラスに挿入できる 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 [GitHub] (英語) は 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 は流れるようなオプションビルダーです。
