Repository navigation
feat(core): expose Gemini retry options #1413
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
014-code
wants to merge
1
commit into
google:main
Choose a base branch
from
014-code:feature/llm-retry-policy
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+255
−42
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
155 changes: 155 additions & 0 deletions
155
core/src/test/java/com/google/adk/models/GeminiBuilderTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | ||
| } | ||
| } | ||
| } |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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 rejectnull.There was a problem hiding this comment.
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 addedorg.jspecify.annotations.Nullableto the parameter and documented thatnulluses the SDK defaults.