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
- 缓存内容支持
- 思考模型(Gemini 3.0+)
- 多模态(音频、视频、PDF)
- Token 计数估算器
- 模型目录
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 以及你的 project ID 和 location 进行认证。如果可用,集成将自动使用 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 允许逐 token 流式传输响应文本。
响应必须由 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 schema(ResponseFormat.jsonSchema())直接映射到官方 Google Gen AI SDK 的 ResponseSchema。这允许原生提取强类型 Java record!
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 schema 功能(如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());
注意:显式上下文缓存需要付费层;在免费层上不可用。
思考模型(Gemini 3.0+)
Gemini 3.0 模型(如 gemini-3.0-pro 和 gemini-3.0-flash)支持高级推理(思考)功能。
你可以通过在模型配置期间指定 thinkingLevel 来启用此功能。支持的值为 "MINIMAL"、"LOW"、"MEDIUM" 和 "HIGH":
ChatModel gemini = GoogleGenAiChatModel.builder()
.apiKey(System.getenv("GOOGLE_AI_GEMINI_API_KEY"))
.modelName("gemini-3.0-pro")
.thinkingLevel("MEDIUM")
.build();
[!NOTE] 以前,思考是使用基于 token 的
thinkingBudget配置的。thinkingBudget参数现在被视为遗留参数,但仍受支持。你不能同时指定thinkingLevel和thinkingBudget。
[!TIP] LangChain4j
google-genai集成无缝管理带有思考模型的多轮工具执行所需的复杂状态。它自动在对话轮次之间持久化和注入必要的隐藏thought_signaturetoken,确保稳健且不间断的智能体工作流!
GoogleGenAiEmbeddingModel
GoogleGenAiEmbeddingModel 允许你使用 gemini-embedding-2 等模型为文本片段生成嵌入。
EmbeddingModel embeddingModel = GoogleGenAiEmbeddingModel.builder()
.apiKey(System.getenv("GOOGLE_AI_GEMINI_API_KEY"))
.modelName("gemini-embedding-2")
.outputDimensionality(768)
.taskType(GoogleGenAiEmbeddingModel.TaskTypeEnum.RETRIEVAL_DOCUMENT)
.build();
Response<Embedding> response = embeddingModel.embed("Hello world!");
批处理与重试
当嵌入多个文本片段时(通过 embedAll),GoogleGenAiEmbeddingModel 自动管理批处理和 API 请求重试。
EmbeddingModel embeddingModel = GoogleGenAiEmbeddingModel.builder()
.apiKey(System.getenv("GOOGLE_AI_GEMINI_API_KEY"))
.modelName("gemini-embedding-2")
.maxSegmentsPerBatch(100) // Default: 100. Sets maximum segments per batch request.
.maxRetries(3) // Default: 3. Automatically retries failed requests.
.build();
基于标题的分组策略
官方 Google Gen AI Java SDK 的 embedContent API 每个批处理请求仅支持一个公共 title。为了干净地处理此限制并保留文档级关联,GoogleGenAiEmbeddingModel 实现了按标题分组的批处理策略:
- 当
taskType设置为RETRIEVAL_DOCUMENT时,模型按文档标题对文本片段进行分组(使用.titleMetadataKey(...)定义的键从片段的元数据中提取,默认为"title")。 - 共享相同标题的片段被批处理并在单个 API 调用中一起发送。
- 具有不同标题(或无标题)的片段在单独的优化批次中处理。
- 生成的嵌入被无缝重新组装并按原始顺序返回。
这在不丢失文档元数据上下文或单个片段标题的情况下最大化了 API 吞吐量。
GoogleGenAiImageModel
GoogleGenAiImageModel 允许你从文本提示生成图像。它支持宽高比、图像大小和人物生成策略等自定义配置。
ImageModel imageModel = GoogleGenAiImageModel.builder()
.apiKey(System.getenv("GOOGLE_AI_GEMINI_API_KEY"))
.modelName("gemini-3.1-flash-image-preview")
.aspectRatio("16:9")
.build();
Response<Image> response = imageModel.generate("A futuristic city at sunset");
Batch API
Google Gen AI 集成提供对 Batch API 的支持,允许你在后台异步运行操作。支持以下批处理模型:
GoogleGenAiBatchChatModelGoogleGenAiBatchEmbeddingModelGoogleGenAiBatchImageModel
你可以从内联或从 Google Cloud 上上传的文件创建批处理作业。
GoogleGenAiBatchChatModel batchChatModel = GoogleGenAiBatchChatModel.builder()
.apiKey(System.getenv("GOOGLE_AI_GEMINI_API_KEY"))
.modelName("gemini-2.5-flash")
.build();
BatchResponse<ChatResponse> batchResponse = batchChatModel.submit(
"My Batch Job",
List.of(
ChatRequest.builder().messages(UserMessage.from("What is 2+2?")).build(),
ChatRequest.builder().messages(UserMessage.from("What is the capital of France?")).build()
)
);
System.out.println("Batch Job ID: " + batchResponse.batchId());
然后你可以使用 batchChatModel.retrieve(batchResponse.batchId()) 检索作业的状态和结果。
Grounding 元数据
如果你启用 Google Search grounding 或使用 Vertex AI Search 数据存储,Google Gen AI 聊天模型会在 ChatResponse 中直接公开原生的 GroundingMetadata。你可以通过底层原始 GenerateContentResponse 的响应元数据检索它。
ChatModel gemini = GoogleGenAiChatModel.builder()
.apiKey(System.getenv("GOOGLE_AI_GEMINI_API_KEY"))
.modelName("gemini-2.5-flash")
.enableGoogleSearch(true)
.build();
ChatResponse response = gemini.chat(ChatRequest.builder()
.messages(UserMessage.from("Who won the super bowl in 2024?"))
.build());
GoogleGenAiChatResponseMetadata metadata =
(GoogleGenAiChatResponseMetadata) response.metadata();
if (metadata.rawResponse() != null
&& metadata.rawResponse().candidates() != null
&& !metadata.rawResponse().candidates().isEmpty()) {
var groundingMetadata = metadata.rawResponse().candidates().get(0).groundingMetadata();
if (groundingMetadata != null && groundingMetadata.webSearchQueries() != null) {
System.out.println("Search Queries: " + groundingMetadata.webSearchQueries());
}
}
自定义标签
你可以将自定义键值标签应用于 Google Gen AI 请求,这对计费、指标和跟踪目的很有用。自定义标签受以下支持:
GoogleGenAiChatModelGoogleGenAiStreamingChatModelGoogleGenAiBatchChatModelGoogleGenAiImageModelGoogleGenAiBatchImageModel
ChatModel gemini = GoogleGenAiChatModel.builder()
.apiKey(System.getenv("GOOGLE_AI_GEMINI_API_KEY"))
.modelName("gemini-2.5-flash")
.labels(Map.of("environment", "production", "team", "backend"))
.build();
File API
Google Gen AI 集成提供 GoogleGenAiFiles 实用程序,用于在 Google 服务器上上传和管理文件。这对于传递可能超过标准请求限制的大型多模态输入(如长视频、音频文件或大量 PDF)特别有用。
GoogleGenAiFiles fileApi = GoogleGenAiFiles.builder()
.apiKey(System.getenv("GOOGLE_AI_GEMINI_API_KEY"))
.build();
String uploadedFileUri = fileApi.uploadFile(
Paths.get("path/to/my-video.mp4"),
"video/mp4",
"My Video Demo"
);
// You can now use this URI in your chat requests
ChatModel gemini = GoogleGenAiChatModel.builder()
.apiKey(System.getenv("GOOGLE_AI_GEMINI_API_KEY"))
.modelName("gemini-2.5-flash")
.build();
ChatResponse response = gemini.chat(ChatRequest.builder()
.messages(UserMessage.from(
VideoContent.from(uploadedFileUri, "video/mp4"),
TextContent.from("What happens in this video?")
))
.build());
多模态(音频、视频、PDF)
该集成完全支持 LangChain4j 的多模态内容类型。底层的 GoogleGenAiContentMapper 自动将它们转换为适当的 Gemini Part 对象。
ChatModel gemini = GoogleGenAiChatModel.builder()
.apiKey(System.getenv("GOOGLE_AI_GEMINI_API_KEY"))
.modelName("gemini-2.5-flash")
.build();
ChatResponse response = gemini.chat(ChatRequest.builder()
.messages(UserMessage.from(
AudioContent.from("https://example.com/audio.mp3"),
PdfFileContent.from("https://example.com/document.pdf"),
TextContent.from("Summarize the document and the audio recording.")
))
.build());
Token 计数估算器
你可以使用 GoogleGenAiTokenCountEstimator 准确估算提示和消息中的 token 数量,它使用官方 SDK 的计数端点。
TokenCountEstimator estimator = GoogleGenAiTokenCountEstimator.builder()
.apiKey(System.getenv("GOOGLE_AI_GEMINI_API_KEY"))
.modelName("gemini-2.5-flash")
.build();
int tokenCount = estimator.estimateTokenCount("How many tokens is this sentence?");
System.out.println("Tokens: " + tokenCount);
模型目录
你可以使用 GoogleGenAiModelCatalog 以编程方式查询可用 Gemini 模型的列表。这对于动态发现模型功能、上下文窗口和支持的方法很有帮助。
GoogleGenAiModelCatalog catalog = GoogleGenAiModelCatalog.builder()
.apiKey(System.getenv("GOOGLE_AI_GEMINI_API_KEY"))
.build();
List<Model> availableModels = catalog.listModels();
availableModels.forEach(model -> {
System.out.println("Model Name: " + model.name());
System.out.println("Supported Generation Methods: " + model.supportedGenerationMethods());
});