Google Gen AI(実験的)
https://github.com/googleapis/java-genai
[!WARNING]
この統合は現在実験的とマークされています。API と実装は将来のリリースで変更される可能性があります。 新しい公式 Google Gen AI Java SDK(com.google.genai:google-genai)を使用します。
目次
- Maven 依存関係
- API キー
- 利用可能なモデル
- GoogleGenAiChatModel
- GoogleGenAiStreamingChatModel
- GoogleGenAiEmbeddingModel
- GoogleGenAiImageModel
- リクエストとレスポンスのログ
- Batch API
- ツール
- JSON Schema / 構造化出力
- Grounding メタデータ
- カスタムラベル
- File API
- キャッシュコンテンツのサポート
- Thinking モデル(Gemini 3.0+)
- マルチモーダル(オーディオ、ビデオ、PDF)
- トークン数推定器
- モデルカタログ
Maven 依存関係
<dependency>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-google-genai</artifactId>
<version>1.18.1-beta28</version>
</dependency>
認証
API キーまたは Google Cloud Vertex AI 認証情報を使用して Gemini モデルで認証できます。
Gemini Developer API(API キー)
ここで無料の API キーを取得できます: https://ai.google.dev/gemini-api/docs/api-key。
.apiKey(System.getenv("GOOGLE_AI_GEMINI_API_KEY")) を使用してビルダーに提供できます。
Google Cloud Vertex AI
Vertex AI を使用している場合、Google Credentials とプロジェクト ID およびロケーションを使用して認証できます。利用可能な場合、統合は Application Default Credentials(ADC)を自動的に使用します。または 明示的に提供することもできます。
ChatModel gemini = GoogleGenAiChatModel.builder()
// .googleCredentials(...) // Optional: explicitly provide credentials
.projectId("your-google-cloud-project-id")
.location("us-central1")
.modelName("gemini-2.5-flash")
.build();
利用可能なモデル
ドキュメントで利用可能なモデルのリストを確 認してください。
gemini-3.1-pro-previewgemini-3.1-flash-litegemini-3-pro-previewgemini-3-flash-previewgemini-2.5-progemini-2.5-flashgemini-2.5-flash-lite
(-image、-tts、-live などの専用プレビューモデルの完全なリストについては、公式ドキュメントを参照してください。)
GoogleGenAiChatModel
通常の chat(...) メソッドが利用できます。
ChatModel gemini = GoogleGenAiChatModel.builder()
.apiKey(System.getenv("GOOGLE_AI_GEMINI_API_KEY"))
.modelName("gemini-2.5-flash")
.build();
String response = gemini.chat("Hello Gemini!");
および ChatResponse chat(ChatRequest req) メソッド:
ChatModel gemini = GoogleGenAiChatModel.builder()
.apiKey(System.getenv("GOOGLE_AI_GEMINI_API_KEY"))
.modelName("gemini-2.5-flash")
.build();
ChatResponse chatResponse = gemini.chat(ChatRequest.builder()
.messages(UserMessage.from(
"How many R's are there in the word 'strawberry'?"))
.build());
String response = chatResponse.aiMessage().text();
設定
ChatModel gemini = GoogleGenAiChatModel.builder()
.apiKey(System.getenv("GOOGLE_AI_GEMINI_API_KEY"))
// or .googleCredentials(...)
.projectId(...)
.location(...)
.modelName("gemini-2.5-flash")
.temperature(1.0)
.topP(0.95)
.topK(64)
.seed(42)
.maxOutputTokens(8192)
.timeout(Duration.ofSeconds(60))
.maxRetries(2)
.stopSequences(List.of(...))
.safetySettings(List.of(...))
.responseFormat(ResponseFormat.JSON)
.enableGoogleSearch(true)
.enableGoogleMaps(true)
.enableUrlContext(true)
.allowedFunctionNames(List.of("getWeather"))
.thinkingLevel("LOW")
.listeners(...)
.build();
高度: GenerateContentConfig のカスタマイズ
ビルダーメソッドは最も一般的なオプションをカバーしています。基盤となる Google Gen AI Java SDK のオプションのうち、ビルダーメソッドで(まだ)公開されていないものを設定するには、generateContentConfigCustomizer を登録します。これは、この統合が設定を入力した後(生成パラメータ、ツール、システム指示など)、設定が構築される直前に GenerateContentConfig.Builder を受け取るため、リクエストごとのツールとシステム指示を保持しながら、追加オプションを設定したり既存のものを上書きしたりできます。
ChatModel gemini = GoogleGenAiChatModel.builder()
.apiKey(System.getenv("GOOGLE_AI_GEMINI_API_KEY"))
.modelName("gemini-2.5-flash")
.generateContentConfigCustomizer(config -> config.responseLogprobs(true).logprobs(5))
.build();
これは GoogleGenAiStreamingChatModel でも同じように機能します。
リクエストとレスポ ンスのログ
デバッグ、トラブルシューティング、監査の目的で、GoogleGenAiChatModel、GoogleGenAiStreamingChatModel、GoogleGenAiEmbeddingModel、GoogleGenAiImageModel でリクエストとレスポンスのログを有効にできます。
これらのログをキャプチャするには、モデルビルダーで .logRequests(true)、.logResponses(true)(または .logRequestsAndResponses(true) で両方)を設定します。
ChatModel gemini = GoogleGenAiChatModel.builder()
.apiKey(System.getenv("GOOGLE_AI_GEMINI_API_KEY"))
.modelName("gemini-2.5-flash")
.logRequests(true)
.logResponses(true)
// Or: .logRequestsAndResponses(true)
.build();
ログ設定のセットアップ
Google Gen AI 統合モジュール内のすべてのログは、標準の SLF4J ファサードを通じてルーティングされます。実際に出力を表示するには、次を確認してください。
- SLF4J バインディング(実装)が依存関係に存在する。
- ログフレームワークがパッケージ
dev.langchain4j.model.google.genaiに対してINFOレベルでログを出力するよう設定されている。
以下は一般的なログ環境のセットアップパターンです。
1. Logback を使用したセットアップ
プロジェクトに Logback classic 実装を追加します。
Maven
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.5.8</version> <!-- or your preferred version -->
</dependency>
Gradle
implementation 'ch.qos.logback:logback-classic:1.5.8'
次に、src/main/resources/logback.xml ファイルでログレベルを設定します。例:
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<!-- Configure the package specifically for Google Gen AI logging -->
<logger name="dev.langchain4j.model.google.genai" level="INFO" />
<root level="WARN">
<appender-ref ref="STDOUT" />
</root>
</configuration>
2. Spring Boot アプリケーションでのセットアップ
Spring Boot は自動的に SLF4J プロバイダーを提供します。application.properties(または同等の application.yml)でログレベルを設定するだけです。
# Enable logging for Google Gen AI models
logging.level.dev.langchain4j.model.google.genai=INFO
3. SLF4J Simple でのセットアップ
スクリプトまたはシンプルなコマンドラインアプリケーションを作成している場合は、軽量の slf4j-simple バックエンドを使用できます。
Maven
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>2.0.13</version>
</dependency>
アプリケーション起動時にシステムプロパティ経由で SLF4J Simple を設定します。
java -Dorg.slf4j.simpleLogger.log.dev.langchain4j.model.google.genai=INFO -jar app.jar
または、src/main/resources/ に次の内容を含む simplelogger.properties ファイルを作成します。
org.slf4j.simpleLogger.log.dev.langchain4j.model.google.genai=info
GoogleGenAiStreamingChatModel
GoogleGenAiStreamingChatModel を使用すると、レスポンスのテキストをトークンごとにストリーミングできます。
レスポンスは StreamingChatResponseHandler で処理する必要があります。
StreamingChatModel gemini = GoogleGenAiStreamingChatModel.builder()
.apiKey(System.getenv("GOOGLE_AI_GEMINI_API_KEY"))
.modelName("gemini-2.5-flash")
.build();
CompletableFuture<ChatResponse> futureResponse = new CompletableFuture<>();
gemini.chat("Tell me a joke about Java", new StreamingChatResponseHandler() {
@Override
public void onPartialResponse(String partialResponse) {
System.out.print(partialResponse);
}
@Override
public void onCompleteResponse(ChatResponse completeResponse) {
futureResponse.complete(completeResponse);
}
@Override
public void onError(Throwable error) {
futureResponse.completeExceptionally(error);
}
});
futureResponse.join();
Executor
Google Gen AI SDK はストリーミングをブロッキングの ResponseStream イテレータとして公開します。各チャンクはブロッキングの next() 呼び出しによって配信されます。したがって、GoogleGenAiStreamingChatModel は呼び出し元のスレッド外でその反復を駆動するために ExecutorService を必要とします。
渡さない場合、DefaultExecutorProvider の共有デフォルトが使用されます(遅延初期化、利用可能な場合は仮想スレッドを使用)。これはすぐに動作しますが、本番環境では推奨されません。デフォルトのエグゼキュータは無制限で、JVM 全体に及び、アプリケーション のライフサイクルに結び付けられていないため、バックプレッシャー、グレースフルシャットダウン、メトリクスでの可視性を提供しません。
ほぼ常に独自のエグゼキュータを提供すべきです。たとえば、フレームワーク管理のタスクエグゼキュータ(Spring TaskExecutor、Quarkus ManagedExecutor など)、所有する仮想スレッドエグゼキュータ、または同時実行予算に合わせて調整された有界プールです。
ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor(); // or your framework's executor
StreamingChatModel gemini = GoogleGenAiStreamingChatModel.builder()
.apiKey(System.getenv("GOOGLE_AI_GEMINI_API_KEY"))
.modelName("gemini-2.5-flash")
.executor(executor)
.build();
ツール
ツール(関数呼び出し)がサポートされています。LangChain4j の AiServices を使用して定義できます。
class WeatherForecastService {
@Tool("Get the weather forecast for a location")
String getForecast(@P("Location to get the forecast for") String location) {
return "The weather in " + location + " is sunny and 25°C.";
}
}
interface WeatherAssistant {
String chat(String userMessage);
}
WeatherForecastService weatherForecastService = new WeatherForecastService();
ChatModel gemini = GoogleGenAiChatModel.builder()
.apiKey(System.getenv("GOOGLE_AI_GEMINI_API_KEY"))
.modelName("gemini-2.5-flash")
.temperature(0.0)
.build();
WeatherAssistant weatherAssistant = AiServices.builder(WeatherAssistant.class)
.chatModel(gemini)
.tools(weatherForecastService)
.build();
String response = weatherAssistant.chat("What is the weather forecast for Tokyo?");
JSON Schema / 構造化出力
langchain4j-google-genai 統合は、LangChain4j の JSON スキーマ(ResponseFormat.jsonSchema())を公式 Google Gen AI SDK の ResponseSchema に直接マップします。これにより、強く型付けされた Java レコードをネイティブに抽出できます!
record WeatherForecast(
@Description("minimum temperature") Integer minTemperature,
@Description("maximum temperature") Integer maxTemperature,
@Description("chances of rain") boolean rain
) { }
interface WeatherForecastAssistant {
WeatherForecast extract(String forecast);
}
ChatModel gemini = GoogleGenAiChatModel.builder()
.apiKey(System.getenv("GOOGLE_AI_GEMINI_API_KEY"))
.modelName("gemini-2.5-flash")
.build();
WeatherForecastAssistant forecastAssistant = AiServices.builder(WeatherForecastAssistant.class)
.chatModel(gemini)
.build();
WeatherForecast forecast = forecastAssistant.extract("""
Morning: The day dawns bright and clear in Osaka...
Temperatures climb to a comfortable 22°C (72°F) and
will drop to 15°C (59°F).
""");
[!NOTE]
Google Gen AI API には、高度な JSON スキーマ機能(anyOf/ ポリモーフィック型付けなど)にいくつかの制限があります。シンプルな POJO、リスト、ネストされたオブジェクトは完全にサポートされています。
キャッシュコンテンツのサポート
複数のリクエストにわたって再利用される非常に大きなコンテキストウィンドウ(大規模なシステムプロンプト、大きなドキュメント、または広範なコードベースなど)を扱う場合、コンテンツをキャッシュすることでコストとレイテンシを大幅に削減できます。
公式の Google Gen AI SDK または API を使用してキャッシュコンテンツを作成したら、一意のキャッシュ識別子を LangChain4j チャットモデルビルダーに簡単に渡すことができます。
// Pass your cached content URI here
String cachedContentUri = "projects/123456/locations/us-central1/cachedContents/my-cached-content-789";
ChatModel gemini = GoogleGenAiChatModel.builder()
.apiKey(System.getenv("GOOGLE_AI_GEMINI_API_KEY"))
.modelName("gemini-2.5-pro")
.cachedContent(cachedContentUri)
.build();
// The model will automatically use the cached context!
String response = gemini.chat("Summarize the cached document in 3 bullet points.");
この機能は GoogleGenAiChatModel、GoogleGenAiStreamingChatModel、GoogleGenAiBatchChatModel で利用できます。
キャッシュの作成と管理
帯域外でキャッシュを作成する代わりに、GoogleGenAiCaches を使用して LangChain4j から直接作成および管理できます。これは SDK のキャッシュライフサイクル(create / get / list / update TTL / delete)をラップします。メッセージはチャットモデルと同じ GoogleGenAiContentMapper を使用してキャッシュされるため、LangChain4j の ChatMessage ドメインに留まります。
GoogleGenAiCaches caches = GoogleGenAiCaches.builder()
.apiKey(System.getenv("GOOGLE_AI_GEMINI_API_KEY"))
.build();
// Cache a large, reusable context (a system instruction plus a long document)
CachedContent cache = caches.createCache(
"gemini-2.5-flash",
List.of(
SystemMessage.from("You are a precise assistant answering questions about the attached document."),
UserMessage.from(longDocumentText)),
Duration.ofHours(1));
// Reuse it across many requests via cachedContent
ChatModel gemini = GoogleGenAiChatModel.builder()
.apiKey(System.getenv("GOOGLE_AI_GEMINI_API_KEY"))
.modelName("gemini-2.5-flash")
.cachedContent(cache.name().orElseThrow())
.build();
String answer = gemini.chat("Summarize the cached document in 3 bullet points.");
// Manage the cache lifecycle
caches.updateCacheTtl(cache.name().orElseThrow(), Duration.ofHours(2));
caches.listCaches();
caches.deleteCache(cache.name().orElseThrow());