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
44 changes: 29 additions & 15 deletions core/src/main/java/com/google/adk/models/Gemini.java
Original file line number Diff line number Diff line change
Expand Up @@ -136,12 +136,12 @@ private static Client buildDefaultClient(@Nullable ExecutorService executorServi
private final @Nullable String requestApiVersion;

/**
* 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
* Engine, Cloud Run or Kubernetes the tag names that runtime unless a base URL ADK can see, in
* the request config or the environment, points outside Google APIs; the client's own base URL is
* not visible. If the client's own headers already carry an ADK tag, requests send two because
* the SDK does not expose a client's headers.
* Constructs a new Gemini instance. Each generate request and live connection sent through {@code
* apiClient} carries ADK's tracking tag, which the genai SDK appends to the client's tracking
* headers. On Agent Engine, Cloud Run or Kubernetes the tag names that runtime unless a base URL
* ADK can see, in the request config or the environment, points outside Google APIs; the client's
* own base URL is not visible. If the client's own headers already carry an ADK tag, requests
* send two because the SDK does not expose a client's headers.
*
* @param modelName The name of the Gemini model to use (e.g., "gemini-2.0-flash").
* @param apiClient The genai {@link com.google.genai.Client} instance for making API calls.
Expand Down Expand Up @@ -359,16 +359,22 @@ private Flowable<LlmResponse> sendRequest(
private static GenerateContentConfig withTrackingHeaders(
@Nullable GenerateContentConfig config, boolean vertexAi) {
GenerateContentConfig base = config != null ? config : GenerateContentConfig.builder().build();
HttpOptions httpOptions = base.httpOptions().orElseGet(() -> HttpOptions.builder().build());
return base.toBuilder().httpOptions(withTrackingHeaders(base.httpOptions(), vertexAi)).build();
}

/**
* Returns {@code httpOptions}, or empty options, with ADK's tracking tag merged into its headers.
* The tag carries the runtime only toward a Google API.
*/
private static HttpOptions withTrackingHeaders(
Optional<HttpOptions> httpOptions, boolean vertexAi) {
HttpOptions base = httpOptions.orElseGet(() -> HttpOptions.builder().build());
return base.toBuilder()
.httpOptions(
httpOptions.toBuilder()
.headers(
TrackingHeaders.mergeIntoGenAiSdkHeaders(
httpOptions.headers().orElse(ImmutableMap.of()),
TrackingHeaders.genAiTargetsGoogleApis(
httpOptions.baseUrl().orElse(null), vertexAi, System::getenv)))
.build())
.headers(
TrackingHeaders.mergeIntoGenAiSdkHeaders(
base.headers().orElse(ImmutableMap.of()),
TrackingHeaders.genAiTargetsGoogleApis(
base.baseUrl().orElse(null), vertexAi, System::getenv)))
.build();
}

Expand Down Expand Up @@ -543,6 +549,14 @@ public BaseLlmConnection connect(LlmRequest llmRequest) {
llmRequest.tools().size(),
liveConnectConfig.systemInstruction().isPresent());

if (!clientSendsTrackingHeaders) {
// The genai SDK appends these connection headers to the client's own.
liveConnectConfig =
liveConnectConfig.toBuilder()
.httpOptions(
withTrackingHeaders(liveConnectConfig.httpOptions(), apiClient.vertexAI()))
.build();
}
return new GeminiLlmConnection(
effectiveModelName, connectLiveTransport(effectiveModelName, liveConnectConfig));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,16 @@
import static com.google.adk.models.LocalModelServer.GENERATE_CONTENT_JSON;
import static com.google.adk.models.LocalModelServer.adkTags;
import static com.google.adk.models.LocalModelServer.headersSentToLocalServer;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.truth.Truth.assertThat;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.junit.Assume.assumeNotNull;

import com.google.adk.models.FakeGeminiApi.Kind;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import com.google.genai.Client;
import com.google.genai.types.LiveConnectConfig;
import com.sun.net.httpserver.Headers;
import org.junit.Before;
import org.junit.Test;
Expand Down Expand Up @@ -73,10 +79,58 @@ public void gemini_callerClientOnVertexAi_ignoresTheGeminiBaseUrl() throws Excep
}
}

@Test
public void connect_callerClientOnTheGeminiApi_sendsNoRuntimeTag() {
FakeGeminiApi api = new FakeGeminiApi();
okhttp3.Headers headers =
liveHandshakeHeaders(
api, new Gemini("gemini-test", api.client()), LiveConnectConfig.builder().build());

for (String name : TrackingHeaders.HEADER_NAMES) {
assertThat(liveAdkTags(headers, name)).containsExactly(TrackingHeaders.ADK_TAG);
}
}

@Test
public void connect_callerClientOnVertexAi_ignoresTheGeminiBaseUrl() {
FakeGeminiApi api = new FakeGeminiApi();
okhttp3.Headers headers =
liveHandshakeHeaders(
api,
new Gemini("gemini-test", api.vertexClient()),
LiveConnectConfig.builder().build());

for (String name : TrackingHeaders.HEADER_NAMES) {
assertThat(liveAdkTags(headers, name))
.containsExactly(TrackingHeaders.ADK_TAG + "+cloud_run");
}
}

/** Asserts that both tracking headers carry exactly one ADK tag, without a runtime suffix. */
private static void assertAdkTag(Headers headers) {
for (String name : TrackingHeaders.HEADER_NAMES) {
assertThat(adkTags(headers, name)).containsExactly(TrackingHeaders.ADK_TAG);
}
}

/**
* Connects {@code gemini} to {@code api} with {@code config} and returns the handshake headers.
*/
private static okhttp3.Headers liveHandshakeHeaders(
FakeGeminiApi api, Gemini gemini, LiveConnectConfig config) {
BaseLlmConnection connection =
gemini.connect(LlmRequest.builder().liveConnectConfig(config).build());
connection.receive().test().awaitDone(5, SECONDS).assertError(Throwable.class);
connection.close();
ImmutableList<okhttp3.Headers> headers = api.headers(Kind.LIVE_CONNECT);
assertThat(headers).hasSize(1);
return headers.get(0);
}

private static ImmutableList<String> liveAdkTags(okhttp3.Headers headers, String name) {
return Splitter.on(' ')
.splitToStream(headers.get(name))
.filter(tag -> tag.startsWith("google-adk/"))
.collect(toImmutableList());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@
import static com.google.common.base.StandardSystemProperty.JAVA_VERSION;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.truth.Truth.assertThat;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.junit.Assume.assumeNotNull;
import static org.junit.Assume.assumeTrue;

import com.google.adk.models.FakeGeminiApi.Kind;
import com.google.common.base.Splitter;
Expand All @@ -32,6 +34,7 @@
import com.google.genai.types.Content;
import com.google.genai.types.GenerateContentConfig;
import com.google.genai.types.HttpOptions;
import com.google.genai.types.LiveConnectConfig;
import com.google.genai.types.Part;
import java.util.Map;
import java.util.function.Function;
Expand All @@ -42,9 +45,9 @@
import org.junit.runners.JUnit4;

/**
* Tests the tracking headers sent on Gemini requests after the genai SDK merges them. Both {@code
* user-agent} and {@code x-goog-api-client} carry one ADK tag and the Java version tag, whoever
* built the client.
* Tests the tracking headers sent on Gemini requests and live handshakes after the genai SDK merges
* them. Both {@code user-agent} and {@code x-goog-api-client} carry one ADK tag and the Java
* version tag, whoever built the client.
*/
@RunWith(JUnit4.class)
public final class GeminiTrackingHeadersTest {
Expand Down Expand Up @@ -166,6 +169,126 @@ public void generateContent_callerRequestHeaderWithAdkTag_isNotExtended() {
assertTrackingHeaders(headers::get, "google-adk/0.0.1");
}

@Test
public void connect_callerClient_sendsTrackingHeaders() {
connect(new Gemini("gemini-test", api.client()), LiveConnectConfig.builder().build());

assertTrackingHeaders(onlyLiveConnectHeaders()::get, TrackingHeaders.ADK_TAG);
}

@Test
public void connect_vertexCallerClient_sendsTrackingHeaders() {
connect(new Gemini("gemini-test", api.vertexClient()), LiveConnectConfig.builder().build());

assertTrackingHeaders(onlyLiveConnectHeaders()::get, TrackingHeaders.ADK_TAG);
}

@Test
public void connect_callerClientUserAgent_isExtendedWithAdkTag() {
Client client =
api.client(
HttpOptions.builder().headers(ImmutableMap.of("user-agent", "my-app/1.0")).build());

connect(new Gemini("gemini-test", client), LiveConnectConfig.builder().build());

Headers headers = onlyLiveConnectHeaders();
assertThat(headers.get("user-agent")).endsWith(" my-app/1.0 " + TrackingHeaders.ADK_TAG);
assertTrackingHeaders(headers::get, TrackingHeaders.ADK_TAG);
}

@Test
public void connect_callerConnectionHeaders_areExtendedWithAdkTag() {
LiveConnectConfig config =
LiveConnectConfig.builder()
.httpOptions(
HttpOptions.builder()
.headers(ImmutableMap.of("User-Agent", "my-app/1.0", "X-Custom", "v"))
.build())
.build();

connect(new Gemini("gemini-test", api.client()), config);

Headers headers = onlyLiveConnectHeaders();
assertThat(headers.get("user-agent")).endsWith(" my-app/1.0 " + TrackingHeaders.ADK_TAG);
assertThat(headers.get("X-Custom")).isEqualTo("v");
assertTrackingHeaders(headers::get, TrackingHeaders.ADK_TAG);
}

@Test
public void connect_callerConnectionApiVersion_isKept() {
LiveConnectConfig config =
LiveConnectConfig.builder()
.httpOptions(HttpOptions.builder().apiVersion("v1alpha").build())
.build();

connect(new Gemini("gemini-test", api.client()), config);

assertThat(onlyLiveConnectPath()).contains(".v1alpha.");
assertTrackingHeaders(onlyLiveConnectHeaders()::get, TrackingHeaders.ADK_TAG);
}

@Test
public void connect_callerClientWithoutApiVersion_keepsTheDefaultApiVersion() {
String apiVersion = System.getenv("GOOGLE_GENAI_API_VERSION");
assumeTrue(apiVersion == null || apiVersion.isEmpty());

connect(new Gemini("gemini-test", api.client()), LiveConnectConfig.builder().build());

assertThat(onlyLiveConnectPath()).contains(".v1beta.");
assertTrackingHeaders(onlyLiveConnectHeaders()::get, TrackingHeaders.ADK_TAG);
}

@Test
public void connect_callerConnectionHeaderWithAdkTag_isNotExtended() {
LiveConnectConfig config =
LiveConnectConfig.builder()
.httpOptions(
HttpOptions.builder()
.headers(ImmutableMap.of("X-Goog-Api-Client", "my-app/1.0 google-adk/0.0.1"))
.build())
.build();

connect(new Gemini("gemini-test", api.client()), config);

assertThat(onlyLiveConnectHeaders().get("x-goog-api-client"))
.endsWith(" my-app/1.0 google-adk/0.0.1");
}

@Test
public void connect_clientSendingTrackingHeaders_isNotExtended() {
Client client =
api.client(
HttpOptions.builder()
.headers(TrackingHeaders.genAiSdkHeaders(/* includeRuntimeTag= */ false))
.build());

connect(
new Gemini("gemini-test", client, /* clientSendsTrackingHeaders= */ true),
LiveConnectConfig.builder().build());

assertTrackingHeaders(onlyLiveConnectHeaders()::get, TrackingHeaders.ADK_TAG);
}

/** Connects {@code gemini} with {@code config} and waits for the fake to refuse it. */
private static void connect(Gemini gemini, LiveConnectConfig config) {
BaseLlmConnection connection =
gemini.connect(LlmRequest.builder().liveConnectConfig(config).build());
connection.receive().test().awaitDone(5, SECONDS).assertError(Throwable.class);
connection.close();
}

private Headers onlyLiveConnectHeaders() {
ImmutableList<Headers> headers = api.headers(Kind.LIVE_CONNECT);
assertThat(headers).hasSize(1);
return headers.get(0);
}

private String onlyLiveConnectPath() {
ImmutableList<String> paths = api.paths(Kind.LIVE_CONNECT);
assertThat(paths).hasSize(1);
return paths.get(0);
}

private Client clientWithHeaders(Map<String, String> headers) {
return Client.builder()
.apiKey("test-api-key")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,18 @@
import static com.google.adk.models.LocalModelServer.GENERATE_CONTENT_JSON;
import static com.google.adk.models.LocalModelServer.adkTags;
import static com.google.adk.models.LocalModelServer.headersSentToLocalServer;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.truth.Truth.assertThat;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.junit.Assume.assumeNotNull;

import com.google.adk.models.FakeGeminiApi.Kind;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import com.google.genai.Client;
import com.google.genai.types.GenerateContentConfig;
import com.google.genai.types.HttpOptions;
import com.google.genai.types.LiveConnectConfig;
import com.sun.net.httpserver.Headers;
import org.junit.Before;
import org.junit.Test;
Expand Down Expand Up @@ -102,6 +108,34 @@ public void apigeeChatCompletions_sendsNoRuntimeTag() throws Exception {
TrackingHeaders.ADK_TAG);
}

@Test
public void connect_callerClient_sendsTheRuntimeTag() {
FakeGeminiApi api = new FakeGeminiApi();
okhttp3.Headers headers =
liveHandshakeHeaders(
api, new Gemini("gemini-test", api.client()), LiveConnectConfig.builder().build());

for (String name : TrackingHeaders.HEADER_NAMES) {
assertThat(liveAdkTags(headers, name)).containsExactly(CLOUD_RUN_ADK_TAG);
}
}

@Test
public void connect_connectionBaseUrlOutsideGoogleApis_sendsNoRuntimeTag() {
FakeGeminiApi api = new FakeGeminiApi();
okhttp3.Headers headers =
liveHandshakeHeaders(
api,
new Gemini("gemini-test", api.client()),
LiveConnectConfig.builder()
.httpOptions(HttpOptions.builder().baseUrl("https://proxy.example.com").build())
.build());

for (String name : TrackingHeaders.HEADER_NAMES) {
assertThat(liveAdkTags(headers, name)).containsExactly(TrackingHeaders.ADK_TAG);
}
}

private static BaseLlm apigee(String modelName, String proxyUrl) {
return ApigeeLlm.builder().modelName(modelName).proxyUrl(proxyUrl).build();
}
Expand All @@ -112,4 +146,25 @@ private static void assertAdkTag(Headers headers, String adkTag) {
assertThat(adkTags(headers, name)).containsExactly(adkTag);
}
}

/**
* Connects {@code gemini} to {@code api} with {@code config} and returns the handshake headers.
*/
private static okhttp3.Headers liveHandshakeHeaders(
FakeGeminiApi api, Gemini gemini, LiveConnectConfig config) {
BaseLlmConnection connection =
gemini.connect(LlmRequest.builder().liveConnectConfig(config).build());
connection.receive().test().awaitDone(5, SECONDS).assertError(Throwable.class);
connection.close();
ImmutableList<okhttp3.Headers> headers = api.headers(Kind.LIVE_CONNECT);
assertThat(headers).hasSize(1);
return headers.get(0);
}

private static ImmutableList<String> liveAdkTags(okhttp3.Headers headers, String name) {
return Splitter.on(' ')
.splitToStream(headers.get(name))
.filter(tag -> tag.startsWith("google-adk/"))
.collect(toImmutableList());
}
}
Loading