Skip to content
Merged
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
43 changes: 40 additions & 3 deletions core/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,11 @@
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<!-- a hosting runtime variable adds a suffix to the tracking headers tests assert; an
execution that sets its own list replaces this one, so it must repeat these -->
<excludedEnvironmentVariables>GOOGLE_CLOUD_AGENT_ENGINE_ID,K_SERVICE,CLOUD_RUN_JOB,KUBERNETES_SERVICE_HOST</excludedEnvironmentVariables>
</configuration>
<executions>
<execution>
<!-- run all tests with standard env -->
Expand Down Expand Up @@ -293,7 +298,7 @@
<GOOGLE_API_KEY>api-key</GOOGLE_API_KEY>
<GOOGLE_GENAI_USE_VERTEXAI>false</GOOGLE_GENAI_USE_VERTEXAI>
</environmentVariables>
<excludedEnvironmentVariables>GOOGLE_GENAI_USE_ENTERPRISE</excludedEnvironmentVariables>
<excludedEnvironmentVariables>GOOGLE_GENAI_USE_ENTERPRISE,GOOGLE_CLOUD_AGENT_ENGINE_ID,K_SERVICE,CLOUD_RUN_JOB,KUBERNETES_SERVICE_HOST</excludedEnvironmentVariables>
</configuration>
</execution>
<execution>
Expand All @@ -308,7 +313,7 @@
<!-- runs a second variant of the test method -->
<GOOGLE_GENAI_USE_VERTEXAI>true</GOOGLE_GENAI_USE_VERTEXAI>
</environmentVariables>
<excludedEnvironmentVariables>GOOGLE_GENAI_USE_ENTERPRISE</excludedEnvironmentVariables>
<excludedEnvironmentVariables>GOOGLE_GENAI_USE_ENTERPRISE,GOOGLE_CLOUD_AGENT_ENGINE_ID,K_SERVICE,CLOUD_RUN_JOB,KUBERNETES_SERVICE_HOST</excludedEnvironmentVariables>
</configuration>
</execution>
<execution>
Expand All @@ -322,7 +327,7 @@
<GOOGLE_API_KEY>api-key</GOOGLE_API_KEY>
<GOOGLE_GENAI_USE_ENTERPRISE>true</GOOGLE_GENAI_USE_ENTERPRISE>
</environmentVariables>
<excludedEnvironmentVariables>GOOGLE_GENAI_USE_VERTEXAI</excludedEnvironmentVariables>
<excludedEnvironmentVariables>GOOGLE_GENAI_USE_VERTEXAI,GOOGLE_CLOUD_AGENT_ENGINE_ID,K_SERVICE,CLOUD_RUN_JOB,KUBERNETES_SERVICE_HOST</excludedEnvironmentVariables>
</configuration>
</execution>
<execution>
Expand Down Expand Up @@ -353,6 +358,38 @@
</environmentVariables>
</configuration>
</execution>
<execution>
<id>runtime-tag-tracking-headers</id>
<goals>
<goal>test</goal>
</goals>
<configuration>
<test>RuntimeTagTrackingHeadersTest, ClaudeTest#generateContent_googleApiHost_sendsTheRuntimeTag+generateContent_otherHost_sendsNoRuntimeTag</test>
<!-- these tests run as on Cloud Run; Apigee genai reads the API key -->
<environmentVariables>
<GOOGLE_API_KEY>api-key</GOOGLE_API_KEY>
<K_SERVICE>test-service</K_SERVICE>
<GOOGLE_GENAI_USE_VERTEXAI>false</GOOGLE_GENAI_USE_VERTEXAI>
</environmentVariables>
<excludedEnvironmentVariables>GOOGLE_CLOUD_AGENT_ENGINE_ID,CLOUD_RUN_JOB,KUBERNETES_SERVICE_HOST,GOOGLE_GEMINI_BASE_URL,GOOGLE_VERTEX_BASE_URL</excludedEnvironmentVariables>
</configuration>
</execution>
<execution>
<id>base-url-runtime-tag</id>
<goals>
<goal>test</goal>
</goals>
<configuration>
<test>BaseUrlRuntimeTagTest</test>
<!-- these tests run as on Cloud Run with a Gemini API base URL outside Google APIs -->
<environmentVariables>
<K_SERVICE>test-service</K_SERVICE>
<GOOGLE_GEMINI_BASE_URL>https://proxy.example.com</GOOGLE_GEMINI_BASE_URL>
<GOOGLE_GENAI_USE_VERTEXAI>false</GOOGLE_GENAI_USE_VERTEXAI>
</environmentVariables>
<excludedEnvironmentVariables>GOOGLE_CLOUD_AGENT_ENGINE_ID,CLOUD_RUN_JOB,KUBERNETES_SERVICE_HOST,GOOGLE_VERTEX_BASE_URL</excludedEnvironmentVariables>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
Expand Down
5 changes: 3 additions & 2 deletions core/src/main/java/com/google/adk/models/ApigeeLlm.java
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
45 changes: 26 additions & 19 deletions core/src/main/java/com/google/adk/models/Claude.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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<String, String> 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<String> 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<String, String> 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<String> 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;
}

Expand Down
26 changes: 18 additions & 8 deletions core/src/main/java/com/google/adk/models/Gemini.java
Original file line number Diff line number Diff line change
Expand Up @@ -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());
}
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -312,7 +319,7 @@ private Flowable<LlmResponse> 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);
Expand All @@ -335,17 +342,20 @@ private Flowable<LlmResponse> 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()
.httpOptions(
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();
}
Expand Down
Loading
Loading