From 13ce6e3d96ebaa9b9ad84198e50ed81e6aab14f3 Mon Sep 17 00:00:00 2001 From: Google Team Member Date: Wed, 2 Dec 2026 02:05:35 -0800 Subject: [PATCH] feat(models): tag the hosting runtime in tracking headers to Google APIs PiperOrigin-RevId: 1034261928 --- core/pom.xml | 43 +++- .../java/com/google/adk/models/ApigeeLlm.java | 5 +- .../java/com/google/adk/models/Claude.java | 45 ++-- .../java/com/google/adk/models/Gemini.java | 26 +- .../google/adk/models/TrackingHeaders.java | 143 +++++++++-- .../com/google/adk/models/ApigeeLlmTest.java | 79 ++---- .../adk/models/BaseUrlRuntimeTagTest.java | 82 ++++++ .../com/google/adk/models/ClaudeTest.java | 69 ++++- .../adk/models/GeminiTrackingHeadersTest.java | 73 ++---- .../google/adk/models/LocalModelServer.java | 119 +++++++++ .../models/RuntimeTagTrackingHeadersTest.java | 115 +++++++++ .../adk/models/TrackingHeadersTest.java | 237 +++++++++++++++++- 12 files changed, 852 insertions(+), 184 deletions(-) create mode 100644 core/src/test/java/com/google/adk/models/BaseUrlRuntimeTagTest.java create mode 100644 core/src/test/java/com/google/adk/models/LocalModelServer.java create mode 100644 core/src/test/java/com/google/adk/models/RuntimeTagTrackingHeadersTest.java diff --git a/core/pom.xml b/core/pom.xml index cb2dd08550..7591d1f6cb 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -251,6 +251,11 @@ maven-surefire-plugin + + + GOOGLE_CLOUD_AGENT_ENGINE_ID,K_SERVICE,CLOUD_RUN_JOB,KUBERNETES_SERVICE_HOST + @@ -293,7 +298,7 @@ api-key false - GOOGLE_GENAI_USE_ENTERPRISE + GOOGLE_GENAI_USE_ENTERPRISE,GOOGLE_CLOUD_AGENT_ENGINE_ID,K_SERVICE,CLOUD_RUN_JOB,KUBERNETES_SERVICE_HOST @@ -308,7 +313,7 @@ true - GOOGLE_GENAI_USE_ENTERPRISE + GOOGLE_GENAI_USE_ENTERPRISE,GOOGLE_CLOUD_AGENT_ENGINE_ID,K_SERVICE,CLOUD_RUN_JOB,KUBERNETES_SERVICE_HOST @@ -322,7 +327,7 @@ api-key true - GOOGLE_GENAI_USE_VERTEXAI + GOOGLE_GENAI_USE_VERTEXAI,GOOGLE_CLOUD_AGENT_ENGINE_ID,K_SERVICE,CLOUD_RUN_JOB,KUBERNETES_SERVICE_HOST @@ -353,6 +358,38 @@ + + runtime-tag-tracking-headers + + test + + + RuntimeTagTrackingHeadersTest, ClaudeTest#generateContent_googleApiHost_sendsTheRuntimeTag+generateContent_otherHost_sendsNoRuntimeTag + + + api-key + test-service + false + + GOOGLE_CLOUD_AGENT_ENGINE_ID,CLOUD_RUN_JOB,KUBERNETES_SERVICE_HOST,GOOGLE_GEMINI_BASE_URL,GOOGLE_VERTEX_BASE_URL + + + + base-url-runtime-tag + + test + + + BaseUrlRuntimeTagTest + + + test-service + https://proxy.example.com + false + + GOOGLE_CLOUD_AGENT_ENGINE_ID,CLOUD_RUN_JOB,KUBERNETES_SERVICE_HOST,GOOGLE_VERTEX_BASE_URL + + diff --git a/core/src/main/java/com/google/adk/models/ApigeeLlm.java b/core/src/main/java/com/google/adk/models/ApigeeLlm.java index 9f9dfcaf48..d84c15d523 100644 --- a/core/src/main/java/com/google/adk/models/ApigeeLlm.java +++ b/core/src/main/java/com/google/adk/models/ApigeeLlm.java @@ -104,8 +104,9 @@ private ApigeeLlm( // adds its own gl-java tag. .headers( this.apiType == ApiType.CHAT_COMPLETIONS - ? TrackingHeaders.mergeInto(callerHeaders) - : TrackingHeaders.mergeIntoGenAiSdkHeaders(callerHeaders)); + ? TrackingHeaders.mergeInto(callerHeaders, /* includeRuntimeTag= */ false) + : TrackingHeaders.mergeIntoGenAiSdkHeaders( + callerHeaders, /* includeRuntimeTag= */ false)); String apiVersion = identifyApiVersion(modelName); if (!apiVersion.isEmpty()) { httpOptionsBuilder.apiVersion(apiVersion); diff --git a/core/src/main/java/com/google/adk/models/Claude.java b/core/src/main/java/com/google/adk/models/Claude.java index 60d567f065..58fbdae9d1 100644 --- a/core/src/main/java/com/google/adk/models/Claude.java +++ b/core/src/main/java/com/google/adk/models/Claude.java @@ -21,6 +21,7 @@ import static java.util.stream.Collectors.joining; import com.anthropic.client.AnthropicClient; +import com.anthropic.core.ClientOptions; import com.anthropic.core.JsonValue; import com.anthropic.core.Properties; import com.anthropic.core.http.Headers; @@ -166,7 +167,8 @@ public class Claude extends BaseLlm { /** * Constructs a new Claude instance. Requests sent through {@code anthropicClient} carry ADK's - * usage-tracking headers, added to the ones the client already sends. + * usage-tracking headers, added to the ones the client already sends; on Agent Engine, Cloud Run + * or Kubernetes they name that runtime only when the client targets a Google API. * * @param modelName The name of the Claude model to use (e.g., "claude-3-opus-20240229"). * @param anthropicClient The Anthropic API client instance. @@ -281,30 +283,35 @@ public Claude build() { /** * Returns a copy of {@code client} that shares its connections and sends ADK's tracking headers, - * extending any the client already sets. A null client, or a test double that returns no copy, is - * returned unchanged. + * extending any the client already sets, with the runtime tag only toward a Google API. The + * target is the base URL the client's backend reports, so a backend that rewrites the host when + * it prepares a request is judged by the reported URL. A null client, or a test double that + * returns no copy, is returned unchanged. */ private static @Nullable AnthropicClient withTrackingHeaders(@Nullable AnthropicClient client) { if (client == null) { return null; } AnthropicClient tracked = - client.withOptions( - options -> { - Headers configured = options.build().headers(); - Map current = new HashMap<>(); - // Start from the SDK's default User-Agent, which it adds only when none is set. - current.put( - "user-agent", - client.getClass().getSimpleName() + "/Java " + Properties.getPackageVersion()); - for (String name : TrackingHeaders.HEADERS.keySet()) { - List values = configured.values(name); - if (!values.isEmpty()) { - current.put(name, String.join(" ", values)); - } - } - TrackingHeaders.mergeInto(current).forEach(options::replaceHeaders); - }); + client.withOptions(options -> { + ClientOptions built = options.build(); + Headers configured = built.headers(); + Map current = new HashMap<>(); + // Start from the SDK's default User-Agent, which it adds only when none is set. + current.put( + "user-agent", + client.getClass().getSimpleName() + "/Java " + Properties.getPackageVersion()); + for (String name : TrackingHeaders.HEADER_NAMES) { + List values = configured.values(name); + if (!values.isEmpty()) { + current.put(name, String.join(" ", values)); + } + } + TrackingHeaders.mergeInto( + current, + /* includeRuntimeTag= */ TrackingHeaders.isGoogleApisUrl(built.baseUrl())) + .forEach(options::replaceHeaders); + }); return tracked != null ? tracked : client; } diff --git a/core/src/main/java/com/google/adk/models/Gemini.java b/core/src/main/java/com/google/adk/models/Gemini.java index 533715bca2..9f135d0101 100644 --- a/core/src/main/java/com/google/adk/models/Gemini.java +++ b/core/src/main/java/com/google/adk/models/Gemini.java @@ -94,7 +94,12 @@ 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) { return Client.builder() - .httpOptions(HttpOptions.builder().headers(TrackingHeaders.GENAI_SDK_HEADERS).build()) + .httpOptions( + HttpOptions.builder() + .headers( + TrackingHeaders.genAiSdkHeaders( + TrackingHeaders.adkGenAiClientTargetsGoogleApis(System::getenv))) + .build()) .clientOptions( ClientOptions.builder().customHttpClient(prepareHttpClient(executorService)).build()); } @@ -123,9 +128,11 @@ private static Client buildDefaultClient(@Nullable ExecutorService executorServi /** * 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. If the - * client's own headers already carry an ADK tag, requests send two because the SDK does not - * expose a client's headers. + * 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. @@ -312,7 +319,7 @@ private Flowable sendRequest( llmRequest.tools().size()); if (!clientSendsTrackingHeaders) { - config = withTrackingHeaders(config); + config = withTrackingHeaders(config, apiClient.vertexAI()); } if (stream) { logger.debug("Sending streaming generateContent request to model {}", effectiveModelName); @@ -335,9 +342,10 @@ private Flowable sendRequest( /** * Returns {@code config} with ADK's tracking tag merged into its request headers, which the genai - * SDK appends to the client's own. + * SDK appends to the client's own. The tag carries the runtime only toward a Google API. */ - private static GenerateContentConfig withTrackingHeaders(@Nullable GenerateContentConfig config) { + 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() @@ -345,7 +353,9 @@ private static GenerateContentConfig withTrackingHeaders(@Nullable GenerateConte httpOptions.toBuilder() .headers( TrackingHeaders.mergeIntoGenAiSdkHeaders( - httpOptions.headers().orElse(ImmutableMap.of()))) + httpOptions.headers().orElse(ImmutableMap.of()), + TrackingHeaders.genAiTargetsGoogleApis( + httpOptions.baseUrl().orElse(null), vertexAi, System::getenv))) .build()) .build(); } diff --git a/core/src/main/java/com/google/adk/models/TrackingHeaders.java b/core/src/main/java/com/google/adk/models/TrackingHeaders.java index 52e0521a96..d249c655dc 100644 --- a/core/src/main/java/com/google/adk/models/TrackingHeaders.java +++ b/core/src/main/java/com/google/adk/models/TrackingHeaders.java @@ -22,13 +22,20 @@ import com.google.adk.Version; import com.google.common.base.Ascii; +import com.google.common.base.CharMatcher; import com.google.common.base.Splitter; +import com.google.common.base.Strings; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.function.Function; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import java.util.stream.Stream; +import okhttp3.HttpUrl; +import org.jspecify.annotations.Nullable; /** * Headers that let Google APIs attribute model calls to ADK, in the format all ADK SDKs use. A @@ -38,52 +45,138 @@ final class TrackingHeaders { private static final Splitter TAG_SPLITTER = Splitter.on(' ').omitEmptyStrings(); - /** ADK's own tag. */ + /** ADK's own tag, without a hosting runtime suffix. */ static final String ADK_TAG = "google-adk/" + Version.JAVA_ADK_VERSION; - /** ADK's tag followed by the Java version tag, for clients that send no language tag. */ - static final String VALUE = ADK_TAG + " gl-java/" + JAVA_VERSION.value(); + /** The names of the tracking headers, in lower case. */ + static final ImmutableSet HEADER_NAMES = + ImmutableSet.of("x-goog-api-client", "user-agent"); - static final ImmutableMap HEADERS = - ImmutableMap.of("x-goog-api-client", VALUE, "user-agent", VALUE); + /** The authority of an https URL as written: up to the path, query or fragment. */ + private static final Pattern RAW_AUTHORITY = Pattern.compile("(?i)https://([^/?#]+)"); /** - * Headers for a genai SDK client, which puts its own {@code gl-java} tag first. Both carry only - * {@link #ADK_TAG}. + * Returns ADK's tag, with the hosting runtime as a build-metadata suffix if {@code + * includeRuntimeTag}, for example {@code google-adk/1.0.0+cloud_run}. */ - static final ImmutableMap GENAI_SDK_HEADERS = - ImmutableMap.of("x-goog-api-client", ADK_TAG, "user-agent", ADK_TAG); + private static String adkTag(boolean includeRuntimeTag) { + String runtimeTag = includeRuntimeTag ? runtimeTag(System::getenv) : null; + return runtimeTag == null ? ADK_TAG : ADK_TAG + "+" + runtimeTag; + } + + /** + * Returns {@link #adkTag} followed by the Java version tag, for clients that send no language + * tag. + */ + static String value(boolean includeRuntimeTag) { + return adkTag(includeRuntimeTag) + " gl-java/" + JAVA_VERSION.value(); + } + + /** + * Returns both tracking headers set to {@link #adkTag}, for a genai SDK client, which puts its + * own {@code gl-java} tag first. + */ + static ImmutableMap genAiSdkHeaders(boolean includeRuntimeTag) { + String tag = adkTag(includeRuntimeTag); + return ImmutableMap.of("x-goog-api-client", tag, "user-agent", tag); + } + + /** + * Returns the hosting runtime tag, or null when none is detected. Only checks whether variables + * the platform sets are non-empty; their values are never sent. + */ + static @Nullable String runtimeTag(Function getenv) { + // Most specific first: Agent Engine may also set K_*, Cloud Run on GKE KUBERNETES_SERVICE_HOST. + if (isSet(getenv, "GOOGLE_CLOUD_AGENT_ENGINE_ID")) { + return "remote_reasoning_engine"; + } + if (isSet(getenv, "K_SERVICE") || isSet(getenv, "CLOUD_RUN_JOB")) { + return "cloud_run"; + } + if (isSet(getenv, "KUBERNETES_SERVICE_HOST")) { + return "k8s"; + } + return null; + } + + private static boolean isSet(Function getenv, String name) { + return !Strings.isNullOrEmpty(getenv.apply(name)); + } + + /** + * Returns whether {@code url} is an https {@code *.googleapis.com} URL. A user info or backslash + * in the authority is rejected, because HTTP clients disagree on which host such a URL names. + */ + static boolean isGoogleApisUrl(@Nullable String url) { + HttpUrl parsed = url == null ? null : HttpUrl.parse(url); + if (parsed == null || !parsed.isHttps() || !parsed.host().endsWith(".googleapis.com")) { + return false; + } + // HttpUrl drops an empty user info and extra slashes and reads a backslash as a slash. + Matcher authority = RAW_AUTHORITY.matcher(url); + return authority.lookingAt() && CharMatcher.anyOf("@\\").matchesNoneOf(authority.group(1)); + } + + /** + * Returns whether a genai request goes to a Google API, judging by the base URL ADK can see: the + * request's {@code requestBaseUrl}, else the base URL variable for the client's API, else the + * genai default, which is a Google API. Requests to a caller client's own base URL, to one set + * through {@code Client.setDefaultBaseUrls}, or to a request base URL on a client ADK built, + * whose tag is fixed when it is built, still carry the runtime tag. + */ + static boolean genAiTargetsGoogleApis( + @Nullable String requestBaseUrl, + boolean vertexAi, + Function getenv) { + String baseUrl = requestBaseUrl; + if (baseUrl == null) { + baseUrl = + Strings.emptyToNull( + getenv.apply(vertexAi ? "GOOGLE_VERTEX_BASE_URL" : "GOOGLE_GEMINI_BASE_URL")); + } + return baseUrl == null || isGoogleApisUrl(baseUrl); + } + + /** + * Returns whether a genai client ADK builds goes to a Google API. Its API is known only once it + * is built, so neither base URL variable may point elsewhere. + */ + static boolean adkGenAiClientTargetsGoogleApis(Function getenv) { + return genAiTargetsGoogleApis(null, /* vertexAi= */ true, getenv) + && genAiTargetsGoogleApis(null, /* vertexAi= */ false, getenv); + } /** - * Like {@link #mergeInto}, but adds only {@link #ADK_TAG}, for headers that the genai SDK appends + * Like {@link #mergeInto}, but adds only {@link #adkTag}, for headers that the genai SDK appends * to its own label. */ - static ImmutableMap mergeIntoGenAiSdkHeaders(Map headers) { - return mergeInto(headers, ADK_TAG); + static ImmutableMap mergeIntoGenAiSdkHeaders( + Map headers, boolean includeRuntimeTag) { + return mergeInto(headers, adkTag(includeRuntimeTag)); } /** * Returns {@code headers} with each tracking header, matched case-insensitively, followed by - * every tag of {@link #VALUE} whose name it lacks. + * every tag of {@link #value} whose name it lacks. */ - static ImmutableMap mergeInto(Map headers) { - return mergeInto(headers, VALUE); + static ImmutableMap mergeInto( + Map headers, boolean includeRuntimeTag) { + return mergeInto(headers, value(includeRuntimeTag)); } private static ImmutableMap mergeInto( Map headers, String adkTags) { Map merged = new LinkedHashMap<>(); Map callerValues = new LinkedHashMap<>(); - headers.forEach( - (name, value) -> { - String trackingName = Ascii.toLowerCase(name); - if (HEADERS.containsKey(trackingName)) { - callerValues.merge(trackingName, value, (first, second) -> first + " " + second); - } else { - merged.put(name, value); - } - }); - for (String name : HEADERS.keySet()) { + headers.forEach((name, value) -> { + String trackingName = Ascii.toLowerCase(name); + if (HEADER_NAMES.contains(trackingName)) { + callerValues.merge(trackingName, value, (first, second) -> first + " " + second); + } else { + merged.put(name, value); + } + }); + for (String name : HEADER_NAMES) { merged.put(name, extend(callerValues.getOrDefault(name, ""), adkTags)); } return ImmutableMap.copyOf(merged); diff --git a/core/src/test/java/com/google/adk/models/ApigeeLlmTest.java b/core/src/test/java/com/google/adk/models/ApigeeLlmTest.java index 1d211461de..0c81b1aa99 100644 --- a/core/src/test/java/com/google/adk/models/ApigeeLlmTest.java +++ b/core/src/test/java/com/google/adk/models/ApigeeLlmTest.java @@ -15,11 +15,13 @@ */ package com.google.adk.models; +import static com.google.adk.models.LocalModelServer.CHAT_COMPLETION_JSON; +import static com.google.adk.models.LocalModelServer.GENERATE_CONTENT_JSON; +import static com.google.adk.models.LocalModelServer.headersSentToLocalServer; import static com.google.common.base.StandardSystemProperty.JAVA_VERSION; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.Iterables.getOnlyElement; import static com.google.common.truth.Truth.assertThat; -import static java.nio.charset.StandardCharsets.UTF_8; import static org.junit.Assert.assertThrows; import static org.junit.Assume.assumeNotNull; import static org.junit.Assume.assumeTrue; @@ -41,7 +43,6 @@ import com.google.common.base.Splitter; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; -import com.google.common.net.InetAddresses; import com.google.genai.Client; import com.google.genai.types.Content; import com.google.genai.types.FunctionDeclaration; @@ -49,15 +50,10 @@ import com.google.genai.types.Part; import com.google.genai.types.Schema; import com.sun.net.httpserver.Headers; -import com.sun.net.httpserver.HttpServer; import io.reactivex.rxjava3.core.Flowable; -import java.io.OutputStream; -import java.net.InetAddress; -import java.net.InetSocketAddress; import java.util.Map; import java.util.Objects; import java.util.Optional; -import java.util.concurrent.atomic.AtomicReference; import org.junit.Before; import org.junit.Rule; import org.junit.Test; @@ -416,7 +412,7 @@ public void build_chatCompletions_addsTheTrackingTagsCustomHeadersLack() { assertThat(llm.getHttpOptions().headers().get()) .containsExactly( "user-agent", - "custom-agent " + TrackingHeaders.VALUE, + "custom-agent " + TrackingHeaders.value(/* includeRuntimeTag= */ false), "x-goog-api-client", "lib/1 google-adk/0.0.1 gl-java/" + JAVA_VERSION.value()); } @@ -502,8 +498,9 @@ public void generateContent_chatCompletions_sendsTrackingHeaders() throws Except headersSentToProxy( "apigee/openai/gpt-4o", /* customHeaders= */ ImmutableMap.of(), CHAT_COMPLETION_JSON); - for (String name : TrackingHeaders.HEADERS.keySet()) { - assertThat(headers.get(name)).containsExactly(TrackingHeaders.VALUE); + for (String name : TrackingHeaders.HEADER_NAMES) { + assertThat(headers.get(name)) + .containsExactly(TrackingHeaders.value(/* includeRuntimeTag= */ false)); } } @@ -528,8 +525,10 @@ public void generateContent_chatCompletions_extendsACustomUserAgent() throws Exc ImmutableMap.of("User-Agent", "custom-agent"), CHAT_COMPLETION_JSON); - assertThat(headers.get("user-agent")).containsExactly("custom-agent " + TrackingHeaders.VALUE); - assertThat(headers.get("x-goog-api-client")).containsExactly(TrackingHeaders.VALUE); + assertThat(headers.get("user-agent")) + .containsExactly("custom-agent " + TrackingHeaders.value(/* includeRuntimeTag= */ false)); + assertThat(headers.get("x-goog-api-client")) + .containsExactly(TrackingHeaders.value(/* includeRuntimeTag= */ false)); } /** @@ -589,44 +588,14 @@ public Optional declaration() { */ private static Headers headersSentToProxy( String modelName, Map customHeaders, String responseJson) throws Exception { - AtomicReference requestHeaders = new AtomicReference<>(); - HttpServer server = - HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0); - server.createContext( - "/", - exchange -> { - requestHeaders.set(exchange.getRequestHeaders()); - byte[] body = responseJson.getBytes(UTF_8); - exchange.getResponseHeaders().set("Content-Type", "application/json"); - exchange.sendResponseHeaders(200, body.length); - try (OutputStream out = exchange.getResponseBody()) { - out.write(body); - } - }); - server.start(); - try { - ApigeeLlm.Builder builder = - ApigeeLlm.builder() - .modelName(modelName) - .proxyUrl( - "http://" - + InetAddresses.toUriString(server.getAddress().getAddress()) - + ":" - + server.getAddress().getPort()); - builder.customHeaders(customHeaders); - LlmRequest request = - LlmRequest.builder() - .contents( - ImmutableList.of( - Content.builder().role("user").parts(Part.fromText("hello")).build())) - .build(); - - builder.build().generateContent(request, /* stream= */ false).blockingSubscribe(); - - return requestHeaders.get(); - } finally { - server.stop(0); - } + return headersSentToLocalServer( + url -> + ApigeeLlm.builder() + .modelName(modelName) + .proxyUrl(url) + .customHeaders(customHeaders) + .build(), + responseJson); } /** @@ -634,7 +603,7 @@ private static Headers headersSentToProxy( * includes the Java version tag and ADK's tag, and repeats no tag name. */ private static void assertGenAiTrackingHeaders(Headers headers) { - for (String name : TrackingHeaders.HEADERS.keySet()) { + for (String name : TrackingHeaders.HEADER_NAMES) { ImmutableList tags = ImmutableList.copyOf(Splitter.on(' ').split(getOnlyElement(headers.get(name)))); assertThat(tags.get(0)).startsWith("google-genai-sdk/"); @@ -643,12 +612,4 @@ private static void assertGenAiTrackingHeaders(Headers headers) { .containsNoDuplicates(); } } - - private static final String GENERATE_CONTENT_JSON = - "{\"candidates\":[{\"content\":{\"role\":\"model\",\"parts\":[{\"text\":\"hi\"}]}," - + "\"finishReason\":\"STOP\"}]}"; - - private static final String CHAT_COMPLETION_JSON = - "{\"choices\":[{\"message\":{\"role\":\"assistant\",\"content\":\"hi\"}," - + "\"finish_reason\":\"stop\"}]}"; } diff --git a/core/src/test/java/com/google/adk/models/BaseUrlRuntimeTagTest.java b/core/src/test/java/com/google/adk/models/BaseUrlRuntimeTagTest.java new file mode 100644 index 0000000000..861f13854c --- /dev/null +++ b/core/src/test/java/com/google/adk/models/BaseUrlRuntimeTagTest.java @@ -0,0 +1,82 @@ +/* + * 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.adk.models.LocalModelServer.adkTags; +import static com.google.adk.models.LocalModelServer.headersSentToLocalServer; +import static com.google.common.truth.Truth.assertThat; +import static org.junit.Assume.assumeNotNull; + +import com.google.genai.Client; +import com.sun.net.httpserver.Headers; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** + * Checks that Gemini leaves the runtime tag out when {@code GOOGLE_GEMINI_BASE_URL} points outside + * Google APIs, with {@code K_SERVICE} set as on Cloud Run. The build sets both for this test. + */ +@RunWith(JUnit4.class) +public final class BaseUrlRuntimeTagTest { + + @Before + public void setUp() { + assumeNotNull(System.getenv("K_SERVICE"), System.getenv("GOOGLE_GEMINI_BASE_URL")); + } + + @Test + public void gemini_adkBuiltClient_sendsNoRuntimeTag() throws Exception { + assertAdkTag( + headersSentToLocalServer( + url -> Gemini.builder().modelName("gemini-test").apiKey("test-api-key").build(), + GENERATE_CONTENT_JSON)); + } + + @Test + public void gemini_callerClientOnTheGeminiApi_sendsNoRuntimeTag() throws Exception { + assertAdkTag( + headersSentToLocalServer( + url -> + new Gemini( + "gemini-test", Client.builder().apiKey("test-api-key").vertexAI(false).build()), + GENERATE_CONTENT_JSON)); + } + + @Test + public void gemini_callerClientOnVertexAi_ignoresTheGeminiBaseUrl() throws Exception { + Headers headers = + headersSentToLocalServer( + url -> + new Gemini( + "gemini-test", Client.builder().apiKey("test-api-key").vertexAI(true).build()), + GENERATE_CONTENT_JSON); + + for (String name : TrackingHeaders.HEADER_NAMES) { + assertThat(adkTags(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); + } + } +} diff --git a/core/src/test/java/com/google/adk/models/ClaudeTest.java b/core/src/test/java/com/google/adk/models/ClaudeTest.java index 6fb194dffb..2ac50aca19 100644 --- a/core/src/test/java/com/google/adk/models/ClaudeTest.java +++ b/core/src/test/java/com/google/adk/models/ClaudeTest.java @@ -17,10 +17,12 @@ package com.google.adk.models; import static com.google.adk.testing.TestUtils.createInvocationContext; +import static com.google.common.base.StandardSystemProperty.JAVA_VERSION; import static com.google.common.collect.Iterables.getOnlyElement; import static com.google.common.truth.Truth.assertThat; import static java.nio.charset.StandardCharsets.UTF_8; import static org.junit.Assert.assertThrows; +import static org.junit.Assume.assumeNotNull; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -31,6 +33,7 @@ import com.anthropic.client.AnthropicClient; import com.anthropic.client.okhttp.AnthropicOkHttpClient; import com.anthropic.core.JsonValue; +import com.anthropic.core.http.HttpRequest; import com.anthropic.models.messages.Base64ImageSource; import com.anthropic.models.messages.CacheControlEphemeral; import com.anthropic.models.messages.ContentBlock; @@ -1529,8 +1532,9 @@ public void generateContent_extendsTheSdkUserAgentWithAdkTrackingHeaders() throw String userAgent = getOnlyElement(headers.get("user-agent")); assertThat(userAgent).startsWith("AnthropicClientImpl/Java "); - assertThat(userAgent).endsWith(" " + TrackingHeaders.VALUE); - assertThat(headers.get("x-goog-api-client")).containsExactly(TrackingHeaders.VALUE); + assertThat(userAgent).endsWith(" " + TrackingHeaders.value(/* includeRuntimeTag= */ false)); + assertThat(headers.get("x-goog-api-client")) + .containsExactly(TrackingHeaders.value(/* includeRuntimeTag= */ false)); } @Test @@ -1538,8 +1542,35 @@ public void generateContent_extendsTheCallerUserAgentWithAdkTrackingHeaders() th Headers headers = headersSentThrough(AnthropicOkHttpClient.builder().putHeader("User-Agent", "my-app/1.0")); - assertThat(headers.get("user-agent")).containsExactly("my-app/1.0 " + TrackingHeaders.VALUE); - assertThat(headers.get("x-goog-api-client")).containsExactly(TrackingHeaders.VALUE); + assertThat(headers.get("user-agent")) + .containsExactly("my-app/1.0 " + TrackingHeaders.value(/* includeRuntimeTag= */ false)); + assertThat(headers.get("x-goog-api-client")) + .containsExactly(TrackingHeaders.value(/* includeRuntimeTag= */ false)); + } + + @Test + public void generateContent_googleApiHost_sendsTheRuntimeTag() throws Exception { + assumeNotNull(System.getenv("K_SERVICE")); + + Headers headers = + headersSentThrough( + AnthropicOkHttpClient.builder(), "https://us-east5-aiplatform.googleapis.com"); + + String value = TrackingHeaders.ADK_TAG + "+cloud_run gl-java/" + JAVA_VERSION.value(); + assertThat(getOnlyElement(headers.get("user-agent"))).endsWith(" " + value); + assertThat(headers.get("x-goog-api-client")).containsExactly(value); + } + + @Test + public void generateContent_otherHost_sendsNoRuntimeTag() throws Exception { + assumeNotNull(System.getenv("K_SERVICE")); + + Headers headers = headersSentThrough(AnthropicOkHttpClient.builder(), ANTHROPIC_API_URL); + + assertThat(getOnlyElement(headers.get("user-agent"))) + .endsWith(" " + TrackingHeaders.value(/* includeRuntimeTag= */ false)); + assertThat(headers.get("x-goog-api-client")) + .containsExactly(TrackingHeaders.value(/* includeRuntimeTag= */ false)); } @Test @@ -1547,6 +1578,8 @@ public void constructor_nullClient_doesNotThrow() { assertThat(new Claude("claude-test", (AnthropicClient) null).model()).isEqualTo("claude-test"); } + private static final String ANTHROPIC_API_URL = "https://api.anthropic.com"; + private static final String MESSAGE_JSON = "{\"id\":\"msg_1\",\"type\":\"message\",\"role\":\"assistant\",\"model\":\"claude-test\"," + "\"content\":[{\"type\":\"text\",\"text\":\"pong\"}],\"stop_reason\":\"end_turn\"," @@ -1674,7 +1707,7 @@ private static String messageDelta(String stopReason) { private List streamedResponses(String sseBody, LlmRequest request) throws Exception { HttpServer server = serve("text/event-stream", sseBody, new AtomicReference<>()); try { - return claudeServedBy(server, AnthropicOkHttpClient.builder()) + return claudeServedBy(server, AnthropicOkHttpClient.builder(), ANTHROPIC_API_URL) .generateContent(request, /* stream= */ true) .toList() .blockingGet(); @@ -1737,11 +1770,20 @@ public void generateContent_streamedToolUseCutOffByMaxTokens_returnsAnError() th */ private static Headers headersSentThrough(AnthropicOkHttpClient.Builder clientBuilder) throws Exception { + return headersSentThrough(clientBuilder, ANTHROPIC_API_URL); + } + + /** + * Like {@link #headersSentThrough(AnthropicOkHttpClient.Builder)}, with a client that reports + * {@code reportedBaseUrl} as its base URL. + */ + private static Headers headersSentThrough( + AnthropicOkHttpClient.Builder clientBuilder, String reportedBaseUrl) throws Exception { AtomicReference requestHeaders = new AtomicReference<>(); HttpServer server = serve("application/json", MESSAGE_JSON, requestHeaders); try { LlmResponse response = - claudeServedBy(server, clientBuilder) + claudeServedBy(server, clientBuilder, reportedBaseUrl) .generateContent(request(userText("Ping")), /* stream= */ false) .blockingFirst(); @@ -1772,9 +1814,13 @@ private static HttpServer serve( return server; } + /** + * Returns a {@link Claude} whose client reports {@code reportedBaseUrl} as its base URL but sends + * every request to {@code server}. + */ private static Claude claudeServedBy( - HttpServer server, AnthropicOkHttpClient.Builder clientBuilder) { - String baseUrl = + HttpServer server, AnthropicOkHttpClient.Builder clientBuilder, String reportedBaseUrl) { + String serverUrl = "http://" + InetAddresses.toUriString(server.getAddress().getAddress()) + ":" @@ -1783,7 +1829,12 @@ private static Claude claudeServedBy( new Backend() { @Override public String baseUrl() { - return baseUrl; + return reportedBaseUrl; + } + + @Override + public HttpRequest prepareRequest(HttpRequest request) { + return request.toBuilder().baseUrl(serverUrl).build(); } @Override diff --git a/core/src/test/java/com/google/adk/models/GeminiTrackingHeadersTest.java b/core/src/test/java/com/google/adk/models/GeminiTrackingHeadersTest.java index c325e29d83..3432d39962 100644 --- a/core/src/test/java/com/google/adk/models/GeminiTrackingHeadersTest.java +++ b/core/src/test/java/com/google/adk/models/GeminiTrackingHeadersTest.java @@ -16,32 +16,25 @@ package com.google.adk.models; +import static com.google.adk.models.LocalModelServer.GENERATE_CONTENT_JSON; +import static com.google.adk.models.LocalModelServer.headersSentToLocalServer; 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.nio.charset.StandardCharsets.UTF_8; 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.common.collect.ImmutableMap; -import com.google.common.net.InetAddresses; import com.google.genai.Client; import com.google.genai.types.ClientOptions; import com.google.genai.types.Content; import com.google.genai.types.GenerateContentConfig; import com.google.genai.types.HttpOptions; import com.google.genai.types.Part; -import com.sun.net.httpserver.HttpServer; -import java.io.OutputStream; -import java.net.InetAddress; -import java.net.InetSocketAddress; import java.util.Map; -import java.util.Optional; -import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; -import java.util.function.Supplier; import okhttp3.Headers; import okhttp3.OkHttpClient; import org.junit.Test; @@ -75,15 +68,19 @@ public void generateContentStream_callerClient_sendsTrackingHeaders() { @Test public void generateContent_adkBuiltApiKeyClient_sendsTrackingHeaders() throws Exception { assertTrackingHeaders( - headersSentByAdkBuiltClient(() -> new Gemini("gemini-test", "test-api-key")), + headersSentToLocalServer( + url -> new Gemini("gemini-test", "test-api-key"), GENERATE_CONTENT_JSON) + ::getFirst, TrackingHeaders.ADK_TAG); } @Test public void generateContent_adkBuiltBuilderClient_sendsTrackingHeaders() throws Exception { assertTrackingHeaders( - headersSentByAdkBuiltClient( - () -> Gemini.builder().modelName("gemini-test").apiKey("test-api-key").build()), + headersSentToLocalServer( + url -> Gemini.builder().modelName("gemini-test").apiKey("test-api-key").build(), + GENERATE_CONTENT_JSON) + ::getFirst, TrackingHeaders.ADK_TAG); } @@ -92,7 +89,9 @@ public void generateContent_adkBuiltRegistryClient_sendsTrackingHeaders() throws assumeNotNull(System.getenv("GOOGLE_API_KEY")); assertTrackingHeaders( - headersSentByAdkBuiltClient(() -> LlmRegistry.getLlm("gemini-tracking-headers-test")), + headersSentToLocalServer( + url -> LlmRegistry.getLlm("gemini-tracking-headers-test"), GENERATE_CONTENT_JSON) + ::getFirst, TrackingHeaders.ADK_TAG); } @@ -103,8 +102,10 @@ public void generateContent_adkBuiltVertexCredentialsClient_sendsTrackingHeaders // Empty credentials let the environment configure the backend, here the Gemini API key. assertTrackingHeaders( - headersSentByAdkBuiltClient( - () -> new Gemini("gemini-test", VertexCredentials.builder().build())), + headersSentToLocalServer( + url -> new Gemini("gemini-test", VertexCredentials.builder().build()), + GENERATE_CONTENT_JSON) + ::getFirst, TrackingHeaders.ADK_TAG); } @@ -165,44 +166,6 @@ public void generateContent_callerRequestHeaderWithAdkTag_isNotExtended() { assertTrackingHeaders(headers::get, "google-adk/0.0.1"); } - /** - * Sends one request through a {@link Gemini} that builds its own client pointed at a local server - * with {@link Client#setDefaultBaseUrls}, and returns the headers the server received. - */ - private static Function headersSentByAdkBuiltClient( - Supplier model) throws Exception { - AtomicReference received = new AtomicReference<>(); - HttpServer server = - HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0); - server.createContext( - "/", - exchange -> { - received.set(exchange.getRequestHeaders()); - byte[] body = GENERATE_CONTENT_JSON.getBytes(UTF_8); - exchange.getResponseHeaders().set("Content-Type", "application/json"); - exchange.sendResponseHeaders(200, body.length); - try (OutputStream out = exchange.getResponseBody()) { - out.write(body); - } - }); - server.start(); - Optional serverUrl = - Optional.of( - "http://" - + InetAddresses.toUriString(server.getAddress().getAddress()) - + ":" - + server.getAddress().getPort()); - // The environment can select Vertex AI instead of the Gemini API, so redirect both backends. - Client.setDefaultBaseUrls(serverUrl, serverUrl); - try { - generate(model.get(), request(), /* stream= */ false); - return name -> received.get().getFirst(name); - } finally { - Client.setDefaultBaseUrls(Optional.empty(), Optional.empty()); - server.stop(0); - } - } - private Client clientWithHeaders(Map headers) { return Client.builder() .apiKey("test-api-key") @@ -262,8 +225,4 @@ private static void assertTrackingHeaders( .containsNoDuplicates(); }); } - - private static final String GENERATE_CONTENT_JSON = - "{\"candidates\":[{\"content\":{\"role\":\"model\",\"parts\":[{\"text\":\"hi\"}]}," - + "\"finishReason\":\"STOP\"}]}"; } diff --git a/core/src/test/java/com/google/adk/models/LocalModelServer.java b/core/src/test/java/com/google/adk/models/LocalModelServer.java new file mode 100644 index 0000000000..4d6a8e86d3 --- /dev/null +++ b/core/src/test/java/com/google/adk/models/LocalModelServer.java @@ -0,0 +1,119 @@ +/* + * 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.common.base.Preconditions.checkState; +import static java.nio.charset.StandardCharsets.UTF_8; + +import com.google.common.base.Splitter; +import com.google.common.collect.ImmutableList; +import com.google.common.net.InetAddresses; +import com.google.genai.Client; +import com.google.genai.types.Content; +import com.google.genai.types.GenerateContentConfig; +import com.google.genai.types.Part; +import com.sun.net.httpserver.Headers; +import com.sun.net.httpserver.HttpServer; +import java.io.IOException; +import java.io.OutputStream; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.util.Optional; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Function; +import org.jspecify.annotations.Nullable; + +/** A local HTTP server that captures the headers a model sends with its client as built. */ +final class LocalModelServer { + + static final String GENERATE_CONTENT_JSON = + "{\"candidates\":[{\"content\":{\"role\":\"model\",\"parts\":[{\"text\":\"hi\"}]}," + + "\"finishReason\":\"STOP\"}]}"; + + static final String CHAT_COMPLETION_JSON = + "{\"choices\":[{\"message\":{\"role\":\"assistant\",\"content\":\"hi\"}," + + "\"finish_reason\":\"stop\"}]}"; + + /** + * Sends one request through the model that {@code modelFor} returns for the server's URL, and + * returns the headers the server received. Genai clients built meanwhile default to the server + * too, for both the Gemini API and Vertex AI. + */ + static Headers headersSentToLocalServer(Function modelFor, String responseJson) + throws IOException { + return headersSentToLocalServer(modelFor, url -> null, responseJson); + } + + /** + * Like {@link #headersSentToLocalServer(Function, String)}, with the request config that {@code + * configFor} returns for the server's URL, or none if it returns null. + */ + static Headers headersSentToLocalServer( + Function modelFor, + Function configFor, + String responseJson) + throws IOException { + AtomicReference received = new AtomicReference<>(); + HttpServer server = + HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0); + server.createContext( + "/", + exchange -> { + received.set(exchange.getRequestHeaders()); + byte[] body = responseJson.getBytes(UTF_8); + exchange.getResponseHeaders().set("Content-Type", "application/json"); + exchange.sendResponseHeaders(200, body.length); + try (OutputStream out = exchange.getResponseBody()) { + out.write(body); + } + }); + server.start(); + String url = + "http://" + + InetAddresses.toUriString(server.getAddress().getAddress()) + + ":" + + server.getAddress().getPort(); + Client.setDefaultBaseUrls(Optional.of(url), Optional.of(url)); + try { + LlmRequest.Builder request = + LlmRequest.builder() + .contents( + ImmutableList.of( + Content.builder().role("user").parts(Part.fromText("hello")).build())); + GenerateContentConfig config = configFor.apply(url); + if (config != null) { + request.config(config); + } + LlmResponse response = + modelFor.apply(url).generateContent(request.build(), /* stream= */ false).blockingLast(); + checkState(response.content().isPresent(), "The model returned no content."); + return received.get(); + } finally { + Client.setDefaultBaseUrls(Optional.empty(), Optional.empty()); + server.stop(0); + } + } + + /** Returns the ADK tags in {@code headers}' tracking header {@code name}. */ + static ImmutableList adkTags(Headers headers, String name) { + return Splitter.on(' ') + .splitToStream(headers.getFirst(name)) + .filter(tag -> tag.startsWith("google-adk/")) + .collect(ImmutableList.toImmutableList()); + } + + private LocalModelServer() {} +} diff --git a/core/src/test/java/com/google/adk/models/RuntimeTagTrackingHeadersTest.java b/core/src/test/java/com/google/adk/models/RuntimeTagTrackingHeadersTest.java new file mode 100644 index 0000000000..aa9d2ded5f --- /dev/null +++ b/core/src/test/java/com/google/adk/models/RuntimeTagTrackingHeadersTest.java @@ -0,0 +1,115 @@ +/* + * 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.CHAT_COMPLETION_JSON; +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.truth.Truth.assertThat; +import static org.junit.Assume.assumeNotNull; + +import com.google.genai.Client; +import com.google.genai.types.GenerateContentConfig; +import com.google.genai.types.HttpOptions; +import com.sun.net.httpserver.Headers; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** + * Tests the hosting runtime tag on the tracking headers that models send. Runs only with {@code + * K_SERVICE} set, as on Cloud Run, which the build sets for this test. + */ +@RunWith(JUnit4.class) +public final class RuntimeTagTrackingHeadersTest { + + private static final String CLOUD_RUN_ADK_TAG = TrackingHeaders.ADK_TAG + "+cloud_run"; + + @Before + public void setUp() { + assumeNotNull(System.getenv("K_SERVICE")); + } + + @Test + public void gemini_callerClient_sendsTheRuntimeTag() throws Exception { + assertAdkTag( + headersSentToLocalServer( + url -> + new Gemini( + "gemini-test", Client.builder().apiKey("test-api-key").vertexAI(false).build()), + GENERATE_CONTENT_JSON), + CLOUD_RUN_ADK_TAG); + } + + @Test + public void gemini_adkBuiltClient_sendsTheRuntimeTag() throws Exception { + assertAdkTag( + headersSentToLocalServer( + url -> Gemini.builder().modelName("gemini-test").apiKey("test-api-key").build(), + GENERATE_CONTENT_JSON), + CLOUD_RUN_ADK_TAG); + } + + @Test + public void value_withRuntimeTag_namesCloudRun() { + assertThat(TrackingHeaders.value(/* includeRuntimeTag= */ true)) + .startsWith(CLOUD_RUN_ADK_TAG + " gl-java/"); + } + + @Test + public void gemini_requestBaseUrlOutsideGoogleApis_sendsNoRuntimeTag() throws Exception { + assertAdkTag( + headersSentToLocalServer( + url -> + new Gemini( + "gemini-test", Client.builder().apiKey("test-api-key").vertexAI(false).build()), + url -> + GenerateContentConfig.builder() + .httpOptions(HttpOptions.builder().baseUrl(url).build()) + .build(), + GENERATE_CONTENT_JSON), + TrackingHeaders.ADK_TAG); + } + + @Test + public void apigeeGenAi_sendsNoRuntimeTag() throws Exception { + assertAdkTag( + headersSentToLocalServer( + url -> apigee("apigee/gemini/v1beta/gemini-test", url), GENERATE_CONTENT_JSON), + TrackingHeaders.ADK_TAG); + } + + @Test + public void apigeeChatCompletions_sendsNoRuntimeTag() throws Exception { + assertAdkTag( + headersSentToLocalServer(url -> apigee("apigee/openai/gpt-4o", url), CHAT_COMPLETION_JSON), + TrackingHeaders.ADK_TAG); + } + + private static BaseLlm apigee(String modelName, String proxyUrl) { + return ApigeeLlm.builder().modelName(modelName).proxyUrl(proxyUrl).build(); + } + + /** Asserts that both tracking headers carry exactly one ADK tag, {@code adkTag}. */ + private static void assertAdkTag(Headers headers, String adkTag) { + for (String name : TrackingHeaders.HEADER_NAMES) { + assertThat(adkTags(headers, name)).containsExactly(adkTag); + } + } +} diff --git a/core/src/test/java/com/google/adk/models/TrackingHeadersTest.java b/core/src/test/java/com/google/adk/models/TrackingHeadersTest.java index 9a934739cc..7707ba948f 100644 --- a/core/src/test/java/com/google/adk/models/TrackingHeadersTest.java +++ b/core/src/test/java/com/google/adk/models/TrackingHeadersTest.java @@ -18,7 +18,9 @@ import static com.google.common.base.StandardSystemProperty.JAVA_VERSION; import static com.google.common.truth.Truth.assertThat; +import static com.google.common.truth.Truth.assertWithMessage; +import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import org.junit.Test; import org.junit.runner.RunWith; @@ -27,6 +29,12 @@ @RunWith(JUnit4.class) public final class TrackingHeadersTest { + private static final ImmutableList RUNTIME_VARIABLES = + ImmutableList.of( + "GOOGLE_CLOUD_AGENT_ENGINE_ID", "K_SERVICE", "CLOUD_RUN_JOB", "KUBERNETES_SERVICE_HOST"); + private static final String GOOGLE_URL = "https://us-central1-aiplatform.googleapis.com"; + private static final String PROXY_URL = "https://proxy.example.com"; + @Test public void mergeInto_addsOnlyTheTagsACallerValueLacks() { ImmutableMap merged = @@ -34,7 +42,8 @@ public void mergeInto_addsOnlyTheTagsACallerValueLacks() { ImmutableMap.of( "User-Agent", "my-app/1.0 gl-java/11", "X-Goog-Api-Client", "my-lib/2.0 google-adk/0.0.1", - "X-Custom", "v")); + "X-Custom", "v"), + /* includeRuntimeTag= */ false); assertThat(merged) .containsExactly( @@ -45,6 +54,230 @@ public void mergeInto_addsOnlyTheTagsACallerValueLacks() { @Test public void mergeInto_noCallerValues_addsTrackingHeaders() { - assertThat(TrackingHeaders.mergeInto(ImmutableMap.of())).isEqualTo(TrackingHeaders.HEADERS); + String value = TrackingHeaders.ADK_TAG + " gl-java/" + JAVA_VERSION.value(); + + assertThat(TrackingHeaders.mergeInto(ImmutableMap.of(), /* includeRuntimeTag= */ false)) + .containsExactly("x-goog-api-client", value, "user-agent", value); + } + + @Test + public void value_withoutRuntimeTag_isThePlainAdkTagAndJavaTag() { + assertThat(TrackingHeaders.value(/* includeRuntimeTag= */ false)) + .isEqualTo(TrackingHeaders.ADK_TAG + " gl-java/" + JAVA_VERSION.value()); + } + + @Test + public void genAiSdkHeaders_withoutRuntimeTag_carryOnlyThePlainAdkTag() { + assertThat(TrackingHeaders.genAiSdkHeaders(/* includeRuntimeTag= */ false)) + .containsExactly( + "x-goog-api-client", TrackingHeaders.ADK_TAG, "user-agent", TrackingHeaders.ADK_TAG); + } + + @Test + public void runtimeTag_agentEngine() { + assertThat(runtimeTagWith("GOOGLE_CLOUD_AGENT_ENGINE_ID")).isEqualTo("remote_reasoning_engine"); + } + + @Test + public void runtimeTag_cloudRunService() { + assertThat(runtimeTagWith("K_SERVICE")).isEqualTo("cloud_run"); + } + + @Test + public void runtimeTag_cloudRunJob() { + assertThat(runtimeTagWith("CLOUD_RUN_JOB")).isEqualTo("cloud_run"); + } + + @Test + public void runtimeTag_cloudRunServiceAndJob() { + assertThat(runtimeTagWith("K_SERVICE", "CLOUD_RUN_JOB")).isEqualTo("cloud_run"); + } + + @Test + public void runtimeTag_kubernetes() { + assertThat(runtimeTagWith("KUBERNETES_SERVICE_HOST")).isEqualTo("k8s"); + } + + @Test + public void runtimeTag_cloudRunServiceOnKubernetes_isCloudRun() { + assertThat(runtimeTagWith("K_SERVICE", "KUBERNETES_SERVICE_HOST")).isEqualTo("cloud_run"); + } + + @Test + public void runtimeTag_cloudRunJobOnKubernetes_isCloudRun() { + assertThat(runtimeTagWith("CLOUD_RUN_JOB", "KUBERNETES_SERVICE_HOST")).isEqualTo("cloud_run"); + } + + @Test + public void runtimeTag_agentEngineWinsOverEveryOtherRuntime() { + assertThat(runtimeTagWith(RUNTIME_VARIABLES.toArray(new String[0]))) + .isEqualTo("remote_reasoning_engine"); + } + + @Test + public void runtimeTag_noVariables_isNull() { + assertThat(TrackingHeaders.runtimeTag(ImmutableMap.of()::get)).isNull(); + } + + @Test + public void runtimeTag_emptyValues_areIgnored() { + for (String name : RUNTIME_VARIABLES) { + assertThat(TrackingHeaders.runtimeTag(ImmutableMap.of(name, "")::get)).isNull(); + } + } + + @Test + public void runtimeTag_emptyAgentEngineId_fallsThroughToCloudRun() { + assertThat( + TrackingHeaders.runtimeTag( + ImmutableMap.of("GOOGLE_CLOUD_AGENT_ENGINE_ID", "", "K_SERVICE", "s")::get)) + .isEqualTo("cloud_run"); + } + + @Test + public void runtimeTag_emptyCloudRunService_fallsThroughToKubernetes() { + assertThat( + TrackingHeaders.runtimeTag( + ImmutableMap.of("K_SERVICE", "", "KUBERNETES_SERVICE_HOST", "h")::get)) + .isEqualTo("k8s"); } + + @Test + public void isGoogleApisUrl_googleApiHosts() { + ImmutableList urls = + ImmutableList.of( + "https://aiplatform.googleapis.com/v1", + "https://us-east5-aiplatform.googleapis.com", + "https://aiplatform.mtls.googleapis.com/v1", + "https://BigQuery.GoogleAPIs.com/v1", + "HTTPS://bigquery.googleapis.com/v1", + // A backslash outside the authority is fine. + "https://bigquery.googleapis.com/v1?q=a\\b", + "https://bigquery.googleapis.com/v1/a@b?q=c@d", + "https://bigquery.googleapis.com?q=a@b", + "https://bigquery.googleapis.com#a\\b"); + + for (String url : urls) { + assertWithMessage(url).that(TrackingHeaders.isGoogleApisUrl(url)).isTrue(); + } + } + + @Test + public void isGoogleApisUrl_otherDestinations() { + ImmutableList urls = + ImmutableList.of( + "http://aiplatform.googleapis.com/v1", + "https://notgoogleapis.com/v1", + "https://googleapis.com.evil.com/v1", + "https://api.anthropic.com", + // The apex is not a service endpoint. + "https://googleapis.com/v1", + "https://googleapis.com@evil.com/v1", + "https://user@bigquery.googleapis.com/v1", + "https://:secret@bigquery.googleapis.com/v1", + "https://@bigquery.googleapis.com/v1", + "https://evil.com\\.googleapis.com/v1", + "https://evil.com\\@bigquery.googleapis.com/v1", + "https://bigquery.googleapis.com\\@evil.com/v1", + "https://bigquery.googleapis.com\\evil.com/v1", + "https:\\\\bigquery.googleapis.com/v1", + "https:///aiplatform.googleapis.com/v1", + "https:///evil.com@aiplatform.googleapis.com/v1", + "https:///aiplatform.googleapis.com\\evil.com", + "not a url", + ""); + + for (String url : urls) { + assertWithMessage(url).that(TrackingHeaders.isGoogleApisUrl(url)).isFalse(); + } + } + + @Test + public void isGoogleApisUrl_null_isFalse() { + assertThat(TrackingHeaders.isGoogleApisUrl(null)).isFalse(); + } + + @Test + public void genAiTargetsGoogleApis_noBaseUrl_isTrue() { + boolean vertexAi = TrackingHeaders.genAiTargetsGoogleApis(null, true, name -> null); + boolean geminiApi = TrackingHeaders.genAiTargetsGoogleApis(null, false, name -> null); + + assertThat(vertexAi).isTrue(); + assertThat(geminiApi).isTrue(); + } + + @Test + public void genAiTargetsGoogleApis_requestBaseUrlOutsideGoogleApis_isFalse() { + assertThat(TrackingHeaders.genAiTargetsGoogleApis(PROXY_URL, true, name -> null)).isFalse(); + } + + @Test + public void genAiTargetsGoogleApis_requestBaseUrlWinsOverTheEnvironment() { + ImmutableMap proxyEnv = + ImmutableMap.of("GOOGLE_GEMINI_BASE_URL", PROXY_URL, "GOOGLE_VERTEX_BASE_URL", PROXY_URL); + + boolean vertexAi = TrackingHeaders.genAiTargetsGoogleApis(GOOGLE_URL, true, proxyEnv::get); + boolean geminiApi = TrackingHeaders.genAiTargetsGoogleApis(GOOGLE_URL, false, proxyEnv::get); + + assertThat(vertexAi).isTrue(); + assertThat(geminiApi).isTrue(); + } + + @Test + public void genAiTargetsGoogleApis_baseUrlVariables() { + ImmutableList cases = + ImmutableList.of( + new BaseUrlCase(true, "GOOGLE_VERTEX_BASE_URL", PROXY_URL, false), + new BaseUrlCase(true, "GOOGLE_VERTEX_BASE_URL", GOOGLE_URL, true), + new BaseUrlCase(true, "GOOGLE_VERTEX_BASE_URL", "", true), + new BaseUrlCase(true, "GOOGLE_GEMINI_BASE_URL", PROXY_URL, true), + new BaseUrlCase(false, "GOOGLE_GEMINI_BASE_URL", PROXY_URL, false), + new BaseUrlCase(false, "GOOGLE_GEMINI_BASE_URL", GOOGLE_URL, true), + new BaseUrlCase(false, "GOOGLE_GEMINI_BASE_URL", "", true), + new BaseUrlCase(false, "GOOGLE_VERTEX_BASE_URL", PROXY_URL, true)); + + for (BaseUrlCase c : cases) { + ImmutableMap env = ImmutableMap.of(c.variable(), c.url()); + assertWithMessage(c.toString()) + .that(TrackingHeaders.genAiTargetsGoogleApis(null, c.vertexAi(), env::get)) + .isEqualTo(c.targetsGoogleApis()); + } + } + + @Test + public void adkGenAiClientTargetsGoogleApis_eitherBaseUrlVariable() { + ImmutableList cases = + ImmutableList.of( + new BaseUrlCase(true, "GOOGLE_VERTEX_BASE_URL", GOOGLE_URL, true), + new BaseUrlCase(true, "GOOGLE_VERTEX_BASE_URL", PROXY_URL, false), + new BaseUrlCase(false, "GOOGLE_GEMINI_BASE_URL", GOOGLE_URL, true), + new BaseUrlCase(false, "GOOGLE_GEMINI_BASE_URL", PROXY_URL, false)); + + for (BaseUrlCase c : cases) { + ImmutableMap env = ImmutableMap.of(c.variable(), c.url()); + assertWithMessage(c.toString()) + .that(TrackingHeaders.adkGenAiClientTargetsGoogleApis(env::get)) + .isEqualTo(c.targetsGoogleApis()); + } + } + + @Test + public void adkGenAiClientTargetsGoogleApis_noBaseUrlVariable_isTrue() { + assertThat(TrackingHeaders.adkGenAiClientTargetsGoogleApis(name -> null)).isTrue(); + } + + /** + * Returns the runtime tag detected when only {@code names} are set, each to a non-empty value. + */ + private static String runtimeTagWith(String... names) { + ImmutableMap.Builder env = ImmutableMap.builder(); + for (String name : names) { + env.put(name, "set"); + } + return TrackingHeaders.runtimeTag(env.buildOrThrow()::get); + } + + /** A genai client's API, the one base URL variable set and its value, and the expected result. */ + private record BaseUrlCase( + boolean vertexAi, String variable, String url, boolean targetsGoogleApis) {} }