Skip to content
LangChain4j 文档版本 1.22.0 源快照 98bb2daa 更新于 2026-10-14

Google Gen AI(实验性)

https://github.com/googleapis/java-genai

WARNING

该集成目前被标记为实验性。其 API 与实现在未来版本中可能变化。 它使用了新的官方 Google Gen AI Java SDK(com.google.genai:google-genai)。

目录

Maven 依赖

xml
<dependency>
    <groupId>dev.langchain4j</groupId>
    <artifactId>langchain4j-google-genai</artifactId>
    <version>1.22.0-beta32</version>
</dependency>

身份认证

你可以用 API 密钥或 Google Cloud Vertex AI 凭据之一对 Gemini 模型进行认证。

Gemini 开发者 API(API 密钥)

在此免费获取 API 密钥:https://ai.google.dev/gemini-api/docs/api-key。 你可以用 .apiKey(System.getenv("GOOGLE_AI_GEMINI_API_KEY")) 把它传给 builder。

Google Cloud Vertex AI

如果你使用 Vertex AI,可以用 Google 凭据连同你的项目 ID 与位置进行认证。若可用,该集成会自动使用应用默认凭据(ADC),或你可以显式提供它们:

java
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-preview
  • gemini-3.1-flash-lite
  • gemini-3-pro-preview
  • gemini-3-flash-preview
  • gemini-2.5-pro
  • gemini-2.5-flash
  • gemini-2.5-flash-lite

(关于像 -image、-tts 与 -live 这样专门的预览模型的完整列表,见官方文档)。

GoogleGenAiChatModel

常用的 chat(...) 方法均可用:

java
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) 方法:

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

配置

java
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

builder 方法覆盖了最常见的选项。要设置某个(尚)未被 builder 方法暴露的底层 Google Gen AI Java SDK 选项,请注册一个 generateContentConfigCustomizer。它在本集成填充完 GenerateContentConfig.Builder 之后(生成参数、工具、系统指令等)、即将构建配置之前接收它,从而能在保留逐次请求工具与系统指令的同时,设置额外选项或覆盖已有选项。

java
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 启用请求与响应日志,用于调试、排障与审计。

要捕获这些日志,请在你的模型 builder 中配置 .logRequests(true)、.logResponses(true)(或用 .logRequestsAndResponses(true) 同时开启)。

java
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 门面路由。要实际查看输出,你必须确保:

  1. 你的依赖中存在一个 SLF4J 绑定(实现)。
  2. 日志框架被配置为对包 dev.langchain4j.model.google.genai 输出 INFO 级别以下的日志。

下面是一些针对流行日志环境的常见搭建模式:

1. 使用 Logback 搭建

把 Logback classic 实现添加到你的项目:

Maven
xml
<dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-classic</artifactId>
    <version>1.5.8</version> <!-- or your preferred version -->
</dependency>
Gradle
groovy
implementation 'ch.qos.logback:logback-classic:1.5.8'

然后,在你的 src/main/resources/logback.xml 文件中配置日志级别。例如:

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)中配置日志级别:

properties
# Enable logging for Google Gen AI models
logging.level.dev.langchain4j.model.google.genai=INFO

3. 使用 SLF4J Simple 搭建

如果你在写一个脚本或简单的命令行应用,可以使用轻量的 slf4j-simple 后端:

Maven
xml
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-simple</artifactId>
    <version>2.0.13</version>
</dependency>

在启动应用时通过一个系统属性配置 SLF4J Simple:

bash
java -Dorg.slf4j.simpleLogger.log.dev.langchain4j.model.google.genai=INFO -jar app.jar

或者,在 src/main/resources/ 下创建一个 simplelogger.properties 文件,内容为:

properties
org.slf4j.simpleLogger.log.dev.langchain4j.model.google.genai=info

GoogleGenAiStreamingChatModel

GoogleGenAiStreamingChatModel 允许逐词元流式输出响应的文本。

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

执行器

Google Gen AI SDK 把流式作为一个阻塞式的 ResponseStream 迭代器暴露:每个块都由一个阻塞的 next() 调用投递。因此 GoogleGenAiStreamingChatModel 需要一个 ExecutorService 来在调用线程之外驱动该迭代。

如果你不传入一个,会使用来自 DefaultExecutorProvider 的一个共享默认值(惰性初始化,在可用时使用虚拟线程)。这开箱即用,但不推荐用于生产:默认执行器是无界的、JVM 范围的,且不绑定到你的应用生命周期——因此它没有背压、没有优雅停机,在你的指标里也没有可见性。

你几乎总应当提供你自己的执行器——例如你框架托管的任务执行器(Spring TaskExecutor、Quarkus ManagedExecutor……)、一个你拥有的虚拟线程执行器,或一个按你的并发预算调优的有界线程池:

java
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 定义它们:

java
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!

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 schema 特性(例如 anyOf / 多态类型)有所限制。简单的 POJO、列表与嵌套对象则完全支持。

缓存内容支持

当处理非常大的上下文窗口(如海量系统提示词、大型文档或庞大代码库)且它们会在多个请求间被复用时,你可以通过缓存内容显著降低成本与延迟。

一旦你用官方 Google Gen AI SDK 或 API 创建了缓存内容,就可以轻松地把这个唯一缓存标识符传给 LangChain4j 聊天模型 builder:

java
// 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 领域内。

java
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":

java
ChatModel gemini = GoogleGenAiChatModel.builder()
    .apiKey(System.getenv("GOOGLE_AI_GEMINI_API_KEY"))
    .modelName("gemini-3.0-pro")
    .thinkingLevel("MEDIUM")
    .build();

NOTE

此前,思考用一个基于词元数的 thinkingBudget 配置。thinkingBudget 参数现被视为遗留,但仍受支持。你不能同时指定 thinkingLevel 与 thinkingBudget。

TIP

LangChain4j 的 google-genai 集成会无缝管理思考模型多轮工具执行所需的复杂状态。它会自动跨对话轮次持久化并注入必要的隐藏 thought_signature 词元,确保健壮而不间断的智能体工作流!

思考摘要

设置 includeThoughts(true) 以要求模型在答案之外返回思考摘要,并设置 returnThinking(true) 以把它们映射到 AiMessage.thinking():

java
ChatModel gemini = GoogleGenAiChatModel.builder()
    .apiKey(System.getenv("GOOGLE_AI_GEMINI_API_KEY"))
    .modelName("gemini-3.1-pro-preview")
    .thinkingLevel("MEDIUM")
    .includeThoughts(true)
    .returnThinking(true)
    .build();

ChatResponse response = gemini.chat(UserMessage.from("What is 6 times 7?"));

String thinking = response.aiMessage().thinking();
String answer = response.aiMessage().text();

流式时,思考摘要通过 StreamingChatResponseHandler.onPartialThinking() 投递,而答案继续通过 onPartialResponse() 到达。

要在后续请求中把思考摘要回送给模型,请设置 sendThinking(true)。多轮工具执行所需的 thought_signature 词元被独立处理,且无论此设置如何都会被始终保留。

NOTE

returnThinking 默认禁用。那样模型返回的思考摘要会被丢弃,从不出现在 AiMessage.text() 中。

词元用量

响应携带一个 GoogleGenAiTokenUsage,它在标准的输入、输出与总数之外,附加了 Gemini 报告的用于思考、缓存内容与工具使用的词元数:

java
GoogleGenAiTokenUsage tokenUsage = (GoogleGenAiTokenUsage) response.metadata().tokenUsage();

Integer thoughtsTokenCount = tokenUsage.thoughtsTokenCount();
Integer cachedContentTokenCount = tokenUsage.cachedContentTokenCount();
Integer toolUsePromptTokenCount = tokenUsage.toolUsePromptTokenCount();

当模型未上报时,每个都为 null。cachedContentTokenCount 是 inputTokenCount() 的一个子集,而 toolUsePromptTokenCount 与 thoughtsTokenCount 则在其之上另行计数:Gemini 把总数定义为 inputTokenCount + outputTokenCount + toolUsePromptTokenCount + thoughtsTokenCount。

GoogleGenAiEmbeddingModel

GoogleGenAiEmbeddingModel 让你能使用像 gemini-embedding-2 这样的模型为文本片段生成嵌入。

java
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 请求重试。

java
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 实现了一种按标题分组的批处理策略:

  1. 当 taskType 设为 RETRIEVAL_DOCUMENT 时,模型按文档标题对文本片段分组(标题从片段元数据中用 .titleMetadataKey(...) 定义的键提取,默认为 "title")。
  2. 共享同一标题的片段被合批,在一次 API 调用中一起发送。
  3. 标题不同(或无标题)的片段在分开的、经过优化的批次中处理。
  4. 所得嵌入会被无缝重组并按原始顺序返回。

这在最大化 API 吞吐的同时,不丢失文档元数据上下文或各个片段的标题。

GoogleGenAiImageModel

GoogleGenAiImageModel 让你能从文本提示词生成图像。它支持诸如宽高比、图像尺寸与人物生成策略之类的自定义配置。

java
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");

批处理 API

Google Gen AI 集成为 Batch API 提供支持,让你能在后台异步运行操作。支持以下批处理模型:

  • GoogleGenAiBatchChatModel
  • GoogleGenAiBatchEmbeddingModel
  • GoogleGenAiBatchImageModel

你可以内联创建批任务,或从 Google Cloud 上一个上传的文件创建。

java
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()) 获取该任务的状态与结果。

接地元数据

如果你启用 Google 搜索接地或使用一个 Vertex AI Search 数据存储,Google Gen AI 聊天模型会把原生 GroundingMetadata 直接暴露在 ChatResponse 中。你可以经由底层原始 GenerateContentResponse 的响应元数据来取回它。

java
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 请求应用自定义的键值标签,这对计费、指标与追踪很有用。自定义标签由以下支持:

  • GoogleGenAiChatModel
  • GoogleGenAiStreamingChatModel
  • GoogleGenAiBatchChatModel
  • GoogleGenAiImageModel
  • GoogleGenAiBatchImageModel
  • GoogleGenAiModerationModel
java
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();

文件 API

Google Gen AI 集成提供了 GoogleGenAiFiles 工具,用于在 Google 服务器上上传与管理文件。这在传入可能超出标准请求限制的大型多模态输入(如很长的视频、音频文件或大量 PDF)时尤其有用。

java
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 对象。

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

音频转写

为语音识别构建的模型(如 gemini-3.5-transcribe)会把音频转为文本。把音频作为 AudioContent 发送;无需文本指令。转录文本会作为 AiMessage 的文本返回。

用 audioTranscriptionConfig 控制音频如何被转写:

java
ChatModel transcriber = GoogleGenAiChatModel.builder()
    .apiKey(System.getenv("GOOGLE_AI_GEMINI_API_KEY"))
    .modelName("gemini-3.5-transcribe")
    .audioTranscriptionConfig(AudioTranscriptionConfig.builder()
        .mode(AudioTranscriptionConfigMode.Known.VERBATIM)
        .languageCodes("en-US")
        .customVocabulary("LangChain4j", "Gemini")
        .wordTimestamp(true)
        .diarization(true)
        .build())
    .build();

ChatResponse response = transcriber.chat(ChatRequest.builder()
    .messages(UserMessage.from(AudioContent.from("https://example.com/meeting.mp3")))
    .build());

String transcript = response.aiMessage().text();
  • mode:VERBATIM(默认)保留每个词,包括填充词、重复与口误起始。SMART 会去除它们并做轻量格式化。词级时间戳与说话人分离不能与 SMART 一同使用。
  • languageCodes:音频中所讲语言的 BCP-47 代码。省略时会自动检测语言。
  • customVocabulary:模型应当识别的词与短语,例如产品名或人名。
  • wordTimestamp:返回每个词的起止偏移。
  • diarization:标注哪位说话人说了什么。

词级时间戳与说话人标签并非 AiMessage 文本的一部分。请从原始响应中读取它们:

java
GoogleGenAiChatResponseMetadata metadata = (GoogleGenAiChatResponseMetadata) response.metadata();

for (Part part : metadata.rawResponse().parts()) {
    part.audioTranscription().ifPresent(transcription -> {
        String speaker = transcription.speakerLabel().orElse("");
        for (WordInfo word : transcription.words().orElse(List.of())) {
            System.out.printf("[%s] %s - %s %s%n",
                speaker, word.startOffset().orElse(""), word.endOffset().orElse(""), word.word().orElse(""));
        }
    });
}

GoogleGenAiStreamingChatModel 接受同样的 audioTranscriptionConfig,但它的原始响应只持有最后一个流式块,因此当你需要词级时间戳或说话人标签时,请使用 GoogleGenAiChatModel。

图像生成输出

一些 Gemini 模型(如 gemini-2.5-flash-image)会在聊天响应的文本之外返回生成的图像。它们以 inlineData 块到达,而 GoogleGenAiChatModel 会把它们映射进 AiMessage 属性下的 GENERATED_IMAGES_KEY,即 AiMessage.images() 所读取的键:

java
ChatModel model = GoogleGenAiChatModel.builder()
    .apiKey(System.getenv("GOOGLE_AI_GEMINI_API_KEY"))
    .modelName("gemini-2.5-flash-image")
    .build();

ChatResponse response = model.chat(UserMessage.from("A watercolor sketch of a lighthouse at dusk"));

for (Image image : response.aiMessage().images()) {
    System.out.println("Generated image: " + image.mimeType());

    // Save it, display it, or hand it to another model
    Files.write(Paths.get("generated_image.png"), Base64.getDecoder().decode(image.base64Data()));
}

只有 image/* 的块会成为生成图像;任何其他类型的内联数据都会被忽略。

流式响应的工作方式相同。GoogleGenAiStreamingChatModel 一次接收一个块的响应,且每个块都会把它的图像贡献给最终消息,因此一个单独成块到达的图像不会丢失。

langchain4j-google-ai-gemini 用同一个键存储生成图像,因此同一套读取代码对两个模块都适用。

词元数估算器

你可以用 GoogleGenAiTokenCountEstimator 准确估算提示词与消息中的词元数,它使用官方 SDK 的计数端点。

java
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 模型列表。这对动态发现模型能力、上下文窗口与受支持的方法很有帮助。

java
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());
});

BytesRouter 是社区翻译站点,所有译文仅供参考,一切以官方英文原文为准。