Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
142 changes: 100 additions & 42 deletions core/src/main/java/com/google/adk/models/Gemini.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
import com.google.genai.types.GenerateContentConfig;
import com.google.genai.types.GenerateContentResponse;
import com.google.genai.types.HttpOptions;
import com.google.genai.types.HttpRetryOptions;
import com.google.genai.types.LiveConnectConfig;
import io.reactivex.rxjava3.core.Flowable;
import io.reactivex.rxjava3.schedulers.Schedulers;
Expand Down Expand Up @@ -99,34 +100,47 @@ private static OkHttpClient prepareHttpClient(@Nullable ExecutorService executor
}

// Every client ADK builds starts here, so each sends ADK's tracking tag.
private static Client.Builder adkClientBuilder(@Nullable ExecutorService executorService) {
private static Client.Builder adkClientBuilder(
@Nullable ExecutorService executorService, @Nullable HttpRetryOptions retryOptions) {
return Client.builder()
.httpOptions(
HttpOptions.builder()
.headers(
TrackingHeaders.genAiSdkHeaders(
TrackingHeaders.adkGenAiClientTargetsGoogleApis(System::getenv)))
.build())
.httpOptions(buildHttpOptions(retryOptions))
.clientOptions(
ClientOptions.builder().customHttpClient(prepareHttpClient(executorService)).build());
}

private static Client buildApiKeyClient(
String apiKey, @Nullable ExecutorService executorService) {
return adkClientBuilder(executorService).apiKey(apiKey).build();
String apiKey,
@Nullable ExecutorService executorService,
@Nullable HttpRetryOptions retryOptions) {
return adkClientBuilder(executorService, retryOptions).apiKey(apiKey).build();
}

private static Client buildVertexClient(
VertexCredentials vertexCredentials, @Nullable ExecutorService executorService) {
Client.Builder apiClientBuilder = adkClientBuilder(executorService);
VertexCredentials vertexCredentials,
@Nullable ExecutorService executorService,
@Nullable HttpRetryOptions retryOptions) {
Client.Builder apiClientBuilder = adkClientBuilder(executorService, retryOptions);
vertexCredentials.project().ifPresent(apiClientBuilder::project);
vertexCredentials.location().ifPresent(apiClientBuilder::location);
vertexCredentials.credentials().ifPresent(apiClientBuilder::credentials);
return apiClientBuilder.build();
}

private static Client buildDefaultClient(@Nullable ExecutorService executorService) {
return adkClientBuilder(executorService).build();
private static Client buildDefaultClient(
@Nullable ExecutorService executorService, @Nullable HttpRetryOptions retryOptions) {
return adkClientBuilder(executorService, retryOptions).build();
}

private static HttpOptions buildHttpOptions(@Nullable HttpRetryOptions retryOptions) {
HttpOptions.Builder httpOptionsBuilder =
HttpOptions.builder()
.headers(
TrackingHeaders.genAiSdkHeaders(
TrackingHeaders.adkGenAiClientTargetsGoogleApis(System::getenv)));
if (retryOptions != null) {
httpOptionsBuilder.retryOptions(retryOptions);
}
return httpOptionsBuilder.build();
}

private final Client apiClient;
Expand All @@ -135,6 +149,26 @@ private static Client buildDefaultClient(@Nullable ExecutorService executorServi
// The API version requested on calls that set none, or null to keep apiClient's own.
private final @Nullable String requestApiVersion;

private Gemini(Builder builder) {
super(builder.modelName);
if (builder.apiClient != null) {
this.apiClient = builder.apiClient;
} else if (builder.apiKey != null) {
this.apiClient =
buildApiKeyClient(builder.apiKey, builder.httpExecutorService, builder.retryOptions);
} else if (builder.vertexCredentials != null) {
this.apiClient =
buildVertexClient(
builder.vertexCredentials, builder.httpExecutorService, builder.retryOptions);
} else {
this.apiClient = buildDefaultClient(builder.httpExecutorService, builder.retryOptions);
}
this.clientSendsTrackingHeaders =
builder.apiClient == null || builder.clientSendsTrackingHeaders;
this.requestApiVersion =
!apiClient.vertexAI() && apiClient.isDefaultApiVersion() ? GEMINI_API_VERSION : null;
}

/**
* Constructs a new Gemini instance. Each generate request sent through {@code apiClient} carries
* ADK's tracking tag, which the genai SDK appends to the client's tracking headers. On Agent
Expand All @@ -147,15 +181,18 @@ private static Client buildDefaultClient(@Nullable ExecutorService executorServi
* @param apiClient The genai {@link com.google.genai.Client} instance for making API calls.
*/
public Gemini(String modelName, Client apiClient) {
this(modelName, apiClient, /* clientSendsTrackingHeaders= */ false);
this(
builder()
.modelName(modelName)
.apiClient(Objects.requireNonNull(apiClient, "apiClient cannot be null")));
}

Gemini(String modelName, Client apiClient, boolean clientSendsTrackingHeaders) {
super(modelName);
this.apiClient = Objects.requireNonNull(apiClient, "apiClient cannot be null");
this.clientSendsTrackingHeaders = clientSendsTrackingHeaders;
this.requestApiVersion =
!apiClient.vertexAI() && apiClient.isDefaultApiVersion() ? GEMINI_API_VERSION : null;
this(
builder()
.modelName(modelName)
.apiClient(Objects.requireNonNull(apiClient, "apiClient cannot be null"))
.clientSendsTrackingHeaders(clientSendsTrackingHeaders));
}

/**
Expand All @@ -166,29 +203,28 @@ public Gemini(String modelName, Client apiClient) {
*/
public Gemini(String modelName, String apiKey) {
this(
modelName,
buildApiKeyClient(Objects.requireNonNull(apiKey, "apiKey cannot be null"), null),
/* clientSendsTrackingHeaders= */ true);
builder()
.modelName(modelName)
.apiKey(Objects.requireNonNull(apiKey, "apiKey cannot be null")));
}

/**
* Constructs a new Gemini instance with a Google Gemini API key.
* Constructs a new Gemini instance with Vertex AI credentials.
*
* @param modelName The name of the Gemini model to use (e.g., "gemini-2.0-flash").
* @param vertexCredentials The Vertex AI credentials to access the Gemini model.
*/
public Gemini(String modelName, VertexCredentials vertexCredentials) {
this(
modelName,
buildVertexClient(
Objects.requireNonNull(vertexCredentials, "vertexCredentials cannot be null"), null),
/* clientSendsTrackingHeaders= */ true);
builder()
.modelName(modelName)
.vertexCredentials(
Objects.requireNonNull(vertexCredentials, "vertexCredentials cannot be null")));
}

/**
* Returns a new Builder instance for constructing Gemini objects. Note that when building a
* Gemini object, at least one of apiKey, vertexCredentials, or an explicit apiClient must be set.
* If multiple are set, the explicit apiClient will take precedence.
* Returns a builder for configuring Gemini. An explicit client takes precedence over an API key
* or Vertex credentials. If none are supplied, the client uses its default configuration.
*
* @return A new {@link Builder}.
*/
Expand All @@ -203,9 +239,16 @@ public static class Builder {
private String apiKey;
private VertexCredentials vertexCredentials;
private ExecutorService httpExecutorService;
private @Nullable HttpRetryOptions retryOptions;
private boolean clientSendsTrackingHeaders;

private Builder() {}

private Builder clientSendsTrackingHeaders(boolean clientSendsTrackingHeaders) {
this.clientSendsTrackingHeaders = clientSendsTrackingHeaders;
return this;
}

/**
* Sets the name of the Gemini model to use.
*
Expand Down Expand Up @@ -274,27 +317,42 @@ public Builder httpExecutorService(ExecutorService httpExecutorService) {
return this;
}

/**
* Sets options for retrying transient HTTP failures through the Gemini client.
*
* <p>By default, the Java Gen AI SDK makes up to five attempts with exponential backoff for
* HTTP status codes 408, 429, 500, 502, 503, and 504. To disable retries, pass {@code
* HttpRetryOptions.builder().attempts(1).build()}.
*
* <p>When supplying a client via {@link #apiClient(Client)}, configure retries in that client's
* {@link HttpOptions}. Setting both options causes {@link #build()} to throw an {@link
* IllegalStateException}.
*
* @param retryOptions The retry options to pass to the Google Gen AI client, or {@code null} to
* use the SDK defaults.
* @return This builder.
*/
Comment on lines +321 to +334

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you document what happens when this is not set? The Gen AI SDK applies its default retry policy (5 attempts on 408, 429, 500, 502, 503, and 504 with exponential backoff), and HttpRetryOptions.builder().attempts(1).build() disables retries. Python's SDK makes a single attempt when no retry options are given, so Java users can't assume the same default.

Also, since the parameter accepts null, please annotate it with @Nullable (org.jspecify.annotations.Nullable) or reject null.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Documented the Java Gen AI SDK defaults: up to five total attempts with exponential backoff for HTTP 408, 429, 500, 502, 503, and 504, and attempts(1) disables retries. I also added org.jspecify.annotations.Nullable to the parameter and documented that null uses the SDK defaults.

@CanIgnoreReturnValue
public Builder retryOptions(@Nullable HttpRetryOptions retryOptions) {
this.retryOptions = retryOptions;
return this;
}

/**
* Builds the {@link Gemini} instance.
*
* @return A new {@link Gemini} instance.
* @throws NullPointerException if modelName is null.
* @throws IllegalStateException if both apiClient and retryOptions are set.
*/
public Gemini build() {
Objects.requireNonNull(modelName, "modelName must be set.");

if (apiClient != null) {
return new Gemini(modelName, apiClient);
}
Client client;
if (apiKey != null) {
client = buildApiKeyClient(apiKey, httpExecutorService);
} else if (vertexCredentials != null) {
client = buildVertexClient(vertexCredentials, httpExecutorService);
} else {
client = buildDefaultClient(httpExecutorService);
if (apiClient != null && retryOptions != null) {
throw new IllegalStateException(
"retryOptions cannot be combined with apiClient; "
+ "set retry options in the Client's HttpOptions instead.");
}
return new Gemini(modelName, client, /* clientSendsTrackingHeaders= */ true);
return new Gemini(this);
}
}

Expand Down
155 changes: 155 additions & 0 deletions core/src/test/java/com/google/adk/models/GeminiBuilderTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
/*
* Copyright 2026 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.adk.models;

import static com.google.adk.models.LocalModelServer.GENERATE_CONTENT_JSON;
import static com.google.common.truth.Truth.assertThat;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.assertThrows;

import com.google.common.collect.ImmutableList;
import com.google.common.net.InetAddresses;
import com.google.genai.Client;
import com.google.genai.errors.ApiException;
import com.google.genai.types.Content;
import com.google.genai.types.HttpRetryOptions;
import com.google.genai.types.Part;
import com.sun.net.httpserver.HttpServer;
import io.reactivex.rxjava3.schedulers.Schedulers;
import io.reactivex.rxjava3.subscribers.TestSubscriber;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** Tests Gemini builder validation and retry behavior against a local HTTP endpoint. */
@RunWith(JUnit4.class)
public final class GeminiBuilderTest {

private static final String MODEL = "gemini-test-model";
private static final String UNAVAILABLE_JSON =
"{\"error\":{\"code\":503,\"message\":\"Temporarily"
+ " unavailable\",\"status\":\"UNAVAILABLE\"}}";

@Test
public void generateContent_withRetries_retriesServiceUnavailable() throws IOException {
generateWithRetryOptions(3, 2).assertComplete().assertNoErrors().assertValueCount(1);
}

@Test
public void generateContent_withOneAttempt_propagatesServiceUnavailable() throws IOException {
generateWithRetryOptions(1, 1)
.assertError(
error -> {
Throwable cause = error instanceof ExecutionException ? error.getCause() : error;
return cause instanceof ApiException apiError && apiError.code() == 503;
})
.assertNoValues();
}

@Test
public void builder_withExplicitClientAndRetryOptions_rejectsConflictingOptions() {
try (Client client = Client.builder().vertexAI(false).apiKey("test-api-key").build()) {
Gemini.Builder builder =
Gemini.builder()
.modelName(MODEL)
.apiClient(client)
.retryOptions(HttpRetryOptions.builder().attempts(1).build());

IllegalStateException exception = assertThrows(IllegalStateException.class, builder::build);

assertThat(exception)
.hasMessageThat()
.contains("set retry options in the Client's HttpOptions instead.");
assertThat(builder.retryOptions(null).build().model()).isEqualTo(MODEL);
}
}

@Test
public void constructors_withNullArguments_rejectInsteadOfUsingDefaultClient() {
assertThrows(NullPointerException.class, () -> new Gemini(MODEL, (Client) null));
assertThrows(NullPointerException.class, () -> new Gemini(MODEL, (String) null));
assertThrows(NullPointerException.class, () -> new Gemini(MODEL, (VertexCredentials) null));
}

@Test
public void builder_withoutModelName_rejectsMissingModelName() {
assertThrows(NullPointerException.class, () -> Gemini.builder().apiKey("test-api-key").build());
}

private static TestSubscriber<LlmResponse> generateWithRetryOptions(
int attempts, int expectedRequests) throws IOException {
AtomicInteger receivedRequests = new AtomicInteger();
HttpServer server =
HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0);
server.createContext(
"/",
exchange -> {
try (exchange) {
exchange.getRequestBody().readAllBytes();
boolean firstRequest = receivedRequests.incrementAndGet() == 1;
byte[] body = (firstRequest ? UNAVAILABLE_JSON : GENERATE_CONTENT_JSON).getBytes(UTF_8);
exchange.getResponseHeaders().set("Content-Type", "application/json");
exchange.sendResponseHeaders(firstRequest ? 503 : 200, body.length);
exchange.getResponseBody().write(body);
}
});
server.start();
Optional<String> baseUrl =
Optional.of(
"http://"
+ InetAddresses.toUriString(server.getAddress().getAddress())
+ ":"
+ server.getAddress().getPort());
Client.setDefaultBaseUrls(baseUrl, baseUrl);
try {
Gemini gemini =
Gemini.builder()
.modelName(MODEL)
.apiKey("test-api-key")
.retryOptions(
HttpRetryOptions.builder()
.attempts(attempts)
.initialDelay(0.01)
.jitter(0.0)
.build())
.build();
LlmRequest request =
LlmRequest.builder()
.contents(
ImmutableList.of(
Content.builder().role("user").parts(Part.fromText("hello")).build()))
.build();
TestSubscriber<LlmResponse> response =
gemini
.generateContent(request, /* stream= */ false)
.subscribeOn(Schedulers.io())
.test()
.awaitDone(10, TimeUnit.SECONDS);
assertThat(receivedRequests.get()).isEqualTo(expectedRequests);
return response;
} finally {
Client.setDefaultBaseUrls(Optional.empty(), Optional.empty());
server.stop(0);
}
}
}